pytorch - 我的“焦点损失”功能是否存在逻辑错误?
问题描述
“焦点损失”的诞生是为了解决困难的样本。我在 pytorch 中用二元交叉熵包装了焦点损失函数:
class FocalLoss(nn.Module):
def __init__(self, gamma=2):
super(FocalLoss, self).__init__()
self.gamma = gamma
def forward(self, pred, label):
# label is not the one-hot
true = torch.zeros_like(pred, dtype=torch.float)
for i, j in enumerate(label):
true[i, j] = 1.0
loss = nn.BCEWithLogitsLoss(pred, true)
pred_prob = torch.sigmoid(pred) # sigmoid
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
modulating_factor = (1.0 - p_t) ** self.gamma
loss *= modulating_factor
return loss.mean()
我在 cifar10 数据集中训练我的 resnet18 进行分类任务,并使用 nn.CrossEntropyLoss 来比较准确性。
但结果与我的预期相差甚远:CrossEntropyLoss 的准确率比我的focal loss 高5% 左右!任何人都可以在我上面的焦点损失代码中找到逻辑错误吗?
解决方案
推荐阅读
- javascript - Discord JS - 当我在更多公会中时,使用 client.guilds 的 .cache 属性会导致错误吗?
- flutter - 如何在颤动的背景上设置自定义声音通知?
- sockets - java maven eclipse的socket io不工作,因为它不能识别socket io
- lua - lua:15: '[' 附近的意外符号
- wordpress - 除了两个页面之外,限制访问我的网站的最佳做法是什么
- bash - Bash 在传递给其他脚本时将变量扩展视为命令
- java - 如何在java中拆分javascript返回的String对象
- typescript - 打字稿多态行为
- html - 添加一个图像作为指向它自己位置的链接
- python - 遍历列表列表的问题