【问题标题】:Output of DecoderRNN contains extra dimensions (Pytorch)DecoderRNN 的输出包含额外的维度(Pytorch)
【发布时间】:2018-08-01 18:24:52
【问题描述】:

我开发了一个编码器(CNN)-解码器(RNN)网络,用于 pytorch 中的图像字幕。解码器网络接收两个输入——来自编码器的上下文特征向量和用于训练的字幕的词嵌入。上下文特征向量的大小 = embed_size ,这也是标题中每个单词的嵌入大小。我这里的问题更关心 Class DecoderRNN 的输出。请参考下面的代码。

class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
    super(DecoderRNN, self).__init__()
    self.embed_size = embed_size
    self.hidden_size = hidden_size
    self.vocab_size = vocab_size
    self.num_layers = num_layers
    self.linear = nn.Linear(hidden_size, vocab_size)
    self.embed = nn.Embedding(vocab_size, embed_size)
    self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first = True)


def forward(self, features, captions):
    embeddings = self.embed(captions)
    embeddings = torch.cat((features.unsqueeze(1), embeddings),1)
    hiddens,_ = self.lstm(embeddings)
    outputs = self.linear(hiddens)
    return outputs

在前向函数中,我发送一个序列 (batch_size, caption_length+1, embed_size) (concatenated tensor of context feature vector and the embedded caption)。序列的输出应该是标题和形状 (batch_size, caption_length, vocab_size) ,但我仍然收到形状 (batch_size, caption_length +1, vocab_size) 的输出。谁能建议我应该在我的转发功能中改变什么,以便不接收额外的二维?提前致谢

【问题讨论】:

    标签: python deep-learning pytorch rnn encoder-decoder


    【解决方案1】:

    由于在 LSTM(或任何 RNN)中每个时间步长(或此处的标题长度),都会有一个输出,我在这里看不到任何问题。您需要做的是在第二维上制作输入大小(caption_length)以获得所需的输出。 (或者人们通常会在目标中添加一个标签。因此目标长度是标题+1)

    【讨论】:

    • 我找到了解决这个问题的办法。我在这里面临的问题是输出的长度应该是 (batch_size, caption_length, vocab_size) 但我得到了额外的维度。显然,第一批输出可以忽略不计,因为它对字幕生成没有贡献,而只是启动该过程。因此,可以使用额外的语句:hiddens = hiddens[:,1:,:]
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2020-06-27
    • 2013-06-18
    • 1970-01-01
    • 2020-07-16
    相关资源
    最近更新 更多