1. 程式人生 > >Python時間序列LSTM預測系列學習筆記(9)-多變數

Python時間序列LSTM預測系列學習筆記(9)-多變數

本文是對:

https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/

https://blog.csdn.net/iyangdi/article/details/77881755

兩篇博文的學習筆記,兩個博主筆風都很浪,有些細節一筆帶過,本人以謙遜的態度進行了學習和整理,筆記內容都在程式碼的註釋中。有不清楚的可以去原博主文中檢視。

資料集下載:https://raw.githubusercontent.com/jbrownlee/Datasets/master/pollution.csv

後期我會補上我的github
 

本文算是正式的預測程式了,根據給出的資料,前部分作為訓練資料,後部分作為預測資料用。

由於資料量很大,最後輸出的預測圖會縮成一坨,拉伸放大來看就好了。

原博主iyangdi的程式碼對資料處理有問題,最後畫預測圖的時候會報錯,所以本文根據Jason Brownlee博士原文重新做了一遍資料處理,在執行後預測圖輸出正常,程式碼分為資料處理程式碼和資料預測程式碼兩部分,如下:

 

定義&訓練模型

1、資料劃分成訓練和測試資料
本教程用第一年資料做訓練,剩餘4年資料做評估
2、輸入=1時間步長,8個feature
3、第一層隱藏層節點=50,輸出節點=1
4、用平均絕對誤差MAE做損失函式、Adam的隨機梯度下降做優化
5、epoch=50, batch_size=72

模型評估

1、預測後需要做逆縮放
2、用RMSE做評估

 

資料預處理部分:

from pandas import read_csv
from datetime import datetime
# load data
def parse(x):
	return datetime.strptime(x, '%Y %m %d %H')
dataset = read_csv('data_set/raw.csv',  parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse)
dataset.drop('No', axis=1, inplace=True)
# manually specify column names
dataset.columns = ['pollution', 'dew', 'temp', 'press', 'wnd_dir', 'wnd_spd', 'snow', 'rain']
dataset.index.name = 'date'
# mark all NA values with 0
dataset['pollution'].fillna(0, inplace=True)
# drop the first 24 hours
dataset = dataset[24:]
# summarize first 5 rows
print(dataset.head(5))
# save to file
dataset.to_csv('data_set/pollution.csv')

 

資料預測部分

from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import numpy as np


#轉成有監督資料
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    #資料序列(也將就是input) input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
        #預測資料(input對應的輸出值) forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
    #拼接 put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # 刪除值為NAN的行 drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg


##資料預處理 load dataset
dataset = read_csv('data_set/pollution.csv', header=0, index_col=0)
values = dataset.values
#標籤編碼 integer encode direction
encoder = LabelEncoder()
values[:, 4] = encoder.fit_transform(values[:, 4])
#保證為float ensure all data is float
values = values.astype('float32')
#歸一化 normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
#轉成有監督資料 frame as supervised learning
reframed = series_to_supervised(scaled, 1, 1)
#刪除不預測的列 drop columns we don't want to predict
reframed.drop(reframed.columns[[9, 10, 11, 12, 13, 14, 15]], axis=1, inplace=True)
print(reframed.head())

#資料準備
#把資料分為訓練資料和測試資料 split into train and test sets
values = reframed.values
#拿一年的時間長度訓練
n_train_hours = 365 * 24
#劃分訓練資料和測試資料
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
#拆分輸入輸出 split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
#reshape輸入為LSTM的輸入格式 reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print ('train_x.shape, train_y.shape, test_x.shape, test_y.shape')
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

##模型定義 design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
#模型訓練 fit network
history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2,
                    shuffle=False)
#輸出 plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()

#進行預測 make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
#預測資料逆縮放 invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:, 0]
inv_yhat = np.array(inv_yhat)
#真實資料逆縮放 invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, 1:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:, 0]

#畫出真實資料和預測資料
pyplot.plot(inv_yhat,label='prediction')
pyplot.plot(inv_y,label='true')
pyplot.legend()
pyplot.show()

# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)