基于Python,利用LSTM对时序数据进行提前多步预测,并用RMSE评估其结果代码】
时间: 2024-04-20 15:22:24 浏览: 107
【代码分享】手把手教你:基于LSTM的时序收益预测系统
5星 · 资源好评率100%
当然可以!以下是一个基于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 LSTM, Dense
# 读取数据
data = pd.read_csv('data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 构建训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size, :]
test_data = scaled_data[train_size:, :]
# 定义函数生成训练集和测试集
def create_dataset(dataset, look_back):
X, Y = [], []
for i in range(len(dataset) - look_back):
X.append(dataset[i:(i + look_back), 0])
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 10 # 设置时间步长
train_X, train_Y = create_dataset(train_data, look_back)
test_X, test_Y = create_dataset(test_data, look_back)
# 将输入数据重塑为LSTM的输入格式 [样本数,时间步长,特征数]
train_X = np.reshape(train_X, (train_X.shape[0], train_X.shape[1], 1))
test_X = np.reshape(test_X, (test_X.shape[0], test_X.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(look_back, 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=32)
# 预测数据
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)
# 反归一化
train_predict = scaler.inverse_transform(train_predict)
train_Y = scaler.inverse_transform([train_Y])
test_predict = scaler.inverse_transform(test_predict)
test_Y = scaler.inverse_transform([test_Y])
# 评估模型
from sklearn.metrics import mean_squared_error
train_rmse = np.sqrt(mean_squared_error(train_Y[0], train_predict[:, 0]))
test_rmse = np.sqrt(mean_squared_error(test_Y[0], test_predict[:, 0]))
print("训练集RMSE值:", train_rmse)
print("测试集RMSE值:", test_rmse)
```
请将代码中的`data.csv`替换为你的实际数据文件名,并根据需要进行调整。该代码通过LSTM模型进行多步预测,并使用均方根误差(RMSE)评估预测结果。
阅读全文