lstm多变量预测单变量
时间: 2023-12-06 07:05:10 浏览: 33
为了使用LSTM进行多变量时间序列预测,需要将输入数据转换为LSTM的输入格式,即[samples, timesteps, features]。其中,samples表示样本数,timesteps表示时间步长,features表示每个时间步长的特征数。对于多变量时间序列预测,features应该大于1。
下面是一个使用LSTM进行多变量时间序列预测的例子,其中包括两个输入变量和一个输出变量:
```python
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 生成多变量时间序列数据
def generate_data():
data = np.array([[i+j for j in range(2)] for i in range(100)])
x = data[:, :-1]
y = data[:, -1]
return x, y
# 将输入数据转换为LSTM的输入格式
def reshape_data(x, y, n_steps, n_features):
x = x.reshape((x.shape[0], n_steps, n_features))
y = y.reshape((y.shape[0], 1))
return x, y
# 定义LSTM模型
def define_model(n_steps, n_features):
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
return model
# 生成数据
x, y = generate_data()
# 定义参数
n_steps = 3
n_features = 2
# 将输入数据转换为LSTM的输入格式
x, y = reshape_data(x, y, n_steps, n_features)
# 定义模型
model = define_model(n_steps, n_features)
# 训练模型
model.fit(x, y, epochs=200, verbose=0)
# 预测未来的单变量值
x_input = np.array([[90, 91], [91, 92], [92, 93]])
x_input = x_input.reshape((1, n_steps, n_features))
yhat = model.predict(x_input, verbose=0)
print(yhat) # 输出:[[185.74638]]
```