【问题标题】:PyTorch ValueError: Target and input must have the same number of elementsPyTorch ValueError:目标和输入必须具有相同数量的元素
【发布时间】:2018-05-15 14:47:14
【问题描述】:

我对 PyTorch 有点陌生,但我想了解在计算损失函数时,目标和输入的大小如何在 torch.nn.BCELoss() 中起作用。

import torch
import torch.nn as nn
from torch.autograd import Variable

time_steps = 15
batch_size = 3
embeddings_size = 100
num_classes = 2

model = nn.LSTM(embeddings_size, num_classes)
input_seq = Variable(torch.randn(time_steps, batch_size, embeddings_size))
lstm_out, _ = model(input_seq)
last_out = lstm_out[-1]
print(last_out)

loss = nn.BCELoss()
target = Variable(torch.LongTensor(batch_size).random_(0, num_classes))
print(target)
err = loss(last_out.long(), target)
err.backward()

我收到以下错误:

Warning (from warnings module):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 767
"Please ensure they have the same size.".format(target.size(), input.size()))

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/nn/functional.py", line 770, in binary_cross_entropy
"!= input nelement ({})".format(target.nelement(), input.nelement()))
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)

这个错误肯定来自last_out (size 3x2) 和target (size 3) 的大小不同。所以我的问题是如何将 last_out 转换为目标(大小为 3,仅包含 0 和 1)来计算损失函数?

【问题讨论】:

    标签: python-3.x lstm pytorch


    【解决方案1】:

    nn.BCELoss()的思路是实现如下公式:

    ot 都是任意(但相同!)大小的张量,i 只是索引两个张量的每个元素以计算上述总和。

    通常,nn.BCELoss() 用于分类设置:oi 将是维度矩阵 N x DN 将是您的数据集或小批量中的观察数。如果您只尝试对单个属性进行分类,D 将为 1,如果您尝试对多个属性进行分类,则大于 1。 t,目标矩阵,将只包含 0 和 1,因为对于每个属性,只有两个类(这就是二元交叉熵损失中的二元的来源)。 o 将保存您将每个观察的每个属性分配给第 1 类的概率。

    现在在您上面的设置中,尚不清楚您正在考虑多少类以及有多少属性适合您。如果您的target 的形状所建议的属性只有一个,则您应该只输出一个数量,即您的model 属于第 1 类的概率。如果有两个属性,您的targets 不完整!如果有多个类,您应该使用torch.nn.CrossEntropyLoss而不是torch.nn.BCELoss()

    顺便说一句,为了数值稳定性,通常希望在某些输出上使用torch.nn.BCEWithLogitsLoss 而不是torch.nn.BCELoss() 跟在nn.Sigmoid() 之后。

    【讨论】:

    • 你好mbpaulus!我在四处寻找我的目标输入大小不匹配问题时看到了您的评论。我正在尝试使用 BCELoss,但出现“目标大小 (torch.Size([64])) 必须与输入大小相同 (torch.Size([64, 256]))”错误。我怎样才能匹配这些尺寸?谢谢!
    猜你喜欢
    • 2019-11-11
    • 2020-09-24
    • 2020-07-27
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多