当前位置:   article > 正文

Python时间序列LSTM预测系列学习笔记(9)-多变量_scaler 多变量

scaler 多变量

本文是对:

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做评估

 

数据预处理部分:

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

 

数据预测部分

  1. from math import sqrt
  2. from numpy import concatenate
  3. from matplotlib import pyplot
  4. from pandas import read_csv
  5. from pandas import DataFrame
  6. from pandas import concat
  7. from sklearn.preprocessing import MinMaxScaler
  8. from sklearn.preprocessing import LabelEncoder
  9. from sklearn.metrics import mean_squared_error
  10. from keras.models import Sequential
  11. from keras.layers import Dense
  12. from keras.layers import LSTM
  13. import numpy as np
  14. #转成有监督数据
  15. def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
  16. n_vars = 1 if type(data) is list else data.shape[1]
  17. df = DataFrame(data)
  18. cols, names = list(), list()
  19. #数据序列(也将就是input) input sequence (t-n, ... t-1)
  20. for i in range(n_in, 0, -1):
  21. cols.append(df.shift(i))
  22. names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
  23. #预测数据(input对应的输出值) forecast sequence (t, t+1, ... t+n)
  24. for i in range(0, n_out):
  25. cols.append(df.shift(-i))
  26. if i == 0:
  27. names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
  28. else:
  29. names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
  30. #拼接 put it all together
  31. agg = concat(cols, axis=1)
  32. agg.columns = names
  33. # 删除值为NAN的行 drop rows with NaN values
  34. if dropnan:
  35. agg.dropna(inplace=True)
  36. return agg
  37. ##数据预处理 load dataset
  38. dataset = read_csv('data_set/pollution.csv', header=0, index_col=0)
  39. values = dataset.values
  40. #标签编码 integer encode direction
  41. encoder = LabelEncoder()
  42. values[:, 4] = encoder.fit_transform(values[:, 4])
  43. #保证为float ensure all data is float
  44. values = values.astype('float32')
  45. #归一化 normalize features
  46. scaler = MinMaxScaler(feature_range=(0, 1))
  47. scaled = scaler.fit_transform(values)
  48. #转成有监督数据 frame as supervised learning
  49. reframed = series_to_supervised(scaled, 1, 1)
  50. #删除不预测的列 drop columns we don't want to predict
  51. reframed.drop(reframed.columns[[9, 10, 11, 12, 13, 14, 15]], axis=1, inplace=True)
  52. print(reframed.head())
  53. #数据准备
  54. #把数据分为训练数据和测试数据 split into train and test sets
  55. values = reframed.values
  56. #拿一年的时间长度训练
  57. n_train_hours = 365 * 24
  58. #划分训练数据和测试数据
  59. train = values[:n_train_hours, :]
  60. test = values[n_train_hours:, :]
  61. #拆分输入输出 split into input and outputs
  62. train_X, train_y = train[:, :-1], train[:, -1]
  63. test_X, test_y = test[:, :-1], test[:, -1]
  64. #reshape输入为LSTM的输入格式 reshape input to be 3D [samples, timesteps, features]
  65. train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
  66. test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
  67. print ('train_x.shape, train_y.shape, test_x.shape, test_y.shape')
  68. print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
  69. ##模型定义 design network
  70. model = Sequential()
  71. model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
  72. model.add(Dense(1))
  73. model.compile(loss='mae', optimizer='adam')
  74. #模型训练 fit network
  75. history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2,
  76. shuffle=False)
  77. #输出 plot history
  78. pyplot.plot(history.history['loss'], label='train')
  79. pyplot.plot(history.history['val_loss'], label='test')
  80. pyplot.legend()
  81. pyplot.show()
  82. #进行预测 make a prediction
  83. yhat = model.predict(test_X)
  84. test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
  85. #预测数据逆缩放 invert scaling for forecast
  86. inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
  87. inv_yhat = scaler.inverse_transform(inv_yhat)
  88. inv_yhat = inv_yhat[:, 0]
  89. inv_yhat = np.array(inv_yhat)
  90. #真实数据逆缩放 invert scaling for actual
  91. test_y = test_y.reshape((len(test_y), 1))
  92. inv_y = concatenate((test_y, test_X[:, 1:]), axis=1)
  93. inv_y = scaler.inverse_transform(inv_y)
  94. inv_y = inv_y[:, 0]
  95. #画出真实数据和预测数据
  96. pyplot.plot(inv_yhat,label='prediction')
  97. pyplot.plot(inv_y,label='true')
  98. pyplot.legend()
  99. pyplot.show()
  100. # calculate RMSE
  101. rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
  102. print('Test RMSE: %.3f' % rmse)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/185826
推荐阅读
相关标签
  

闽ICP备14008679号