lstm时间序列预测python的代码
时间: 2023-06-01 16:01:51 浏览: 102
以下是使用LSTM模型进行时间序列预测的Python代码示例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 读取数据
df = pd.read_csv('data.csv', parse_dates=['date'], index_col='date')
# 数据归一化处理
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(df.values)
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size, :]
test_data = data[train_size:, :]
# 将数据转换为时间序列数据
def create_dataset(dataset, look_back=1):
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 = 3
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, input_shape=(look_back, 1)))
model.add(Dense(units=1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
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])
# 计算RMSE误差
train_rmse = np.sqrt(np.mean(np.power(train_Y - train_predict, 2)))
print('Train RMSE: %.2f' % train_rmse)
test_rmse = np.sqrt(np.mean(np.power(test_Y - test_predict, 2)))
print('Test RMSE: %.2f' % test_rmse)
# 可视化结果
train_predict_plot = np.empty_like(data)
train_predict_plot[:, :] = np.nan
train_predict_plot[look_back:len(train_predict)+look_back, :] = train_predict
test_predict_plot = np.empty_like(data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict)+(look_back*2):len(data), :] = test_predict
plt.plot(scaler.inverse_transform(data))
plt.plot(train_predict_plot)
plt.plot(test_predict_plot)
plt.show()
```
其中,`data.csv`为时间序列数据文件,包含日期和数值两列。代码中使用了LSTM模型进行预测,并将预测结果可视化展示出来。
阅读全文