形状为 [64, 1] 的输出与广播形状 [64, 2] 不匹配

发布于 2025-01-13 11:11:16 字数 636 浏览 0 评论 0原文

当尝试将加权类传递给 BCELoss (使用 pytorch)时,我遇到了上述错误。正如你在下面看到的。我的模型是带有 Sigmoid 的 Resnet。我猜该模型期望一个类值而不是两个,因为它是 Sigmoid。 但哪一项价值百分比,我应该通过。正值(1)或负值(0)的百分比

class_weights2=[postive/(negtive+postive),negtive/(negtive+postive)]
print(class_weights2)
# [0.3135668226071564, 0.6864331773928436]
class_weights=torch.tensor(class_weights2,dtype=torch.float)
lossFunc= torch.nn.BCELoss(class_weights)

,这是模型:

model = torchvision.models.resnet50(pretrained=False)

model.fc = torch.nn.Sequential(
    torch.nn.Linear(
        in_features=2048,
        out_features=1
    ),
    torch.nn.Sigmoid()
)

I got above error when trying to pass weighted class to BCELoss (using pytorch). As you can see below. My model is Resnet with Sigmoid. I guess the model expect one class value instead of two becouse its Sigmoid.
But which one of the value percentage, I should pass. The percentage of postive value (with 1) or negative (with 0)

class_weights2=[postive/(negtive+postive),negtive/(negtive+postive)]
print(class_weights2)
# [0.3135668226071564, 0.6864331773928436]
class_weights=torch.tensor(class_weights2,dtype=torch.float)
lossFunc= torch.nn.BCELoss(class_weights)

and this the model:

model = torchvision.models.resnet50(pretrained=False)

model.fc = torch.nn.Sequential(
    torch.nn.Linear(
        in_features=2048,
        out_features=1
    ),
    torch.nn.Sigmoid()
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

完美的未来在梦里 2025-01-20 11:11:16

传递给 BCELoss 的权重不是类别权重。他们重新调整批次中每个元素的贡献。
来自 文档

为每个批次元素的损失指定手动重新缩放权重。如果
给定,必须是大小为 nbatch 的张量。

The weights passed to BCELoss are not class weights. They rescale the contribution of each element in the batch.
From the docs:

a manual rescaling weight given to the loss of each batch element. If
given, has to be a Tensor of size nbatch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文