---
# System prepended metadata

title: Time Series Prediction with RNN

---

---
title: 'Time Series Prediction with RNN'
disqus: hackmd
---

# Time Series Prediction with RNN


# Table of Contents

[TOC]


# 1.Preprocessing data
---
## 1.1 Read data
```python=
data = []

fp = open('raw.txt', "r")
line = fp.readline()
# 用 while 逐行讀取檔案內容，直至檔案結尾
while line:
    line=line.strip('\n')
    data.append(float(line))
    line = fp.readline()
fp.close()

data = np.array(data) # 轉成nparray
```

* 將data存成txt檔，並逐行讀入data。

## 1.2 Train data format transform
*  M : 50， N : 10。
```python=
M = 50
N = 10
train = []
train_s = [] #紀錄片段

for t in range(0, data.shape[0]-N-M+1): #要留M+N位置。

  for m in range(t,t+M): # M steps
    train_s.append(data[m:m+N]) # N data

  train.append(train_s)
  train_s = []
train = np.array(train)# 轉成nparray
```

## 1.2 Label data format transform
```python=
label = []
for t in range(M-1+N, data.shape[0]):#M要-1，因為index從0開始。
  label.append(data[t])

label = np.array(label)# 轉成nparray
label = label.reshape(label.shape[0], 1)# reshpae成二維

```

## 1.3 Result
```python=
print(train.shape)
print(label.shape)
```
Out: 
```
(941, 50, 10)
(941, 1)
```

# 2.Validation data
---
*  Rate : 0.1。
```python=
rate = 0.1
train_val = train[:int(train.shape[0]*rate)]
label_val = label[:int(label.shape[0]*rate)]
train_t = train[int(train.shape[0]*rate):]
label_t = label[int(label.shape[0]*rate):]
```
```python=
print(train_t.shape)
print(train_val.shape)
print(label_t.shape)
print(label_val.shape)
```

Out:
```
(847, 50, 10)
(94, 50, 10)
(847, 1)
(94, 1)
```

# 3.LSTM Network
---
## 3.1 Construct

```python=
model = Sequential()
model.add(LSTM(units=50, input_shape=(M, N)))
model.add(Dense(1))
model.compile(loss="mse", optimizer="adam",metrics=['accuracy'])
```
*  loss_function : mean square。
*  activation_function : adam。

## 3.2 Fit
```python=
model.fit(train_t,label_t, epochs = 1000, batch_size = 32, validation_data=(train_val, label_val))
```
*  epoch : 1000。
*  batch_size : 32。

## 3.3 Plot the result
```python=
plt.plot(label, color = 'red', label = 'Real ')  
plt.plot(predicted, color = 'blue', label = 'Predicted')  
plt.xlabel('Time')
plt.ylabel('y')
plt.legend()
plt.show()
```

Out:
* ![](https://i.imgur.com/bTZJZLO.png)
# 3.Output result
```python=
predicted_t = predicted.reshape(-1)
```
* 把predicted轉成一維。
```python=
fp = open("out.txt", "a")
for i in range(predicted.shape[0]):
    if i == predicted.shape[0]-1:
        fp.write(str(predicted_t[i]))
    else:
        fp.write(str(predicted_t[i])+',')
fp.close()
```
* 逐個寫入out.txt加上逗號。