Python时间序列LSTM预测系列学习笔记-BeijingPM2.5

Posted 常给自己加个油

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python时间序列LSTM预测系列学习笔记-BeijingPM2.5相关的知识,希望对你有一定的参考价值。

本文是对:

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
源码地址:https://github.com/yangwohenmai/LSTM/tree/master/LSTM%E7%B3%BB%E5%88%97/LSTM%E5%A4%9A%E5%8F%98%E9%87%8F3

本文算是正式的预测程序了,根据给出的数据,前部分作为训练数据,后部分作为预测数据用。

由于数据量很大,最后输出的预测图会缩成一坨,拉伸放大来看就好了。

原博主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)



————————————————
版权声明:本文为CSDN博主「日拱一两卒」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yangwohenmai1/article/details/84568510

以上是关于Python时间序列LSTM预测系列学习笔记-BeijingPM2.5的主要内容,如果未能解决你的问题,请参考以下文章

Keras深度学习实战(32)——基于LSTM预测股价

深度学习模型的准备和使用教程,LSTM用于锂电池SOH预测(第一节)(附Python的jypter源代码)

Keras深度学习实战(33)——基于LSTM的序列预测模型

技术 | 如何在Python下生成用于时间序列预测的LSTM状态

[时间序列预测]基于BPRNNLSTMCNN-LSTM算法多特征(多影响因素)用电负荷预测[保姆级手把手教学]

深度学习多变量时间序列预测:Encoder-Decoder LSTM算法构建时间序列多变量模型预测交通流量+代码实战