1. 程式人生 > >基於Keras的LSTM多變數時間序列預測(北京PM2.5資料集pollution.csv)

基於Keras的LSTM多變數時間序列預測(北京PM2.5資料集pollution.csv)

                             基於Keras的LSTM多變數時間序列預測

  傳統的線性模型難以解決多變數或多輸入問題,而神經網路如LSTM則擅長於處理多個變數的問題,該特性使其有助於解決時間序列預測問題。 
   
  在接下來的這篇部落格中,你將學會如何利用深度學習庫Keras搭建LSTM模型來處理多個變數的時間序列預測問題。 
  經過這個部落格你會掌握: 
  1. 如何將原始資料轉化為適合處理時序預測問題的資料格式; 
  2. 如何準備資料並搭建LSTM來處理時序預測問題; 
  3. 如何利用模型預測。 

1.空氣汙染預測

  在這篇部落格中,我們將採用空氣質量資料集。資料來源自位於北京的美國大使館在2010年至2014年共5年間每小時採集的天氣及空氣汙染指數。 
  資料集包括日期、PM2.5濃度、露點、溫度、風向、風速、累積小時雪量和累積小時雨量。原始資料中完整的特徵如下: 

1.No 行數
2.year 年
3.month 月
4.day 日
5.hour 小時
6.pm2.5 PM2.5濃度
7.DEWP 露點
8.TEMP 溫度
9.PRES 大氣壓
10.cbwd 風向
11.lws 風速
12.ls 累積雪量
13.lr 累積雨量

  我們可以利用此資料集搭建預測模型,利用前一個或幾個小時的天氣條件和汙染資料預測下一個(當前)時刻的汙染程度。 
   
  可以在UCI Machine Learning Repository下載資料集。 
  

Beijing PM2.5 Data Set

2.資料處理

  在使用資料之前需要對資料做一些處理,待處理部分資料如下:

No,year,month,day,hour,pm2.5,DEWP,TEMP,PRES,cbwd,Iws,Is,Ir
1,2010,1,1,0,NA,-21,-11,1021,NW,1.79,0,0
2,2010,1,1,1,NA,-21,-12,1020,NW,4.92,0,0
3,2010,1,1,2,NA,-21,-11,1019,NW,6.71,0,0
4,2010,1,1,3,NA,-21,-14,1019,NW,9.84,0,0
5,2010,1,1,4,NA,-20,-12,1018,NW,12.97,0,0

  粗略的觀察資料集會發現最開始的24小時PM2.5值都是NA,因此需要刪除這部分資料,對於其他時刻少量的預設值利用Pandas中的fillna填充;同時需要整合日期資料,使其作為Pandas中索引(index)。 
  下面的程式碼完成了以上的處理過程,同時去掉了原始資料中“No”列,並將列命名為更清晰的名字。

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('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('pollution.csv')

  處理後的資料儲存在“pollution.csv”檔案中,部分如下:

                     pollution  dew  temp   press wnd_dir  wnd_spd  snow  rain
date
2010-01-02 00:00:00      129.0  -16  -4.0  1020.0      SE     1.79     0     0
2010-01-02 01:00:00      148.0  -15  -4.0  1020.0      SE     2.68     0     0
2010-01-02 02:00:00      159.0  -11  -5.0  1021.0      SE     3.57     0     0
2010-01-02 03:00:00      181.0   -7  -5.0  1022.0      SE     5.36     1     0
2010-01-02 04:00:00      138.0   -7  -5.0  1022.0      SE     6.25     2     0

  現在的資料格式已經更加適合處理,可以簡單的對每列進行繪圖。下面的程式碼載入了“pollution.csv”檔案,並對除了類別型特性“風速”的每一列資料分別繪圖。

from pandas import read_csv
from matplotlib import pyplot
# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# specify columns to plot
groups = [0, 1, 2, 3, 5, 6, 7]
i = 1
# plot each column
pyplot.figure()
for group in groups:
    pyplot.subplot(len(groups), 1, i)
    pyplot.plot(values[:, group])
    pyplot.title(dataset.columns[group], y=0.5, loc='right')
    i += 1
pyplot.show()

  執行上述程式碼,並對7個變數在5年的範圍內繪圖。 
                

3.多變數LSTM預測模型

3.1 LSTM資料準備

  採用LSTM模型時,第一步需要對資料進行適配處理,其中包括將資料集轉化為有監督學習問題和歸一化變數(包括輸入和輸出值),使其能夠實現通過前一個時刻(t-1)的汙染資料和天氣條件預測當前時刻(t)的汙染。 
   
  以上的處理方式很直接也比較簡單,僅僅只是為了拋磚引玉,其他的處理方式也可以探索,比如: 
  1. 利用過去24小時的汙染資料和天氣條件預測當前時刻的汙染; 
  2. 預測下一個時刻(t+1)可能的天氣條件;
  下面程式碼中首先載入“pollution.csv”檔案,並利用sklearn的預處理模組對類別特徵“風向”進行編碼,當然也可以對該特徵進行one-hot編碼。 接著對所有的特徵進行歸一化處理,然後將資料集轉化為有監督學習問題,同時將需要預測的當前時刻(t)的天氣條件特徵移除,完整程式碼如下:

# convert series to supervised learning
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 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)]
    # 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
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# 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())

  執行上述程式碼,能看到被轉化後的資料集,資料集包括8個輸入變數(輸入特徵)和1個輸出變數(當前時刻t的空氣汙染值,標籤) 
  資料集的處理比較簡單,還有很多的方式可以嘗試,一些可以嘗試的方向包括: 
  1. 對“風向”特徵啞編碼; 
  2. 加入季節特徵; 
  3. 時間步長超過1。 
  其中,上述第三種方式對於處理時間序列問題的LSTM可能是最重要的。

