---
title: 'Time Series Prediction'
disqus: hackmd
---
###### tags: `410621240 資工三 徐翊峰`
# Time Series Prediction
---
#### Table of Contents
---
[TOC]
## 問題描述
---
- 
- 
- 這次問題主要是學習使用上課所教的**keras**來做**RNN**(Simple RNN, LSTM, GRU)的網路構建,還有學習使用基本的序列資料來做訓練**RNN**,藉此來學習一些基本的**keras**操作,還有預測下500筆資料。
## 問題解決步驟
---
### 1. 處理訓練資料
- 藉由下載老師提供的訓練資料,再加上對資料的前處理,包括把資料切成適當的大小,還有**reshape**成**model**好學習的大小,藉此來讓**model**的學習率提高。
```python=
data = np.loadtxt('A3_train.txt', delimiter='\n', dtype = np.float64)
x_train = np.array([data[i:i+50] for i in range(len(data)-50)])
y_train = np.array(data[50:])
x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
y_train = np.reshape(y_train, (y_train.shape[0], 1))
```
### 2. 建構神經網路
- 這次我們使用的是**keras.models**中的**Sequential**來建構這一次每一層的神經網路。
- 之中再配合著調整**model**中的一些參數和選擇不同的**RNN**模型和**Dropout**來藉此調高整個**model**的學習表現。
```python=
#buliding model 1
model = Sequential()
model.add(LSTM(64, input_shape = (1, 50)))
model.add(Dense(16, activation = 'relu'))
model.add(Dropout(0.15))
model.add(Dense(1, activation = 'relu'))
model.summary()
model.compile(optimizer = 'adam',
loss = 'mse',
metrics = ['mse', 'mae'])
```
- 我這次**RNN**選擇的是由**LSTM**層來做為主要建構與判斷序列資列的方式,後面再接**Dense**與**Dropout**。
### 3. 開始訓練model
- 使用**fit**就可以開始訓練**model**。
- 之後還可以調整**epochs**跟**batch_size**來讓model的學習表現更好。
```python=
train_history = model.fit(x_train, y_train,
epochs = 100,
batch_size = 30)
```
### 4. 畫出訓練次數與誤差
- 使用**python**的**matplotlib**來畫出**Training mse, lose, mae**的關係,藉此來查看整個model的訓練情況。
- 並且使用**plot_model**來畫出整個模型的建構。
```python=
mse = train_history.history['mean_squared_error']
mae = train_history.history['mean_absolute_error']
loss = train_history.history['loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, mse, label = 'Training mse')
plt.plot(epochs, mae, label = 'Training mae')
plt.plot(epochs, loss, label = 'Training loss')
plt.legend()
plt.grid()
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.title('Traning')
plt.savefig('evaluate model')
plt.show()
# plot model image
plot_model(model, to_file = 'model.png', show_layer_names = False, show_shapes = True)
```
- 之後就可以看到模型的訓練成果。
## 實驗結果
---
### 1. LSTM層架構成果
- 模型結構圖 :

- 模型評估變化圖 :

## 心得與結論
---
- 在我建完**model**後,不斷的調整裡面神經元個數與每一層**activation function**還有**RNN**的類型與**dropout**的比率的過程中:
- 我**LSTM**的訓練效果會比其他的訓練效果還要好,因此我會比較傾向用**LSTM**來構建這次的網路。
- 除此之外如果在**LSTM**後再加上一層**Dropout**會導致整個訓練效果沒有到很好,因此我後來就沒有選擇使用了。
- **Dropout**在後面的**Dense**也能帶來整體更好的效果。
- 我在這次做作業的過程中也再次更加了解了有關於**keras**的各種操作,與整個**RNN**模型的架構與使用時機,我覺得是一個很棒而且充實的過程。
> [name=徐翊峰]