安裝python工具包
找到C:\Windows\system32\cmd 右鍵 以管理員身份運(yùn)行
有些包需要管理員權(quán)限才能安裝
pip3 install --upgrade tensorflow (機(jī)器學(xué)習(xí)框架)
pip3 install --upgrade pandas (數(shù)據(jù)處理用的)
pip3 install --upgrade keras (機(jī)器學(xué)習(xí)封裝框架,可基于tensorflow)
pip3 install --upgrade sklearn (特征工程+模型訓(xùn)練)
pip3 install --upgrade matplotlib (畫圖)
pip3 install --upgrade jupyter (學(xué)習(xí)好幫手)
ps:有l(wèi)stm.rar的同學(xué)可走捷徑,可走特殊照顧渠道,使用juypter notebook 查看代碼
1、解壓lstm.rar 到lstm
2、win+r cmd 到lstm目錄
3、輸入 jupyter notebook
會(huì)默認(rèn)幫你打開瀏覽器
打開此文件,文章下面的東西在此界面都可查看并直接運(yùn)行
空氣污染預(yù)報(bào)
在本教程中,我們將使用空氣質(zhì)量數(shù)據(jù)集。
這是一個(gè)數(shù)據(jù)集,在美國駐北京的大使館五年內(nèi)每小時(shí)報(bào)告天氣和污染水平。
數(shù)據(jù)包括日期時(shí)間, PM2.5污染物,以及天氣信息,包括露點(diǎn)、溫度、氣壓、風(fēng)向、風(fēng)速以及降雨和降雪的累積小時(shí)數(shù)。原始數(shù)據(jù)中的完整功能列表如下:
1.No: 行號
2.year: 這一行的一年數(shù)據(jù)
3.month: 這一行的月數(shù)據(jù)
4.day: d這一行的日數(shù)據(jù)
5.hour: 這一行的小時(shí)數(shù)據(jù)
6.pm2.5: PM2.5濃度
7.DEWP: 露點(diǎn)
8.TEMP: 溫度
9.PRES:氣壓
10.cbwd: 組合風(fēng)向
11.Iws: 累積風(fēng)速
12.Is: 積雪時(shí)間
13.Ir: 累積的降雨時(shí)間
我們可以使用這些數(shù)據(jù)并構(gòu)建一個(gè)預(yù)測問題,鑒于天氣條件和前幾個(gè)小時(shí)的污染,我們預(yù)測下一個(gè)小時(shí)的污染。
你可以從UCI Machine Learning Repository下載數(shù)據(jù)集。傳送門壞了。。。。
?北京PM2.5數(shù)據(jù)集
下載數(shù)據(jù)集并將其放在你當(dāng)前的工作目錄中,文件名為“raw.csv”。
處理基礎(chǔ)數(shù)據(jù)
第一步是將日期時(shí)間信息整合到一個(gè)單獨(dú)的日期時(shí)間,以便我們可以將其用作Pandas的索引。
快速檢查顯示前24小時(shí)pm2.5的NA值。 因此,我們需要?jiǎng)h除第一行數(shù)據(jù),在數(shù)據(jù)集中還有幾個(gè)分散的“NA”值; 我們現(xiàn)在可以用0值標(biāo)記它們?;蛘哂胒illna來填充你需要的值。
以下腳本加載原始數(shù)據(jù)集,并將日期時(shí)間信息解析為Pandas DataFrame索引。No列被刪除,然后為每列指定更清晰的名稱。最后,將NA值替換為“0”值,并刪除前24小時(shí)。
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')
將數(shù)據(jù)集保存到“pollution.csv”。
查看數(shù)據(jù)
from pandas import read_csv
from matplotlib import pyplot
# load dataset
dataset = read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
print(dataset.head())
# 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()
dataset.head(5)
空氣污染時(shí)間序列線圖
多變量LSTM預(yù)測模型
清洗數(shù)據(jù),將數(shù)據(jù)集視為監(jiān)督學(xué)習(xí)問題并對輸入變量進(jìn)行歸一化
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
# 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())
運(yùn)行示例打印轉(zhuǎn)換后的數(shù)據(jù)集的前5行。我們可以看到8個(gè)輸入變量(輸入序列)和1個(gè)輸出變量(當(dāng)前小時(shí)的污染水平)
將數(shù)據(jù)集分成訓(xùn)練集和測試集
# 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)
定義并配置LSTM模型
我們將在第一個(gè)隱藏層中定義具有50個(gè)神經(jīng)元的LSTM以及輸出層中用于預(yù)測污染的的1個(gè)神經(jīng)元。輸入形式將是一個(gè)時(shí)間具有8個(gè)特征的步長。
我們將使用平均絕對誤差(MAE)損失函數(shù)和隨機(jī)梯度下降的高效Adam版本。
該模型將配置為適用于50個(gè)批量大小為72的訓(xùn)練周期。
最后,我們通過在fit()函數(shù)中設(shè)置validation_data參數(shù)來跟蹤訓(xùn)練過程中的訓(xùn)練和測試損失,然后在運(yùn)行結(jié)束時(shí),繪制訓(xùn)練和測試損失曲線圖。
from numpy import concatenate
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from matplotlib import pyplot
# 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()
評估模型
from math import sqrt
from sklearn.metrics import mean_squared_error
# 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)
pyplot.figure()
pyplot.subplot(2, 1, 1)
pyplot.plot(yhat[:,0],"b--",linewidth=1,color="red")
pyplot.subplot(2, 1, 2)
pyplot.plot(test_X[:, 0],"b--",linewidth=1)
pyplot.show()