import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.callbacks import EarlyStopping
# 假设有一组已知的时间序列数据
data = np.array([[10, 20, 30, 40, 50],
[15, 25, 35, 45, 55],
[20, 30, 40, 50, 60],
[25, 35, 45, 55, 65]])
# 将数据集划分为训练集和测试集
train_size = int(len(data) * 0.67)
test_size = len(data) - train_size
train, test = data[0:train_size, :], data[train_size:len(data), :]
# 对数据进行归一化处理
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
train_scaled = scaler.fit_transform(train)
test_scaled = scaler.transform(test)
# 转换为LSTM网络需要的输入格式
def create_X_Y(data, lag=1):
X, Y = [], []
for i in range(len(data) - lag):
X.append(data[i:i+lag, :])
Y.append(data[i+lag, :])
return np.array(X), np.array(Y)
# 创建输入和输出数据
lag = 1 # 指定需要用多少个时间点作为输入
trainX, trainY = create_X_Y(train_scaled, lag)
testX, testY = create_X_Y(test_scaled, lag)
# 重塑输入数据以符合LSTM网络的输入要求
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], trainX.shape[2]))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1], testX.shape[2]))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(50, input_shape=(trainX.shape[1], trainX.shape[2])))
model.add(Dense(trainY.shape[1], activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
early_stopping = EarlyStopping(monitor='val_loss', patience=5)
model.fit(trainX, trainY, epochs=50, batch_size=1, verbose=1, callbacks=[early_stopping], validation_split=0.1)
# 对测试集进行预测
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
# 反归一化处理
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform(trainY)
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform(testY)
# 计算RMSE
from sklearn.metrics import mean_squared_error
trainScore = mean_squared_error(trainY[:,0], trainPredict[:,0])
print('Train Score: %.2f RMSE' % (trainScore))
testScore = mean_squared_error(testY[:,0], testPredict[:,0])
print('Test Score: %.2f RMSE' % (testScore))
这段代码展示了如何使用Python和TensorFlow Keras库来实现一个简单的LSTM时间序列预测模型。代码包括数据准备、归一化处理、模型构建、训练和评