在验证和测试集中时,我是否需要初始化lstm隐藏状态?或只是将其重置为零

时间:2019-06-18 08:19:34

标签: neural-network pytorch lstm

在训练中,初始化隐藏状态而不是将其设置为0是很好的。但是我不知道在验证和测试时初始化隐藏状态是好是坏。谢谢

1 个答案:

答案 0 :(得分:1)

完全没有必要自定义将隐藏状态初始化为为零;这实际上是the case

def forward(self, input, hx=None):
    ...

    if hx is None:
        num_directions = 2 if self.bidirectional else 1
        hx = torch.zeros(self.num_layers * num_directions,
                         max_batch_size, self.hidden_size,
                         dtype=input.dtype, device=input.device)
    else:
        # Each batch of the hidden state should match the input sequence that
        # the user believes he/she is passing in.
        hx = self.permute_hidden(hx, sorted_indices)

它首先检查您是否传递了任何自定义隐藏状态值,如果没有,则将其初始化为零。


从理论上讲,通常,您不需要不需要在测试模式下初始化模型的隐藏状态(随机地或使用预定义的值)。