3.2 構造模型

  在這一節,我們將構造LSTM模型。 
  首先,我們需要將處理後的資料集劃分為訓練集和測試集。為了加速模型的訓練,我們僅利用第一年資料進行訓練,然後利用剩下的4年進行評估。 
  下面的程式碼將資料集進行劃分,然後將訓練集和測試集劃分為輸入和輸出變數,最終將輸入(X)改造為LSTM的輸入格式,即[samples,timesteps,features]。

# 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 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)
  • 、執行上述程式碼列印訓練集和測試集的輸入輸出格式:
(8760, 1, 8) (8760,) (35039, 1, 8) (35039,)

  現在可以搭建LSTM模型了。 
  LSTM模型中,隱藏層有50個神經元,輸出層1個神經元(迴歸問題),輸入變數是一個時間步(t-1)的特徵,損失函式採用Mean Absolute Error(MAE),優化演算法採用Adam,模型採用50個epochs並且每個batch的大小為72。 
  最後,在fit()函式中設定validation_data引數,記錄訓練集和測試集的損失,並在完成訓練和測試後繪製損失圖。

# 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=50, 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()

# 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=50, 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()

3.3 模型評估

  接下里我們對模型效果進行評估。 
  值得注意的是:需要將預測結果和部分測試集資料組合然後進行比例反轉(invert the scaling),同時也需要將測試集上的預期值也進行比例轉換。 
  通過以上處理之後,再結合RMSE(均方根誤差)計算損失。

# 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]
# 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]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

        整個專案完整程式碼如下:

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

# convert series to supervised learning
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 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)]
    # 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
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# 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 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)

# 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=50, 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]
# 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]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

      行以上程式碼,首先將會繪製訓練過程中的訓練和測試損失圖。 

   
               

       訓練中的每個epoch都會記錄和繪製訓練集和測試集的損失,並在整個訓練結束後繪製模型最終的RMSE。 下圖中可以看到,整個模型的RMSE達到26.496。

