使用gru模型,想通过例如前几天的数据,预测后面几天的数据,为什么预测出来的值都是相同的?是不是预测代码写错了?
class RNNModel(nn.Module):
"""RNN模型"""
def __init__(self, rnn_layer, output_size=1):
super(RNNModel, self).__init__()
self.rnn = rnn_layer # RNN层
self.dense = nn.Linear(rnn_layer.hidden_size, output_size) # 全连接层
self.state = None # 隐藏状态
def forward(self, x, state):
Y, self.state = self.rnn(x, state) # (batch_size, num_input, num_hidden)
output = self.dense(Y.reshape(-1, Y.shape[-1])) # (num_input*batch_size, num_output)
return output, self.state
# 4.加载模型
model_path = "model/1.pt"
GRU_layer = nn.GRU(batch_first=True, input_size=dim_x, hidden_size=hidden_size, num_layers=num_layers)
net = model.RNNModel(rnn_layer=GRU_layer)
net.load_state_dict(torch.load(model_path))
net.to(device)
# 5.预测未来数据
net.eval()
state = None
with torch.no_grad():
y_list, y_hat_list = [], []
y_list.append(all_data * (max_data - min_data) + min_data)
for i in range(1, n_train): # 取n_train天数据进行预测
inputs = test_x[i - 1, 0].unsqueeze(1).unsqueeze(1)
output, state = net(inputs, state)
pred = inputs.squeeze().cpu().numpy() * (max_data - min_data) + min_data # 反归一化处理
y_hat_list.append(pred)
# print(f"第{i}天", pred.round(2))
for i in range(n_train, predict_len + n_train + 1): # 预测predict_len天数据
output, state = net(inputs, state) # 输入模型进行预测
inputs = output.unsqueeze(1) # 将预测结果作为下一次的输入
pred = output.squeeze().cpu().numpy() * (max_data - min_data) + min_data # 反归一化处理
y_hat_list.append(pred)
# print(f"第{i}天预测值:{pred.round(2)}")