上一篇搭建的是单时间步长LSTM,但有的时候我们可能需要用以前几个小时的数据来预测下一个小时的数据,这时候就为多时间步长。
程序上一篇里我已经贴的很详细了,由单时间步长到多时间步长只需要在这基础上稍微修改一下就可以了
1、准备数据:
scaler_for_x=MinMaxScaler(feature_range=(0,1))
data_ = scaler_for_x.fit_transform(data) #最大最小归一化
normalize_data = data_[0:50000,:]#训练集50000小时
normalize_data_test = data_[50000:50500,:]#测试集500小时
print(normalize_data_test.shape)
time_step = 20 #由前20小时的数据预测下一小时数据
train_x,train_y=[],[] #训练集
test_x,test_y=[],[] #训练集
for i in range(len(normalize_data)-time_step-1):
x=normalize_data[i:i+time_step]
y=normalize_data[i+time_step+1]
train_x.append(x.tolist())
train_y.append(y.tolist())
for i in range(len(normalize_data_test)-time_step-1):
x1=normalize_data_test[i:i+time_step]
y1=normalize_data_test[i+time_step+1]
test_x.append(x1.tolist())
test_y.append(y1.tolist())
train_x = np.array(train_x)
train_y = np.array(train_y)[:,-1]
test_x = np.array(test_x)
test_y = np.array(test_y)[:,-1]
print(train_x.shape, train_y.shape, test_x.shape, test_y.shape)
输出结果为:(49979, 20, 1) (49979,) (479, 20, 1) (479,)
2、预测并输出RMSE
# make a prediction
yhat = model.predict(test_x)
test_x = test_x.reshape((test_x.shape[0], test_x.shape[1]*test_x.shape[2]))
print(yhat.shape)
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_x[:, 1:]), axis=1)#按行的方式进行组合
inv_yhat = scaler_for_x.inverse_transform(inv_yhat)#反变换
inv_yhat = inv_yhat[:,0]
test_y = test_y[:,np.newaxis]
# invert scaling for actual
inv_y = scaler_for_x.inverse_transform(test_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)
附上前一篇链接:https://blog.csdn.net/FUCCKL/article/details/88687365
希望对大家有所帮助!