Skip to main content
 首页 » 编程设计

python之DecoderRNN 的输出包含额外维度 (Pytorch)

2024年12月31日11www_RR

我开发了一个编码器 (CNN)-解码器 (RNN) 网络,用于在 pytorch 中进行图像描述。解码器网络接受两个输入——来自编码器的上下文特征向量和用于训练的字幕的词嵌入。上下文特征向量的大小为 embed_size ,这也是标题中每个单词的嵌入大小。我这里的问题更关心类 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) (上下文特征向量和嵌入式标题的串联张量)。序列的输出应该是标题和形状 (batch_size, caption_length, vocab_size) ,但我仍然收到形状的输出 (batch_size, caption_length +1, vocab_size) 。任何人都可以建议我应该在我的前向功能中改变什么,以便不接收额外的二维吗?提前致谢

请您参考如下方法:

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