torch.nn.CrossEntrypyLoss(weight=None,size_average=True)
交叉熵
刻画了实际输出(概率)与期望输出(概率)之间的距离。
交叉熵的值越小,两个概率分布就越接近。
我们记概率分布函数
p
p
p为期望输出,概率分布函数
q
q
q为实际输出,
H
(
p
,
q
)
H(p,q)
H(p,q)为交叉熵。
H
(
p
,
q
)
=
−
∑
x
(
p
(
x
)
log
q
(
x
)
+
(
1
−
p
(
x
)
)
log
(
1
−
q
(
x
)
)
)
H(p,q)=-\sum_x(p(x)\log{q(x)}+(1-p(x))\log(1-q(x)))
H(p,q)=−x∑(p(x)logq(x)+(1−p(x))log(1−q(x)))
初始参数说明
weight:
1-D Tensor ,共包含n个元素 ,分别代表了n类的权重 ,如果训练样本不均衡 ,这个参数用处比较大 ,一般默认为None
传入参数说明
input:
2-D shape = batch * num_class 包含了每个类的得分
target:
1-D shape = batch_size 包含了类别的索引
函数
pytorch中的交叉熵函数计算,并不采用上述式子,而是采用下面的式子:
H
(
p
,
q
)
=
−
∑
x
p
(
x
)
log
q
(
x
)
H(p,q)=-\sum_xp(x)\log{q(x)}
H(p,q)=−x∑p(x)logq(x)
期望输出的概率一般取1。
pytorch中,将logsoftmax与NLLLoss融合,得到结果。
- Softmax后,数值都在0~1之间,所以ln之后的值域在负无穷到0;
- 将Softmax之后的结果取log,将乘法改成加法,减少计算量,保证函数的单调性。
- 将上面的输出与Label对应的值取出来,取负号,取均值,这就是NLLLoss。
l o s s ( x , c l a s s ) = − log e x [ c l a s s ] ∑ j e x [ j ] = − x [ c l a s s ] + log ( ∑ j e x [ j ] ) loss(x,class) = -\log{\frac{e^{x[class]}}{\sum_je^{x[j]}}}=-x[class]+\log{(\sum_je^{x[j]})} loss(x,class)=−log∑jex[j]ex[class]=−x[class]+log(j∑ex[j])
计算出loss后,对mini-batch取平均值。
mini-batch
是一个batch中的很小一部分。
介于batch和SGD之间。
实际上,我们称的batch一般指mini-batch。
NLLLoss
负的对数概率损失。
用于训练n分类器。
输入的是:
1.
包含类别概率的二维Tensor。
形状是(batch_size,num_class)。
2.
类别的索引。
形状(batch,)
一般在调用NLLLoss函数之前调用Softmax,或者直接采用CrossEntropyLoss
函数为:
l
o
s
s
(
x
,
c
l
a
s
s
)
=
−
x
[
c
l
a
s
s
]
loss(x,class)=-x[class]
loss(x,class)=−x[class]
Loss越大,则对应类别的概率值越小,则损失越大。