Skip to content

Commit a319df9

Browse files
authored
Add files via upload
1 parent 36d54e6 commit a319df9

File tree

1 file changed

+172
-0
lines changed

1 file changed

+172
-0
lines changed
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
用 LSTM 做时间序列预测的一个小例子
2+
3+
问题:航班乘客预测
4+
数据:1949 到 1960 一共 12 年,每年 12 个月的数据,一共 144 个数据,单位是 1000
5+
[下载地址](https://datamarket.com/data/set/22u3/international-airline-passengers-monthly-totals-in-thousands-jan-49-dec-60#!ds=22u3&display=line)
6+
目标:预测国际航班未来 1 个月的乘客数
7+
8+
```python
9+
import numpy
10+
import matplotlib.pyplot as plt
11+
from pandas import read_csv
12+
import math
13+
from keras.models import Sequential
14+
from keras.layers import Dense
15+
from keras.layers import LSTM
16+
from sklearn.preprocessing import MinMaxScaler
17+
from sklearn.metrics import mean_squared_error
18+
%matplotlib inline
19+
```
20+
21+
**导入数据:**
22+
23+
```python
24+
# load the dataset
25+
dataframe = read_csv('international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3)
26+
dataset = dataframe.values
27+
# 将整型变为float
28+
dataset = dataset.astype('float32')
29+
30+
plt.plot(dataset)
31+
plt.show()
32+
```
33+
34+
从这 12 年的数据可以看到上升的趋势,每一年内的 12 个月里又有周期性季节性的规律
35+
36+
![](http://upload-images.jianshu.io/upload_images/1667471-67cad20cda715361.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
37+
38+
**需要把数据做一下转化:**
39+
40+
将一列变成两列,第一列是 t 月的乘客数,第二列是 t+1 列的乘客数。
41+
look_back 就是预测下一步所需要的 time steps:
42+
43+
timesteps 就是 LSTM 认为每个输入数据与前多少个陆续输入的数据有联系。例如具有这样用段序列数据 “…ABCDBCEDF…”,当 timesteps 为 3 时,在模型预测中如果输入数据为“D”,那么之前接收的数据如果为“B”和“C”则此时的预测输出为 B 的概率更大,之前接收的数据如果为“C”和“E”,则此时的预测输出为 F 的概率更大。
44+
45+
```python
46+
# X is the number of passengers at a given time (t) and Y is the number of passengers at the next time (t + 1).
47+
48+
# convert an array of values into a dataset matrix
49+
def create_dataset(dataset, look_back=1):
50+
dataX, dataY = [], []
51+
for i in range(len(dataset)-look_back-1):
52+
a = dataset[i:(i+look_back), 0]
53+
dataX.append(a)
54+
dataY.append(dataset[i + look_back, 0])
55+
return numpy.array(dataX), numpy.array(dataY)
56+
57+
# fix random seed for reproducibility
58+
numpy.random.seed(7)
59+
```
60+
61+
当激活函数为 sigmoid 或者 tanh 时,要把数据正则话,此时 LSTM 比较敏感
62+
**设定 67% 是训练数据,余下的是测试数据**
63+
64+
```python
65+
# normalize the dataset
66+
scaler = MinMaxScaler(feature_range=(0, 1))
67+
dataset = scaler.fit_transform(dataset)
68+
69+
70+
# split into train and test sets
71+
train_size = int(len(dataset) * 0.67)
72+
test_size = len(dataset) - train_size
73+
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
74+
```
75+
76+
X=t and Y=t+1 时的数据,并且此时的维度为 [samples, features]
77+
78+
```python
79+
# use this function to prepare the train and test datasets for modeling
80+
look_back = 1
81+
trainX, trainY = create_dataset(train, look_back)
82+
testX, testY = create_dataset(test, look_back)
83+
```
84+
85+
投入到 LSTM 的 X 需要有这样的结构: [samples, time steps, features],所以做一下变换
86+
87+
```python
88+
# reshape input to be [samples, time steps, features]
89+
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
90+
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
91+
```
92+
93+
**建立 LSTM 模型:**
94+
输入层有 1 个input,隐藏层有 4 个神经元,输出层就是预测一个值,激活函数用 sigmoid,迭代 100 次,batch size 为 1
95+
96+
```python
97+
# create and fit the LSTM network
98+
model = Sequential()
99+
model.add(LSTM(4, input_shape=(1, look_back)))
100+
model.add(Dense(1))
101+
model.compile(loss='mean_squared_error', optimizer='adam')
102+
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
103+
```
104+
105+
Epoch 100/100
106+
1s - loss: 0.0020
107+
108+
**预测:**
109+
110+
```python
111+
# make predictions
112+
trainPredict = model.predict(trainX)
113+
testPredict = model.predict(testX)
114+
```
115+
116+
计算误差之前要先把预测数据转换成同一单位
117+
118+
```python
119+
# invert predictions
120+
trainPredict = scaler.inverse_transform(trainPredict)
121+
trainY = scaler.inverse_transform([trainY])
122+
testPredict = scaler.inverse_transform(testPredict)
123+
testY = scaler.inverse_transform([testY])
124+
```
125+
126+
**计算 mean squared error**
127+
128+
```python
129+
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
130+
print('Train Score: %.2f RMSE' % (trainScore))
131+
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
132+
print('Test Score: %.2f RMSE' % (testScore))
133+
```
134+
Train Score: 22.92 RMSE
135+
Test Score: 47.53 RMSE
136+
137+
画出结果:蓝色为原数据,绿色为训练集的预测值,红色为测试集的预测值
138+
139+
```python
140+
# shift train predictions for plotting
141+
trainPredictPlot = numpy.empty_like(dataset)
142+
trainPredictPlot[:, :] = numpy.nan
143+
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
144+
145+
# shift test predictions for plotting
146+
testPredictPlot = numpy.empty_like(dataset)
147+
testPredictPlot[:, :] = numpy.nan
148+
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
149+
150+
# plot baseline and predictions
151+
plt.plot(scaler.inverse_transform(dataset))
152+
plt.plot(trainPredictPlot)
153+
plt.plot(testPredictPlot)
154+
plt.show()
155+
```
156+
157+
![](http://upload-images.jianshu.io/upload_images/1667471-ad841e1d55d95e5b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
158+
159+
160+
上面的结果并不是最佳的,只是举一个例子来看 LSTM 是如何做时间序列的预测的
161+
可以改进的地方,最直接的 隐藏层的神经元个数是不是变为 128 更好呢,隐藏层数是不是可以变成 2 或者更多呢,time steps 如果变成 3 会不会好一点
162+
163+
另外感兴趣的筒子可以想想,RNN 做时间序列的预测到底好不好呢 🐌
164+
165+
参考资料:
166+
http://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/
167+
168+
---
169+
170+
推荐阅读 [历史技术博文链接汇总](http://www.jianshu.com/p/28f02bb59fe5)
171+
http://www.jianshu.com/p/28f02bb59fe5
172+
也许可以找到你想要的

0 commit comments

Comments
 (0)