请给我一个LSTM代码实例
时间: 2024-05-28 08:04:40 浏览: 42
LSTM-MATLAB-master_lstm代码_LSTM_lstmmatlab_LSTMMATLAB代码_LSTM-MATL
5星 · 资源好评率100%
这是一个简单的LSTM代码实例,用于预测时间序列数据:
```
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 加载数据
data = pd.read_csv('data.csv')
# 准备数据
X = np.array(data['input'])
y = np.array(data['output'])
# 将数据划分为训练集和测试集
train_size = int(len(X) * 0.67)
test_size = len(X) - train_size
train_X, test_X = X[0:train_size,:], X[train_size:len(X),:]
train_y, test_y = y[0:train_size], y[train_size:len(y)]
# 将训练集和测试集变为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(50, input_shape=(1, 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)
# 对测试集进行预测
predictions = model.predict(test_X)
predictions = predictions.reshape((predictions.shape[0],))
# 计算误差
mse = np.mean((predictions - test_y) ** 2)
# 输出结果
print('MSE:', mse)
```
阅读全文