将 pytorch resnet 头从 sigmoid 更改为 Softmax
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以试试这个:
其中10是类的数量,你可以根据你的需要设置值。
You can try this:
where 10 are the number of classes, you can put value based on your needs.