LSTM的预期隐藏状态尺寸未考虑批次大小

时间:2019-02-07 04:15:27

标签: python-3.x lstm pytorch batchsize

我有一个解码器模型,该模型应该以成批的句子嵌入(批处理大小= 50,隐藏大小= 300)作为输入并输出一批预测的句子的热表示:

class DecoderLSTMwithBatchSupport(nn.Module):
        # Your code goes here
        def __init__(self, embedding_size,batch_size, hidden_size, output_size):
            super(DecoderLSTMwithBatchSupport, self).__init__()
            self.hidden_size = hidden_size
            self.batch_size = batch_size
            self.lstm = nn.LSTM(input_size=embedding_size,num_layers=1, hidden_size=hidden_size, batch_first=True)
            self.out = nn.Linear(hidden_size, output_size)
            self.softmax = nn.LogSoftmax(dim=1)

        def forward(self, my_input, hidden):
            print(type(my_input), type(hidden))
            output, hidden = self.lstm(my_input, hidden)
            output = self.softmax(self.out(output[0]))
            return output, hidden

        def initHidden(self):
            return Variable(torch.zeros(1, self.batch_size, self.hidden_size)).cuda()

但是,当我使用以下命令运行它时:

decoder=DecoderLSTMwithBatchSupport(vocabularySize,batch_size, 300, vocabularySize)
decoder.cuda()
decoder_input=np.zeros([batch_size,vocabularySize])
    for i in range(batch_size):
        decoder_input[i] = embeddings[SOS_token]
    decoder_input=Variable(torch.from_numpy(decoder_input)).cuda()
    decoder_hidden = (decoder.initHidden(),decoder.initHidden())
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input.view(1,batch_size,-1), decoder_hidden)

我得到他以下错误:

  

期望隐藏的[0]大小(1、1、300),得到的(1、50、300)

为了使模型期望成批的隐藏状态,我缺少什么?

2 个答案:

答案 0 :(得分:1)

创建LSTM时,不需要标志batch_first,因为它假定您输入的形状不同。从文档中:

  

如果为True,则输入和输出张量以(batch,   seq,功能)。默认值:False

将LSTM创建更改为:

self.lstm = nn.LSTM(input_size=embedding_size, num_layers=1, hidden_size=hidden_size)

此外,还有类型错误。使用decoder_input创建torch.from_numpy()时,它具有一个dtype=torch.float64,而decoder_input具有默认的dtype=torch.float32。将创建decoder_input的行更改为

decoder_input = Variable(torch.from_numpy(decoder_input)).cuda().float()

这两项都可以正常工作:)

答案 1 :(得分:0)

更改.view()以将[1,batch size,embedding_size]反映为第一维。

此外,您无需初始化零张量,如果未提供张量作为初始张量,则pytorch将使用零张量。