PyTorch学习笔记:nn.MarginRankingLoss——排序损失

PyTorch学习笔记:nn.MarginRankingLoss——排序损失

torch.nn.MarginRankingLoss(margin=0.0, size_average=None, reduce=None, reduction='mean')

功能:创建一个排序损失函数,用于衡量输入 x 1 x_1 x1 x 2 x_2 x2之间的排序损失(Ranking Loss),输入的第三个参数 y y y控制顺序还是逆序,因此 y y y的取值范围为 y ∈ { 1 , − 1 } y\in\{1,-1\} y{1,1}

损失函数
l o s s ( x 1 , x 2 , y ) = max ⁡ ( 0 , − y ∗ ( x 1 − x 2 ) + margin ) loss(x_1,x_2,y)=\max(0,-y*(x_1-x_2)+\text{margin}) loss(x1,x2,y)=max(0,y(x1x2)+margin)
当期望 x 1 > x 2 x_1>x_2 x1>x2,即排序为顺序时,应该传入 y = 1 y=1 y=1;当期望 x 1 < x 2 x_1<x_2 x1<x2,即排序为逆序时,应该传入 y = − 1 y=-1 y=1

输入:

  • margin:差额值,具体用法如公式所示,如果该值越大,则表示期望 x 1 x_1 x1 x 2 x_2 x2越远,即差额越大。输入数据类型为float,默认为0;
  • size_averagereduce已被弃用,具体功能由reduction替代
  • reduction:指定损失输出的形式,有三种选择:none|mean|sumnone:损失不做任何处理,直接输出一个数组;mean:将得到的损失求平均值再输出,会输出一个数;sum:将得到的损失求和再输出,会输出一个数

注意:

  • 输入的 x 1 x_1 x1 x 2 x_2 x2 y y y必须是一维的数据,并且三个数据长度必须一致,数据长度表示 b a t c h batch batch大小

代码案例

一般用法

import torch
import torch.nn as nn

# reduction设为none便于查看每个位置损失计算的结果
rankloss = nn.MarginRankingLoss(reduction='none')
x1 = torch.randn(10)
x2 = torch.randn(10)
# 随机生成10个0,1数据
y = torch.randint(0, 2, [10])
# 将y中数据为0的位置赋值为-1
y[y==0] = -1
loss = rankloss(x1, x2, y)
print(x1)
print(x2)
print(y)
print(loss)

输出

# x1
tensor([-1.2248, -1.4788,  0.1703,  0.1072, -0.2147,  0.7527, -1.2443,  0.8361, 0.3679,  0.5935])
# x2
tensor([-0.3616, -0.0333,  0.8483,  0.9880,  0.6980, -0.5157,  0.1767,  0.2060, -0.4908,  1.1774])
# y
tensor([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1])
# 对应位置的损失计算结果
tensor([0.8631, 0.0000, 0.6780, 0.0000, 0.9127, 1.2684, 1.4210, 0.6301, 0.0000, 0.0000])

官方文档

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

初步完稿于:2022年2月6日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

视觉萌新、

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

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

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

打赏作者

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

抵扣说明:

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

余额充值