用python语言给出LSTM时间序列预测算法
时间: 2023-06-01 14:02:57 浏览: 109
以下是一个LSTM时间序列预测算法的Python实现:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 准备数据
data = pd.read_csv('data.csv', usecols=[1])
dataset = data.values
dataset = dataset.astype('float32')
dataset /= np.max(dataset)
# 划分数据集
train_size = int(len(dataset) * 0.7)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
# 将数据转换为监督学习问题
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
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, look_back)
test_X, test_Y = create_dataset(test, look_back)
# 转换数据为LSTM需要的三维格式
train_X = np.reshape(train_X, (train_X.shape[0], 1, train_X.shape[1]))
test_X = np.reshape(test_X, (test_X.shape[0], 1, test_X.shape[1]))
# 创建LSTM模型
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
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)
# 用模型预测
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)
# 反归一化
train_predict = train_predict * np.max(dataset)
train_Y = train_Y * np.max(dataset)
test_predict = test_predict * np.max(dataset)
test_Y = test_Y * np.max(dataset)
# 计算误差
train_score = np.sqrt(np.mean(np.square(train_predict - train_Y)))
test_score = np.sqrt(np.mean(np.square(test_predict - test_Y)))
print('Train Score: %.2f RMSE' % (train_score))
print('Test Score: %.2f RMSE' % (test_score))
```
这段代码首先准备了一个时间序列数据集,然后将其划分为训练集和测试集,接着将数据转换为监督学习问题,使用LSTM模型进行训练,并进行预测。最后计算了训练集和测试集的误差。注意,在这个例子中,我们使用了一个3时间步长的滑动窗口来预测下一个时间步长的值。
阅读全文