背景
当我们在做多分类问题(multi-classification)时,如果我们的卷积神经网络没有softmax函数,仅仅是linear层和激活函数(如sigmoid),那么我们的输出就是一些预测值 y 1 ^ , y 2 ^ , … , y n ^ \hat{y_1},\hat{y_2},\dots,\hat{y_n} y1^,y2^,…,yn^。但是在多分类问题中,我们希望得到的是关于这 n n n个种类的一个分布(distribution) P ( y 1 ) , … , P ( y n ) , such that ∑ P ( y i ) = 1 P(y_1),\dots,P(y_n),\text{ such\ that\ }\sum P(y_i) = 1 P(y1),…,P(yn), such that ∑P(yi)=1,这样我们就可以预测样本到底属于哪一类了,比如MNIST分类中,我们想知道某张图片的预测结果是数字几。这就需要softmax函数。
softmax layer
softmax层的核心就是softmax函数:
P
(
y
=
i
)
=
e
i
z
∑
j
=
0
n
e
j
z
,
where
i
=
0
,
…
,
n
−
1
P(y=i) = \frac{e^z_i}{\sum_{j=0}^n e^z_j},\text{where }i=0,\dots,n-1
P(y=i)=∑j=0nejzeiz,where i=0,…,n−1
这里的
z
z
z就是上文所说的
y
^
\hat{y}
y^。
CrossEntropyLoss
在完成softmax函数的计算后,把所得的结果取对数
log
\log
log,用来计算损失(loss)。我们所用的损失函数是NILLoss(negative log likelihood loss),即
L
o
s
s
=
−
Y
log
Y
^
Loss = -Y\log \hat{Y}
Loss=−YlogY^其中,
Y
Y
Y是样本的label,即真实值。
结合上文所述,对于softmax函数和cross entropy loss的关系,不难发现
C
r
o
s
s
E
n
t
r
o
p
y
L
o
s
s
=
L
o
g
S
o
f
t
m
a
x
+
N
I
L
L
o
s
s
CrossEntropyLoss = LogSoftmax + NILLoss
CrossEntropyLoss=LogSoftmax+NILLoss