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

乘风 pytorch 535

原文标题: output with shape [64, 1] doesn’t match the broadcast shape [64, 2]

尝试将加权类传递给 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()
)

原文链接:https://stackoverflow.com//questions/71444220/output-with-shape-64-1-doesnt-match-the-broadcast-shape-64-2

回复

我来回复
  • lhk的头像
    lhk 评论

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

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

    2年前 0条评论