【发布时间】:2020-11-26 00:05:04
【问题描述】:
我是机器学习的新手,我正在使用 Keras 中的 LSTM 执行多元时间序列预测。我有一个包含 4 个输入变量(温度、降水、露水和风速)和 1 个输出变量(污染)的月度时间序列数据集。使用这些数据,我构建了一个预测问题,考虑到前几个月的天气状况和污染,我预测下个月的污染。下面是我的代码
X = df[['Temperature', 'Precipitation', 'Dew', 'Wind_speed' ,'Pollution (t_1)']].values
y = df['Pollution (t)'].values
y = y.reshape(-1,1)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(X)
#dataset has 359 samples in total
train_X, train_y = X[:278], y[:278]
test_X, test_y = X[278:], y[278:]
# 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)
model = Sequential()
model.add(LSTM(100, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dropout(0.2))
# model.add(LSTM(70))
# model.add(Dropout(0.3))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
history = model.fit(train_X, train_y, epochs=700, batch_size=70, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
要进行预测,我使用以下代码
from sklearn.metrics import mean_squared_error,r2_score
yhat = model.predict(test_X)
mse = mean_squared_error(test_y, yhat)
rmse = np.sqrt(mse)
r2 = r2_score(test_y, yhat)
print("test set performance")
print("--------------------")
print("MSE:",mse)
print("RMSE:",rmse)
print("R^2: ",r2)
fig, ax = plt.subplots(figsize=(10,5))
ax.plot(range(len(test_y)), test_y, '-b',label='Actual')
ax.plot(range(len(yhat)), yhat, 'r', label='Predicted')
plt.legend()
plt.show()
运行这段代码我遇到了以下问题:
- 由于某种原因,我的测试集得到了一个滞后的结果,该结果不在我的训练数据中,如下图所示。我不明白为什么我有这些滞后的结果(这是否与将“污染(t_1)”作为我的输入的一部分有关)?
图表结果:
- 通过添加“污染 (t_1)”,这是污染变量的 1 滞后作为我的输入的一部分,这个变量现在似乎主导了预测,因为删除其他变量似乎对我的结果没有影响(r -squared 和 rmse),这很奇怪,因为所有这些变量都有助于污染预测。
我的代码中是否有什么问题是导致这些问题的原因?我是 python 新手,因此对于回答上述 2 个问题的任何帮助将不胜感激。
【问题讨论】:
-
我认为你得到了错误的重塑。 Timesteps (reshape train_x.shape[1]) 在 LSTM 模型上最好超过 3 或 4,并且 Samples 可能相当于批量数。因此,我认为像
这样的脚本可以解决您的问题 -
@GenzoIto 你的意思是我应该用
train_X = train_X.reshape(-1, 4, train_X.shape[1])替换train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))吗?因为那给了我以下错误ValueError: cannot reshape array of size 1390 into shape (4,5). -
如果我运行
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)我得到:(278, 1, 5) (278, 1) (81, 1, 5) (81, 1) -
我发布一个答案,希望你能解决问题
标签: python tensorflow keras time-series lstm