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∗(x1−x2)+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_average
与reduce
已被弃用,具体功能由reduction
替代reduction
:指定损失输出的形式,有三种选择:none
|mean
|sum
。none
:损失不做任何处理,直接输出一个数组;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日