Python实现LSTM多变量多步滚动预测代码
时间: 2024-01-09 18:03:38 浏览: 96
LSTM多变量预测
以下是Python实现LSTM多变量多步滚动预测的代码示例:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载数据
df = pd.read_csv('data.csv', header=0, index_col=0)
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df.values)
# 定义函数将数据转换为多时步数据集
def create_dataset(dataset, time_steps=1):
X, y = [], []
for i in range(len(dataset) - time_steps):
X.append(dataset[i:(i + time_steps), :])
y.append(dataset[i + time_steps, 0])
return np.array(X), np.array(y)
# 设置时步和训练/测试集大小
time_steps = 3
train_size = int(len(scaled_data) * 0.75)
test_size = len(scaled_data) - train_size
# 创建训练/测试数据集
train_data = scaled_data[0:train_size, :]
test_data = scaled_data[train_size:len(scaled_data), :]
# 转换数据为多时步数据集
X_train, y_train = create_dataset(train_data, time_steps)
X_test, y_test = create_dataset(test_data, time_steps)
# 定义模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(units=50))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_test, y_test), verbose=2)
# 进行预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 反向转换预测结果
train_predict = scaler.inverse_transform(train_predict)
y_train = scaler.inverse_transform([y_train])
test_predict = scaler.inverse_transform(test_predict)
y_test = scaler.inverse_transform([y_test])
# 计算均方根误差
train_score = np.sqrt(mean_squared_error(y_train[0], train_predict[:, 0]))
print('Train RMSE: %.2f' % (train_score))
test_score = np.sqrt(mean_squared_error(y_test[0], test_predict[:, 0]))
print('Test RMSE: %.2f' % (test_score))
```
需要注意的是,此代码需要导入以下库:
- numpy
- pandas
- sklearn
- keras
其中,数据集应为csv格式,模型使用LSTM,使用均方根误差作为模型评估指标。
阅读全文