请用Python编写一个LSTM预测位移的代码
时间: 2024-04-09 10:21:52 浏览: 86
以下是一个简单的 Python 代码实现 LSTM 预测位移的示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 生成示例数据
data = np.sin(np.arange(1000) * (20 * np.pi / 1000))[:, np.newaxis]
# 划分训练集和测试集
train = data[:800]
test = data[800:]
# 创建数据生成器
def generator(data, lookback):
i = 0
while i + lookback < len(data):
x = data[i:i+lookback]
y = data[i+lookback]
yield x, y
i += 1
# 设置模型参数
lookback = 40
batch_size = 32
epochs = 100
# 创建模型
model = Sequential()
model.add(LSTM(32, input_shape=(lookback, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
# 训练模型
train_generator = generator(train, lookback=lookback)
test_generator = generator(test, lookback=lookback)
history = model.fit_generator(train_generator, steps_per_epoch=len(train)-lookback,
epochs=epochs, validation_data=test_generator,
validation_steps=len(test)-lookback)
# 预测未来数据
predictions = np.zeros_like(test)
for i in range(len(test)-lookback):
x = test[i:i+lookback]
y_pred = model.predict(x[np.newaxis, :, :])
predictions[i+lookback] = y_pred
# 可视化结果
plt.figure(figsize=(10, 6))
plt.plot(range(800), train, label='training data')
plt.plot(range(800, 1000), test, label='test data')
plt.plot(range(800, 1000), predictions, label='predicted test data')
plt.legend(loc='lower left')
plt.show()
```
该代码使用 LSTM 模型来学习一个正弦函数的规律,并尝试预测未来的值。训练过程包括将数据分成训练/测试集、创建数据生成器、定义模型并编译、训练模型,并用训练好的模型进行预测。最终使用 Matplotlib 可视化结果。
阅读全文