【问题标题】:pytorch seq2seq encoder forward methodpytorch seq2seq 编码器正向方法
【发布时间】:2018-06-14 12:50:25
【问题描述】:

我正在关注Pytorch seq2seq tutorial,下面是他们如何定义编码器功能。

class EncoderRNN(nn.Module):
    def __init__(self, input_size, hidden_size):
        super(EncoderRNN, self).__init__()
        self.hidden_size = hidden_size

        self.embedding = nn.Embedding(input_size, hidden_size)
        self.gru = nn.GRU(hidden_size, hidden_size)

    def forward(self, input, hidden):
        embedded = self.embedding(input).view(1, 1, -1)
        output = embedded
        output, hidden = self.gru(output, hidden)
        return output, hidden

    def initHidden(self):
        return torch.zeros(1, 1, self.hidden_size, device=device)

但是,在训练期间似乎从未真正调用过 forward 方法。

以下是本教程中如何使用编码器转发方法:

    for ei in range(input_length):
        encoder_output, encoder_hidden = encoder(input_tensor[ei], encoder_hidden)
        encoder_outputs[ei] = encoder_output[0, 0]

不应该是encoder.forward 而不仅仅是encoder 吗? Pytorch 中是否有一些我不知道的自动“前进”机制?

【问题讨论】:

    标签: deep-learning pytorch seq2seq


    【解决方案1】:

    在 PyTorch 中,您可以通过扩展 torch.nn.Module 来编写自己的类,并定义 forward 方法来表达您所需的计算步骤,这些步骤用作 model.__call__(...) 方法中的“文书工作”(例如调用挂钩)(这是什么模型(x) 将通过 python 特殊名称规范调用)。

    如果你好奇,你可以看看 model(x) 在幕后除了调用 model.forward(x) 之外做了什么:https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L462

    此外,您还可以看到显式调用 .foward(x) 方法与仅在此处简单地使用 model(x) 之间的区别:https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L72

    【讨论】:

    • 非常感谢瓦西!!
    猜你喜欢
    • 2018-03-04
    • 2018-11-21
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2020-08-28
    • 1970-01-01
    相关资源
    最近更新 更多