LSTM 预测模型核心代码示例 - Python 实现
以下是一个简单的 LSTM 预测模型的核心代码,使用 Python 和 Keras 库实现:
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 准备数据
data = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]])
target = np.array([4, 5, 6, 7, 8, 9, 10, 11])
# 创建模型
model = Sequential()
model.add(LSTM(50, input_shape=(3, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(data.reshape(8, 3, 1), target, epochs=100, batch_size=1, verbose=2)
# 预测
test_data = np.array([[9, 10, 11], [10, 11, 12], [11, 12, 13]])
predictions = model.predict(test_data.reshape(3, 3, 1))
print(predictions)
这个模型使用了一个包含 50 个神经元的 LSTM 层,以及一个输出层。我们使用均方误差作为损失函数,Adam 作为优化器。然后,我们将数据拟合到模型中进行训练,并使用训练好的模型进行预测。
这个示例展示了使用 LSTM 模型进行预测的基本步骤,并解释了每个步骤的代码含义。你可以根据自己的需求修改代码和参数,并使用它来解决不同的预测问题。
原文地址: https://www.cveoy.top/t/topic/m8UJ 著作权归作者所有。请勿转载和采集!