問題:航班乘客預測
數(shù)據(jù):1949 到 1960 一共 12 年酌予,每年 12 個月的數(shù)據(jù),一共 144 個數(shù)據(jù)呕寝,單位是 1000
下載地址
目標:預測國際航班未來 1 個月的乘客數(shù)
import numpy
import matplotlib.pyplot as plt
from pandas import read_csv
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
%matplotlib inline
導入數(shù)據(jù):
# load the dataset
dataframe = read_csv('international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
# 將整型變?yōu)閒loat
dataset = dataset.astype('float32')
plt.plot(dataset)
plt.show()
從這 12 年的數(shù)據(jù)可以看到上升的趨勢唠叛,每一年內的 12 個月里又有周期性季節(jié)性的規(guī)律
需要把數(shù)據(jù)做一下轉化:
將一列變成兩列,第一列是 t 月的乘客數(shù)腻贰,第二列是 t+1 列的乘客數(shù)。
look_back 就是預測下一步所需要的 time steps:
timesteps 就是 LSTM 認為每個輸入數(shù)據(jù)與前多少個陸續(xù)輸入的數(shù)據(jù)有聯(lián)系装诡。例如具有這樣用段序列數(shù)據(jù) “…ABCDBCEDF…”银受,當 timesteps 為 3 時,在模型預測中如果輸入數(shù)據(jù)為“D”鸦采,那么之前接收的數(shù)據(jù)如果為“B”和“C”則此時的預測輸出為 B 的概率更大宾巍,之前接收的數(shù)據(jù)如果為“C”和“E”,則此時的預測輸出為 F 的概率更大渔伯。
# X is the number of passengers at a given time (t) and Y is the number of passengers at the next time (t + 1).
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
# fix random seed for reproducibility
numpy.random.seed(7)
當激活函數(shù)為 sigmoid 或者 tanh 時顶霞,要把數(shù)據(jù)正則話,此時 LSTM 比較敏感
設定 67% 是訓練數(shù)據(jù)锣吼,余下的是測試數(shù)據(jù)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
X=t and Y=t+1 時的數(shù)據(jù)选浑,并且此時的維度為 [samples, features]
# use this function to prepare the train and test datasets for modeling
look_back = 1
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
投入到 LSTM 的 X 需要有這樣的結構: [samples, time steps, features],所以做一下變換
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
建立 LSTM 模型:
輸入層有 1 個input玄叠,隱藏層有 4 個神經(jīng)元古徒,輸出層就是預測一個值,激活函數(shù)用 sigmoid读恃,迭代 100 次隧膘,batch size 為 1
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
Epoch 100/100
1s - loss: 0.0020
預測:
# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
計算誤差之前要先把預測數(shù)據(jù)轉換成同一單位
# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
計算 mean squared error
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))
Train Score: 22.92 RMSE
Test Score: 47.53 RMSE
畫出結果:藍色為原數(shù)據(jù),綠色為訓練集的預測值寺惫,紅色為測試集的預測值
# shift train predictions for plotting
trainPredictPlot = numpy.empty_like(dataset)
trainPredictPlot[:, :] = numpy.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
# shift test predictions for plotting
testPredictPlot = numpy.empty_like(dataset)
testPredictPlot[:, :] = numpy.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
# plot baseline and predictions
plt.plot(scaler.inverse_transform(dataset))
plt.plot(trainPredictPlot)
plt.plot(testPredictPlot)
plt.show()
上面的結果并不是最佳的疹吃,只是舉一個例子來看 LSTM 是如何做時間序列的預測的
可以改進的地方,最直接的 隱藏層的神經(jīng)元個數(shù)是不是變?yōu)?128 更好呢西雀,隱藏層數(shù)是不是可以變成 2 或者更多呢萨驶,time steps 如果變成 3 會不會好一點
另外感興趣的筒子可以想想,RNN 做時間序列的預測到底好不好呢 ??
推薦閱讀 歷史技術博文鏈接匯總
http://www.reibang.com/p/28f02bb59fe5
也許可以找到你想要的