火炬损失函数尺寸不匹配

时间:2019-03-22 14:48:22

标签: python neural-network pytorch

我正尝试使用批量培训来运行单词嵌入,如下所示。

def forward(self, inputs):
    print(inputs.shape)
    embeds = self.embeddings(inputs)
    print(embeds.shape)
    out = self.linear1(embeds)
    print(out.shape)
    out = self.activation_function1(out)
    print(out.shape)
    out = self.linear2(out).cuda()
    print(out.shape)
    out = self.activation_function2(out)
    print(out.shape)
    return out.cuda()

在这里,我使用的是上下文大小4,批处理大小32,嵌入大小50,隐藏层大小64,vocab大小9927

“形状”函数的输出为

print(inputs.shape)----> torch.Size([4,32])

print(embeds.shape)----> torch.Size([4,32,50])

print(out.shape)----> torch.Size([4,32,64])

print(out.shape)----> torch.Size([4,32,64])

print(out.shape)----> torch.Size([4,32,9927])

print(out.shape)----> torch.Size([4,32,9927])

这些形状正确吗?我很困惑。

此外,当我训练时,它会返回错误:

def train(epoch):
  model.train()
  for batch_idx, (data, target) in enumerate(train_loader, 0):
    optimizer.zero_grad()
    output = model(torch.stack(data))
    loss = criterion(output, target)
    loss.backward()
    optimizer.step()

我在“损失=标准(输出,目标)”行中出错。它说:“预期输入batch_size(4)以匹配目标batch_size(32)。”我的“前进”功能形状正确吗?我对批量培训不太熟悉。如何使尺寸匹配?

-------编辑:在下面发布初始化代码-----

  def __init__(self, vocab_size, embedding_dim):
    super(CBOW, self).__init__()
    self.embeddings = nn.Embedding(vocab_size, embedding_dim)
    self.linear1 = nn.Linear(embedding_dim, 64)
    self.activation_function1 = nn.ReLU()
    self.linear2 = nn.Linear(64, vocab_size)
    self.activation_function2 = nn.LogSoftmax(dim = -1)

1 个答案:

答案 0 :(得分:0)

torch.nn.Linear的{​​{1}}方法需要批量大小作为第一个参数。

您将其作为第二个(首先是时间步长)提供,请使用forward将其设置为第一。

此外,线性层通常采用2D输入,第一个是批处理,第二个是输入尺寸。您的语言是3d(因为我认为是单词),也许您想使用递归神经网络(例如permute(1, 0, 2))?

相关问题