loss函数之MultiLabelSoftMarginLoss

本文详细介绍了PyTorch中的MultiLabelSoftMarginLoss,虽然名字中含有Margin,但实际上它等价于多标签交叉熵损失函数BCEWithLogitsLoss。作者通过代码示例展示了如何使用该损失函数,并对比了其与BCEWithLogitsLoss的结果,证明两者输出一致。此外,文中还提及了BCEWithLogitsLoss中控制正负样本不均衡的pos_weight参数。
摘要由CSDN通过智能技术生成

MultiLabelSoftMarginLoss

不知道pytorch为什么起这个名字,看loss计算公式,并没有涉及到margin,有可能后面会实现。按照我的理解其实就是多标签交叉熵损失函数,验证之后也和BCEWithLogitsLoss的结果输出一致,使用的torch版本为1.5.0

https://pytorch.org/docs/stable/generated/torch.nn.MultiLabelSoftMarginLoss.html#torch.nn.MultiLabelSoftMarginLoss

BCEWithLogitsLoss 还多一个控制正负样本不均衡的pos_weight, 详见https://blog.csdn.net/ltochange/article/details/117790534

例子:

import torch
import torch.nn.functional as F
import torch.nn as nn
import math


def validate_loss(output, target, weight=None, pos_weight=None):
    output = F.sigmoid(output)
    # 处理正负样本不均衡问题
    if pos_weight is None:
        label_size = output.size()[1]
        pos_weight = torch.ones(label_size)
    # 处理多标签不平衡问题
    if weight is None:
        label_size = output.size()[1]
        weight = torch.ones(label_size)

    val = 0
    for li_x, li_y in zip(output, target):
        for i, xy in enumerate(zip(li_x, li_y)):
            x, y = xy
            loss_val = pos_weight[i] * y * math.log(x, math.e) + (1 - y) * math.log(1 - x, math.e)
            val += weight[i] * loss_val
    return -val / (output.size()[0] * output.size(1))


weight = torch.Tensor([0.8, 1, 0.8])
loss = nn.MultiLabelSoftMarginLoss(weight=weight)

x = torch.Tensor([[0.8, 0.9, 0.3], [0.8, 0.9, 0.3], [0.8, 0.9, 0.3], [0.8, 0.9, 0.3]])
y = torch.Tensor([[1, 1, 0], [1, 1, 0], [1, 1, 0], [1, 1, 0]])
print(x.size())
print(y.size())
loss_val = loss(x, y)
print(loss_val.item())

validate_loss = validate_loss(x, y, weight=weight)
print(validate_loss.item())

loss = torch.nn.BCEWithLogitsLoss(weight=weight)
loss_val = loss(x, y)
print(loss_val.item())


输出结果:

torch.Size([4, 3])
torch.Size([4, 3])
0.4405062198638916
0.4405062198638916
0.440506249666214
val_loss函数是指用于评估模型在验证集上的损失函数。在机器学习中,我们通常将数据集划分为训练集和验证集,用训练集训练模型,然后用验证集验证模型的性能。val_loss函数被用来衡量模型预测结果与验证集标签之间的差异程度。 val_loss函数的代码实现通常与模型训练过程中的损失函数的代码实现类似。在训练过程中,模型会根据训练集的输入和标签生成预测结果,并计算与标签之间的差异,即损失值。同样地,在验证过程中,模型会根据验证集的输入生成预测结果,并计算与验证集的标签之间的差异,这就是val_loss函数的计算方式。 具体的val_loss函数的代码实现可能会根据具体的机器学习框架和任务而有所不同。一般来说,val_loss函数的计算会涉及到模型的预测结果和验证集标签的对比,计算它们之间的差异,并根据差异的大小来评估模型在验证集上的性能。 val_loss函数的数值越小,表示模型在验证集上的性能越好。在训练过程中,我们通常会监控val_loss函数的数值变化,以判断模型是否出现过拟合或欠拟合的情况。如果val_loss函数的数值一直在下降,说明模型在训练过程中在验证集上的表现一直在改善。如果val_loss函数的数值开始上升,说明模型可能已经开始过拟合了,需要调整模型的复杂度或者调整其他超参数。 总之,val_loss函数是用于评估模型在验证集上的损失函数,通过计算模型预测结果与验证集标签之间的差异来评估模型在验证集上的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺旺棒棒冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值