Pytorch GRU模型运行问题;forward()缺少参数

Pytorch GRU模型运行问题;forward()缺少参数,pytorch,gated-recurrent-unit,Pytorch,Gated Recurrent Unit,我正在处理GRU,当我尝试进行预测时,我得到一个错误,指示我需要为forward()定义h。在谷歌搜索和搜索堆栈溢出数小时后,我尝试了几种方法,但都失去了耐心 这是一节课: class GRUNet(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, n_layers, drop_prob = 0.2): super(GRUNet, self).__init__() self.

我正在处理GRU,当我尝试进行预测时,我得到一个错误,指示我需要为forward()定义h。在谷歌搜索和搜索堆栈溢出数小时后,我尝试了几种方法,但都失去了耐心

这是一节课:

class GRUNet(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim, n_layers, drop_prob = 0.2):
        super(GRUNet, self).__init__()
        self.hidden_dim = hidden_dim
        self.n_layers = n_layers
        
        self.gru = nn.GRU(input_dim, hidden_dim, n_layers, batch_first=True, dropout=drop_prob)
        self.fc = nn.Linear(hidden_dim, output_dim)
        self.relu = nn.ReLU()
    
    def forward(self, x, h):
        out, h = self.gru(x,h)
        out = self.fc(self.relu(out[:,-1]))
        return out, h
    
    def init_hidden(self, batch_size):
        weight = next(self.parameters()).data
        hidden = weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().to(device)
        return hidden
然后这就是我加载模型并尝试做出预测的地方。这两个脚本都在同一个脚本中

inputs = np.load('.//Pred//input_list.npy')  
print(inputs.ndim, inputs.shape)
Gmodel = GRUNet(24,256,1,2)
Gmodel = torch.load('.//GRU//GRU_1028_48.pkl')
Gmodel.eval()
pred = Gmodel(inputs)
在没有任何其他Gmodel参数的情况下,我得到以下结果:

Traceback (most recent call last):
  File ".\grunet.py", line 136, in <module>
    pred = Gmodel(inputs)
  File "C:\Users\ryang\Anaconda-3\envs\tf-gpu\lib\site-packages\torch\nn\modules\module.py", line 547, in __call__
    result = self.forward(*input, **kwargs)
TypeError: forward() missing 1 required positional argument: 'h'
回溯(最近一次呼叫最后一次):
文件“\grunet.py”,第136行,在
pred=Gmodel(输入)
文件“C:\Users\ryang\Anaconda-3\envs\tf gpu\lib\site packages\torch\nn\modules\module.py”,第547行,在调用中__
结果=自我转发(*输入,**kwargs)
TypeError:forward()缺少1个必需的位置参数:“h”

您还需要提供隐藏状态,该状态最初通常为全零或干脆为

也就是说,您需要明确地提供这样一个:

hidden_state=torch.zero(大小=(num_layers*方向、批次大小、隐藏尺寸)).to(设备)
pred=Gmodel(输入,隐藏状态)
或者干脆做:

hidden_state = None 
pred = Gmodel(inputs, hidden_state)

这是另一个你需要单独发布的问题。如果这个答案解决了你最初的问题,请接受它作为答案,这样这个问题就完成了。然后分别问你的新问题,我们会尽力回答。