1. 均方误差损失函数
一般加上sigmoid激活函数规范到0-1。
M
S
E
=
1
n
∑
i
=
1
n
(
y
i
^
−
y
i
)
2
MSE = \frac{1}{n} \sum_{i=1}^n(\hat{y_i}-y_i)^2
MSE=n1i=1∑n(yi^−yi)2
torch.nn.MSELoss(reduction='mean')
2. 交叉熵损失函数
多分类任务中,经常采用softmax激活函数 + 交叉熵损失函数,交叉熵损失函数描述了两个概率分布的差异。
H ( p , q ) = − ∑ i = 1 n p ( x i ) l o g ( q ( x i ) ) H(p,q)=-\sum_{i=1}^n p(x_i)log(q(x_i)) H(p,q)=−i=1∑np(xi)log(q(xi))
torch.nn.CrossEntropyLoss(weight=None,ignore_index=-100, reduction='mean')
信息量:
如果一个信息发生的概率越大,其包含的信息量就越少
I
(
x
)
=
−
l
o
g
(
p
(
x
)
)
I(x)=-log(p(x))
I(x)=−log(p(x))
信息熵:
所有信息的期望。比如说明天下雨的概率0.5;多云的概率0.3;晴天的概率0.2;则:
H
(
x
)
=
−
∑
i
=
1
n
−
p
(
x
i
)
l
o
g
(
p
(
x
i
)
)
H(x)=-\sum_{i=1}^{n} -p(x_i)log(p(x_i))
H(x)=−i=1∑n−p(xi)log(p(xi))
H
(
x
)
=
−
0.5
×
l
o
g
(
0.5
)
−
0.3
×
l
o
g
(
0.3
)
−
0.2
×
l
o
g
(
0.2
)
H(x) = -0.5\times log(0.5)-0.3\times log(0.3)-0.2\times log(0.2)
H(x)=−0.5×log(0.5)−0.3×log(0.3)−0.2×log(0.2)
KL散度:
衡量两个分布的差别,
p
p
p为真实分布,
q
q
q为预测;
p
和
q
p和q
p和q完全一致时,才为0。
D
k
l
(
p
∣
∣
q
)
=
∑
i
=
1
n
p
(
x
i
)
l
o
g
(
p
(
x
i
)
q
(
x
i
)
)
D_{kl}(p||q) = \sum_{i=1}^np(x_i)log(\frac{p(x_i)}{q(x_i)})
Dkl(p∣∣q)=i=1∑np(xi)log(q(xi)p(xi))
交叉熵:
D
k
l
(
p
∣
∣
q
)
=
∑
i
=
1
n
p
(
x
i
)
l
o
g
(
p
(
x
i
)
)
−
∑
i
=
1
n
p
(
x
i
)
l
o
g
(
q
(
x
i
)
)
D_{kl}(p||q)=\sum_{i=1}^np(x_i)log(p(x_i))-\sum_{i=1}^np(x_i)log(q(x_i))
Dkl(p∣∣q)=i=1∑np(xi)log(p(xi))−i=1∑np(xi)log(q(xi))
KL散度=交叉熵-信息熵。信息熵是定值,所以交叉熵和KL酸度一样可以衡量两个分布的差异。
3. 二元交叉熵损失函数(BCE)
− y l o g y ^ − ( 1 − y ) l o g ( 1 − y ^ ) ) -ylog\hat{y}-(1-y)log(1-\hat{y})) −ylogy^−(1−y)log(1−y^))
torch.nn.BCELoss(weight=None, reduction='mean')
举个栗子:
预测一个物体是不是栗子,如果真实值是栗子
y
t
r
u
t
h
=
[
1
,
0
]
y_{truth} = [1,0]
ytruth=[1,0];预测是栗子的概率是0.8,则换成one-hot编码应该是:
y
p
r
e
d
=
[
0.8
,
0.2
]
y_{pred} = [0.8,0.2]
ypred=[0.8,0.2]
l
o
s
s
=
−
1
×
l
o
g
(
0.8
)
−
0
×
l
o
g
(
0.2
)
loss = -1\times {log(0.8)} -0\times log(0.2)
loss=−1×log(0.8)−0×log(0.2)
4. BCEWithLogitsLoss
把sigmoid层集成到BCELoss类中。
torch.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)
5. Smooth L1损失
在目标检测中预测坐标时,容易产生梯度爆炸。
将均方误差转换为SmoothL1损失。
s
m
o
o
t
h
L
1
(
x
)
=
{
0.5
x
2
if|x|<1
∣
x
∣
−
0.5
otherwise
smooth_{L_1}(x) = \begin{cases} 0.5x^2 & \text{if|x|<1} \\ |x|-0.5 & \text{otherwise} \end{cases}
smoothL1(x)={0.5x2∣x∣−0.5if|x|<1otherwise
6. Hinge Loss
H i n g e L o s s = m a x ( 0 , y ∗ y ^ ) Hinge Loss = max(0, y*\hat{y}) HingeLoss=max(0,y∗y^)
7.Focal Loss
目标检测任务中,样本间类别不均衡会导致准确率不高。
Focal Loss可增加难分类样本的权重。
F
o
c
a
l
L
o
s
s
=
−
α
t
(
1
−
p
t
)
γ
l
o
g
(
p
t
)
Focal Loss = -\alpha_t(1-p_t)^\gamma log(p_t)
FocalLoss=−αt(1−pt)γlog(pt)