...
Epoch 46/50
0s - loss: 0.0143 - val_loss: 0.0133
Epoch 47/50
0s - loss: 0.0143 - val_loss: 0.0133
Epoch 48/50
0s - loss: 0.0144 - val_loss: 0.0133
Epoch 49/50
0s - loss: 0.0143 - val_loss: 0.0133
Epoch 50/50
0s - loss: 0.0144 - val_loss: 0.0133
Test RMSE: 26.496
  • 這個模型沒有調優。你能做得更好嗎?請在下面的評論中告訴我您的問題框架、模型配置和RMSE。


    更新:培訓多個滯後時間步驟的例子

           對於如何根據前面的多個時間步驟調整上面的示例來培訓模型,已經有許多人提出了建議。在撰寫最初的文章時,我嘗試過這個方法和無數其他配置,但我決定不包含它們,因為它們沒有提升模型技能。儘管如此,我在下面提供了這個示例作為參考模板,您可以根據自己的問題進行調整。在之前的多個時間步驟中訓練模型所需的更改非常少,如下所示:首先,在呼叫series_to_supervised()時,必須適當地構造問題。我們將使用3小時的資料作為輸入。還要注意,我們不再顯式地從ob(t)的所有其他欄位刪除列。

# specify the number of lag hours
n_hours = 3
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, 1)

   接下來,在指定輸入和輸出列時需要更加小心。我們的框架資料集中有3 * 8 + 8列。我們將以3 * 8或24列作為前3小時所有特性的obs的輸入。我們僅將汙染變數作為下一小時的輸出,如下所示:

 

# split into input and outputs
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, -n_features]
test_X, test_y = test[:, :n_obs], test[:, -n_features]
print(train_X.shape, len(train_X), train_y.shape)

   接下來,我們可以正確地重塑輸入資料,以反映時間步驟和特徵。 

# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))

     模型擬合是一樣的。唯一的另一個小變化是如何評估模型。具體來說,就是我們如何重構具有8列的行,這些行適合於反轉縮放操作,從而將y和yhat返回到原始的縮放中,這樣我們就可以計算RMSE。更改的要點是,我們將y或yhat列與測試資料集的最後7個特性連線起來,以便反向縮放,如下所示:

# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]

        我們可以將所有這些修改與上面的示例聯絡在一起。多元時序多時滯輸入預測的完整例子如下:

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

# convert series to supervised learning
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 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)]
	# 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
	# drop rows with NaN values
	if dropnan:
		agg.dropna(inplace=True)
	return agg

# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_hours = 3
n_features = 8
# frame as supervised learning
reframed = series_to_supervised(scaled, n_hours, 1)
print(reframed.shape)

# 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
n_obs = n_hours * n_features
train_X, train_y = train[:, :n_obs], train[:, -n_features]
test_X, test_y = test[:, :n_obs], test[:, -n_features]
print(train_X.shape, len(train_X), train_y.shape)
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_hours, n_features))
test_X = test_X.reshape((test_X.shape[0], n_hours, n_features))
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=50, 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], n_hours*n_features))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

      擬合完成後輸出如下:

...
Epoch 45/50
1s - loss: 0.0143 - val_loss: 0.0154
Epoch 46/50
1s - loss: 0.0143 - val_loss: 0.0148
Epoch 47/50
1s - loss: 0.0143 - val_loss: 0.0152
Epoch 48/50
1s - loss: 0.0143 - val_loss: 0.0151
Epoch 49/50
1s - loss: 0.0143 - val_loss: 0.0152
Epoch 50/50
1s - loss: 0.0144 - val_loss: 0.0149

     訓練集和測試集上的損失繪製如下圖所示:

                       

        最後,RMSE測試被打印出來,並沒有顯示出任何技巧上的優勢,至少在這個問題上沒有。

       

Test RMSE: 27.177

       我想補充一點,LSTM似乎不適用於自迴歸型別問題,您最好使用一個大視窗來研究MLP。我希望這個例子可以幫助您完成自己的時間序列預測實驗。