常用的损失函数
L1范数损失
计算 output 和 target 之差的绝对值
torch.nn.L1Loss(reduction='mean'
mean 返回loss和的平均值
sum 返回loss和
均方误差损失 MSELoss(L2)
计算 output 和 target 之差的均方差。
torch.nn.MSELoss(reduction='mean')
mean 返回loss和的平均值
sum 返回loss的和
交叉熵损失 CrossEntropyLoss
常用的交叉熵,以二分类为例:
每个元素的范围为[0,1],若不在该范围内,要对其进行sigmod处理
C
E
(
p
,
y
)
=
{
−
l
o
g
(
p
)
,
y
=
1
−
l
o
g
(
1
−
p
)
,
o
t
h
e
r
w
i
s
e
CE(p,y)=\begin{cases} -log(p),\quad y=1\\ -log(1-p), otherwise\end{cases}
CE(p,y)={−log(p),y=1−log(1−p),otherwise
P
t
P_t
Pt简化交叉熵loss:
P
t
=
{
p
,
i
f
y
=
1
1
−
p
,
o
t
h
e
r
w
i
s
e
P_t =\begin{cases}p, \quad\quad if \space y=1 \\ 1-p, \quad otherwise\end{cases}
Pt={p,if y=11−p,otherwise
则
C
E
(
p
,
y
)
=
C
E
(
p
t
)
=
−
l
o
g
(
p
t
)
CE(p,y)=CE(p_t)=-log(p_t)
CE(p,y)=CE(pt)=−log(pt)
与Pt类似,当y=1的时候,αt=α;当y=otherwise的时候,αt=1 - α,a的范围也是0到1。此时我们便可以通过设置α实现控制正负样本对loss的贡献。
C
E
(
p
,
y
,
a
)
=
{
−
l
o
g
(
p
)
∗
a
i
f
y
=
1
−
l
o
g
(
1
−
p
)
∗
(
1
−
a
)
i
f
y
=
0
CE(p,y,a)=\begin{cases} -log(p)*a\quad\quad\quad\quad\quad if\space y=1 \\ -log(1-p)*(1-a) \quad if\space y=0\end{cases}
CE(p,y,a)={−log(p)∗aif y=1−log(1−p)∗(1−a)if y=0
torch.nn.CrossEntropyLoss(weight=None, ignore_index=-100, reduction='mean')
KL 散度损失 KLDivLoss
计算 input 和 target 之间的 KL 散度。KL 散度可用于衡量不同的连续分布之间的距离, 在连续的输出分布的空间上(离散采样)上进行直接回归时 很有效.
D
K
L
(
A
∣
∣
B
)
=
∑
i
P
A
(
x
i
)
l
o
g
(
P
A
(
x
i
)
P
B
(
x
i
)
)
D_{KL}(A||B) = \sum_{i}P_A(x_i)log\Big(\frac{P_A(x_i)}{P_B(x_i)} \Big)
DKL(A∣∣B)=i∑PA(xi)log(PB(xi)PA(xi))
KL散度主要有两个性质:
(1)不对称性
它不具有对称性,即 D ( A ∣ ∣ B ) ≠ D ( B ∣ ∣ A ) D(A||B)\ne D(B||A) D(A∣∣B)=D(B∣∣A)$。
(2)非负性
相对熵的值是非负值,即 D ( A ∣ ∣ B ) > 0 D(A||B)>0 D(A∣∣B)>0。
torch.nn.KLDivLoss(reduction='mean')
二进制交叉熵损失 BCELoss
针对二分类任务。 注意目标
t
t
t 的值的范围为0到1之间,
p
p
p为output
B
C
E
(
p
,
t
)
=
−
w
∗
(
t
∗
l
n
(
p
)
+
(
1
−
t
)
∗
l
n
(
1
−
p
)
)
BCE(p,t)=-w*(t*ln(p)+(1-t)*ln(1-p))
BCE(p,t)=−w∗(t∗ln(p)+(1−t)∗ln(1−p))
当然,还可以使用
w
w
w来设置你的权重
torch.nn.BCELoss(weight=None, reduction='mean')
BCEWithLogitsLoss
BCEWithLogitsLoss损失函数把 Sigmoid 层集成到了 BCELoss 类中. 该版比用一个简单的 Sigmoid 层和 BCELoss 在数值上更稳定, 因为把这两个操作合并为一个层之后, 可以利用 log-sum-exp 的 技巧来实现数值稳定.
torch.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)