写一段LSTM预测模型的代码
时间: 2023-10-24 12:39:14 浏览: 95
好的,以下是使用Python和Keras构建LSTM预测模型的示例代码:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
# 读取数据
df = pd.read_csv('data.csv')
# 将数据转化为numpy数组
data = df.values
# 将数据缩放到0和1之间
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 分割数据为训练集和测试集
train_size = int(len(data) * 0.8)
test_size = len(data) - train_size
train, test = data[0:train_size,:], data[train_size:len(data),:]
# 将数据转化为时间序列数据
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 = 3
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# 转化为LSTM输入格式 [样本数, 时间步数, 特征数]
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(4, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 评估模型
train_score = model.evaluate(trainX, trainY, verbose=0)
test_score = model.evaluate(testX, testY, verbose=0)
print('Train Score: %.2f MSE (%.2f RMSE)' % (train_score, np.sqrt(train_score)))
print('Test Score: %.2f MSE (%.2f RMSE)' % (test_score, np.sqrt(test_score)))
# 预测未来值
future = np.array([0.1, 0.2, 0.3])
future = scaler.transform(future.reshape(-1, 1))
future = np.reshape(future, (1, look_back, 1))
prediction = model.predict(future, verbose=0)
print('Future prediction:', scaler.inverse_transform(prediction))
```
以上代码将数据缩放到0和1之间,使用前3个时间步作为输入,训练了一个LSTM模型,并使用该模型预测了未来值。在实际应用中,需要根据具体情况调整数据预处理、模型架构和训练参数等参数。
阅读全文