将 pytorch resnet 头从 sigmoid 更改为 Softmax

原文标题Altering pytorch resnet head from sigmoid to Softmax

我是 pytorch 的新手。我编写了下面的代码来使用带有 Sigmoid 的 Resnet 进行预测,以进行二进制分类。我只需要将其更改为 softmax,因为我可能有 2 个以上的课程。

我知道 pytorch 与 Keras 不同,softmax 在交叉熵损失中。所以我不确定如何更改顶层以使模型使用softmax:

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


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


model = model.cpu()

然后:

lossFunc=torch.nn.BCELoss(class_weights)

原文链接:https://stackoverflow.com//questions/71462468/altering-pytorch-resnet-head-from-sigmoid-to-softmax

回复

我来回复
  • Haris Harris的头像
    Haris Harris 评论

    你可以试试这个:

    model.fc[1] = torch.nn.Softmax(10)
    

    其中 10 是类的数量,您可以根据需要设置值。

    2年前 0条评论