【发布时间】:2022-01-01 16:01:17
【问题描述】:
我正在尝试实现一个神经网络来生成句子(图像说明),为此我正在使用 Pytorch 的 LSTM (nn.LSTM)。
我想在训练中输入的输入来自大小batch_size * seq_size * embedding_size,因此seq_size 是句子的最大大小。例如 - 64*30*512。
在 LSTM 之后有一个 FC 层 (nn.Linear)。
据我了解,这种类型的网络使用隐藏状态(在这种情况下为h,c),并且每次都预测下一个单词。
我的问题是-在训练中-我们是否必须在forward函数中手动将句子逐字输入LSTM,或者LSTM知道如何自己做?
我的转发函数如下所示:
def forward(self, features, caption, h = None, c = None):
batch_size = caption.size(0)
caption_size = caption.size(1)
no_hc = False
if h == None and c == None:
no_hc = True
h,c = self.init_hidden(batch_size)
embeddings = self.embedding(caption)
output = torch.empty((batch_size, caption_size, self.vocab_size)).to(device)
for i in range(caption_size): #go over the words in the sentence
if i==0:
lstm_input = features.unsqueeze(1)
else:
lstm_input = embeddings[:,i-1,:].unsqueeze(1)
out, (h,c) = self.lstm(lstm_input, (h,c))
out = self.fc(out)
output[:,i,:] = out.squeeze()
if no_hc:
return output
return output, h,c
(灵感来自here)
这里forward的输出来自大小batch_size * seq_size * vocab_size,这很好,因为它可以与损失函数中原始batch_size * seq_size大小的标题进行比较。
问题是forward 内的这个for 循环是否真的需要一个接一个地输入单词,或者我可以以某种方式一次输入整个句子并获得相同的结果?
(我看到了一些这样做的例子,例如this one,但我不确定它是否真的等效)
【问题讨论】:
标签: neural-network pytorch lstm recurrent-neural-network