lstm滑动窗口预测python
时间: 2023-08-29 10:13:36 浏览: 215
下面是一个使用LSTM滑动窗口进行时间序列预测的Python示例:
```python
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 生成时间序列数据
def generate_data(n):
x = np.arange(0, 2*n, 2)
y = np.sin(x)
return x, y
# 将时间序列数据转换为监督学习数据
def to_supervised(data, window_size):
X, Y = [], []
for i in range(len(data)-window_size):
X.append(data[i:i+window_size])
Y.append(data[i+window_size])
return np.array(X), np.array(Y)
# 构建LSTM模型
def build_model(window_size):
model = Sequential()
model.add(LSTM(50, input_shape=(window_size, 1)))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
return model
# 训练LSTM模型
def train_model(model, X, Y, epochs):
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
model.fit(X, Y, epochs=epochs, batch_size=32, verbose=0)
# 使用LSTM模型进行预测
def predict(model, X):
X = np.reshape(X, (1, X.shape[0], 1))
yhat = model.predict(X, verbose=0)
return yhat[0]
# 生成数据
data = generate_data(100)
# 将数据转换为监督学习数据
window_size = 10
X, Y = to_supervised(data[1], window_size)
# 构建并训练LSTM模型
model = build_model(window_size)
train_model(model, X, Y, epochs=100)
# 使用LSTM模型进行预测
yhat = []
for i in range(window_size, len(data[1])):
X = data[1][i-window_size:i]
yhat.append(predict(model, X))
# 绘制预测结果
import matplotlib.pyplot as plt
plt.plot(data[0], data[1], label='Original')
plt.plot(data[0][window_size:], yhat, label='Predicted')
plt.legend()
plt.show()
```
该示例使用sin函数生成时间序列数据,然后将该数据转换为监督学习数据,并使用LSTM模型进行训练和预测。最后,使用matplotlib绘制出原始数据和预测结果。
阅读全文