试图了解解码器的Pytorch神经翻译代码

时间:2018-11-05 22:30:07

标签: python machine-learning neural-network pytorch

我正在阅读Python Pytorch神经机器翻译教程https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html,并且直到解码器的神经网络的第一个代码块为止,我都可以理解所有内容,尤其是我无法理解forward函数:

class DecoderRNN(nn.Module):
    def __init__(self, hidden_size, output_size):
        super(DecoderRNN, self).__init__()
        self.hidden_size = hidden_size

        self.embedding = nn.Embedding(output_size, hidden_size)
        self.gru = nn.GRU(hidden_size, hidden_size)
        self.out = nn.Linear(hidden_size, output_size)
        self.softmax = nn.LogSoftmax(dim=1)

    def forward(self, input, hidden):
        output = self.embedding(input).view(1, 1, -1)
        output = F.relu(output)
        output, hidden = self.gru(output, hidden)
        output = self.softmax(self.out(output[0]))
        return output, hidden

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

我知道input是文字,self.embedding会将其转换为一维矢量,它可以是一键热嵌入,也可以是实数矢量嵌入,但是无论如何,它都是向量。但是view(1, 1, -1)的作用是什么?它在语义上做了什么,为什么要调用它?我知道我必须继续使用向量,但是显然view会以某种方式将此向量转换为多维张量,不是吗?我猜想神经激活函数的进一步调用需要一维向量,但是现在有些不同了。在output = self.softmax(self.out(output[0]))行中正在做什么? output应该是一维矢量,但是为什么我应该只采用它的第一个元素?其他元素会发生什么?

这是一个非常基本的示例,但是我不知道在这里发生了什么,为什么引入了这种复杂性,为什么我不能留下来并用一维矢量进行所有计算?

0 个答案:

没有答案