要使用Python进行LSTM时间序列预测,你可以使用Keras库。以下是一个简单的示例:
pip install keras
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
# 生成正弦波数据
def generate_data(n_samples):
x = np.linspace(0, 10 * np.pi, n_samples)
y = np.sin(x)
return x, y
n_samples = 1000
x, y = generate_data(n_samples)
scaler = MinMaxScaler(feature_range=(0, 1))
y = scaler.fit_transform(y.reshape(-1, 1))
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
v = X[i:(i + time_steps)].flatten()
Xs.append(v)
ys.append(y[i + time_steps])
return np.array(Xs), np.array(ys)
time_steps = 10
Xs, ys = create_dataset(x, y, time_steps)
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(time_steps, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
model.fit(Xs, ys, epochs=200, verbose=0)
x_input = np.array([x[-time_steps:]]).reshape((1, time_steps, 1))
yhat = model.predict(x_input, verbose=0)
yhat = scaler.inverse_transform(yhat)
plt.plot(x, y, label='原始数据')
plt.plot(x[-time_steps:], yhat, label='预测数据')
plt.legend()
plt.show()
这个示例展示了如何使用Keras库创建一个简单的LSTM模型来进行时间序列预测。你可以根据自己的需求修改数据生成部分和模型参数。