给我生成一段lstm时间序列预测代码
时间: 2024-10-12 22:12:15 浏览: 28
LSTM(Long Short-Term Memory)是一种特殊的循环神经网络结构,常用于处理时间序列数据。以下是使用Keras库在Python中编写的一个简单LSTM时间序列预测代码示例。这里我们假设我们要预测股市收盘价:
```python
# 导入所需的库
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# 假设df是包含时间序列数据的DataFrame
df = ... # 你需要填充实际的数据读取部分
# 数据预处理
data = df['Close'].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, test_data = scaled_data[0:train_size], scaled_data[train_size:]
# 将数据分割成X(输入)和y(目标)
def create_dataset(dataset, look_back=1):
X, y = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
X.append(a)
y.append(dataset[i + look_back, 0])
return np.array(X), np.array(y)
look_back = 5
X_train, y_train = create_dataset(train_data, look_back)
X_test, y_test = create_dataset(test_data, look_back)
# reshape input to be [samples, time steps, features]
X_train = np.reshape(X_train, (X_train.shape[0], 1, look_back))
X_test = np.reshape(X_test, (X_test.shape[0], 1, look_back))
# 创建模型
model = Sequential()
model.add(LSTM(50, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=2)
# 预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 反归一化预测结果
train_predict = scaler.inverse_transform(train_predict)
y_train = scaler.inverse_transform([y_train])
test_predict = scaler.inverse_transform(test_predict)
y_test = scaler.inverse_transform([y_test])
# 打印相关问题
阅读全文