将 pytorch resnet 头从 sigmoid 更改为 Softmax

发布于 2025-01-13 20:40:24 字数 524 浏览 1 评论 0原文

我是 pytorch 的新手。我编写了下面的代码,使用 Resnet 和 Sigmoid 进行二元分类的预测。我只需要将其更改为 softmax,因为我可能有超过 2 个类。

我知道 pytorch 与 Keras 不同,softmax 位于 CrossEntropyLoss 中。所以我不确定如何更改顶层以使模型使用 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)

I'm new to pytorch. I wrote the below code to do predication using Resnet with Sigmoid for binary classification. I just need to change it to softmax because I might have more than 2 classes.

I understood that pytorch, unlike, Keras, the softmax is in the CrossEntropyLoss. So I'm not sure how could I change the top layer to make the model uses 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()

and later:

lossFunc=torch.nn.BCELoss(class_weights)

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

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

发布评论

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

评论(1

爱给你人给你 2025-01-20 20:40:24

你可以试试这个:

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

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

You can try this:

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

where 10 are the number of classes, you can put value based on your needs.

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