LSTM预测算法预测未来两个月数据python代码
时间: 2023-12-08 19:04:07 浏览: 77
下面是一个简单的LSTM预测算法的例子,可以预测未来两个月的数据。这个例子是基于Keras和TensorFlow的,你需要先安装这两个库。
```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')
# 取出需要预测的列
data = df['value'].values.reshape(-1, 1)
# 数据归一化
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=1):
data_x, data_y = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
data_x.append(a)
data_y.append(dataset[i + look_back, 0])
return np.array(data_x), np.array(data_y)
look_back = 30
train_x, train_y = create_dataset(train_data, look_back)
test_x, test_y = create_dataset(test_data, look_back)
# 转换为3维形式
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(50, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(train_x, train_y, epochs=100, batch_size=1, verbose=2)
# 预测未来两个月的数据
future_x = np.zeros((60, look_back, 1))
future_x[0:30, :, :] = train_x[-30:, :, :]
future_x[30:, :, :] = test_x[-30:, :, :]
future_y = np.zeros((60,))
for i in range(30, 60):
pred = model.predict(future_x[i-look_back:i, :, :])
future_y[i] = pred
future_y = scaler.inverse_transform(future_y.reshape(-1, 1))
# 可视化预测结果
plt.plot(data)
plt.plot(range(len(data)-30, len(data)+30), future_y)
plt.show()
```
这个例子假设你的数据存储在`data.csv`文件中,数据的格式是一个CSV文件,只有一列,名为`value`,每一行是一个数值。你可以根据自己的数据的格式修改代码中的数据读取和预处理部分。
阅读全文