LSTM预测未来的值,代码
时间: 2023-11-30 18:33:17 浏览: 194
以下是使用LSTM神经网络模型进行时间序列预测的Python代码示例:
``` python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载数据集
dataset = pd.read_csv('data.csv', header=None)
data = dataset.values
# 数据预处理
train_data = data[:800, :]
test_data = data[800:, :]
train_x, train_y = train_data[:, 0], train_data[:, 1]
test_x, test_y = test_data[:, 0], test_data[:, 1]
# 数据归一化处理
max_value = np.max(train_y)
min_value = np.min(train_y)
scalar = max_value - min_value
train_y = list(map(lambda x: x / scalar, train_y))
test_y = list(map(lambda x: x / scalar, test_y))
# 数据转换为LSTM的输入格式,即 [样本数,时间步长,特征数]
def create_dataset(dataset, lookback=1):
data_x, data_y = [], []
for i in range(len(dataset) - lookback):
data_x.append(dataset[i:(i+lookback)])
data_y.append(dataset[i+lookback])
return np.array(data_x), np.array(data_y)
lookback = 10
train_x, train_y = create_dataset(train_y, lookback)
test_x, test_y = create_dataset(test_y, lookback)
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, input_shape=(train_x.shape[1], train_x.shape[2])))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(train_x, train_y, epochs=100, batch_size=64, verbose=2)
# 预测结果
train_predict = model.predict(train_x)
test_predict = model.predict(test_x)
# 结果反归一化
train_predict = train_predict * scalar
train_y = train_y * scalar
test_predict = test_predict * scalar
test_y = test_y * scalar
# 画图展示结果
plt.plot(list(range(len(train_y))), train_y, color='blue')
plt.plot(list(range(len(train_predict))), train_predict, color='red')
plt.plot(list(range(len(train_y), len(train_y)+len(test_y))), test_y, color='blue')
plt.plot(list(range(len(train_y)+lookback, len(train_y)+len(test_predict)+lookback)), test_predict, color='red')
plt.show()
```
其中,`data.csv` 是包含时间序列数据的 CSV 文件,`lookback` 是指定的时间步长,`LSTM` 模型中的 `units` 表示 LSTM 层中的神经元个数。代码中使用了 `keras` 库来构建 LSTM 模型,并使用 `mean_squared_error` 作为损失函数,`adam` 作为优化器。最后使用 `matplotlib` 库来展示预测结果。
阅读全文