不用相当的独立功夫,不论在哪个严重的问题上都不能找出真理;谁怕用功夫,谁就无法找到真理。
本文主要介绍损失函数、优化器、反向传播、链式求导法则、激活函数、批归一化。
1 经典损失函数
1.1交叉熵损失函数——分类
(1)熵(Entropy)
变量的不确定性越大,熵也就越大,把它搞清楚所需要的信息量也就越大。log以2为底!
H(x) = E[I(xi)] = E[ log(2,1/p(xi)) ] = -∑p(xi)log(2,p(xi)) (i=1,2,..n)
(2)交叉熵(Cross Entropy)
主要用于度量两个概率分布间的差异性信息。差异性越小,交叉熵值越小!
H(p, q) = ∑p(xi)log(2,q(xi))
H(p, q) = H(p) + DkL(p/q)
DkL(散度,KL-Divergence)越小越好
DkL(p/q) = ∑P (xi)log(P(xi)/Q(xi) )
DkL(p/q) = ∑P (xi)log(P(xi)) - ∑P (xi)log(Q(xi))
则,H(p, q) = - ∑P (xi)log(Q(xi)
对于one-hot 编码
Entrop = 1log1 = 0
二分类举例Binary Classification:
H(P,Q) = -P(cat)logQ(cat)-(1-p(cat))log(1-Q(cat))
P(dog) = (1-P(cat))
H(P,Q) = -∑p(xi)log(Q(xi)) ; i=(cat,log)
=-P(cat)logQ(cat)- p(dog)log(1-Q(cat))
= -(ylog(p)+(1-y)log(1-p))
多分类举例:
P1 = [1 0 0 0 0] —> label
Q1 = [0.4 0.3 0.05 0.05 0.2] —>pred
H(P1,Q1) = -∑p(xi)log(Q(xi)) ; i=range(5)
= -(1*log(0.4) + 0*log(0.3) + 0*log(0.05)+0*log(0.05)+0*log(0.2))
= -log(0.4)
≈ 0.916
Q1 = [0.98 0.01 0 0 0.01] —>pred
H(P1,Q1) = --∑p(xi)log(Q(xi)) ; i=range(5)
= -(1*log(0.98) + 0*log(0.01) + 0*log(0)+0*log(0)+0*log(0.01))
= -log(0.98)
≈ 0.02
(3)Softmax函数
假设原始的神经网络输出为y1, y2, y3, ..., yn,那么经过softmax回归处理之后的输出为:
softmax(y)i = y'i = eyi / (Σnj=1eyj)
这个新的输出,可以理解为经过神经网络的推导,一个样例为不同类别的概率分别是多少大。
1 #调用softmax函数 2 import torch 3 import torch.nn.functional as F1 4 a = torch.randint(3,10,(2,3),dtype=torch.float)#.long() 5 print(a) 6 b = F1.softmax(a,dim = 1) 7 b 8 9 输出: 10 tensor([[3., 7., 4.], 11 [3., 5., 8.]]) 12 tensor([[0.0171, 0.9362, 0.0466], 13 [0.0064, 0.0471, 0.9465]]) 14 15 #自定义softmax 16 for i in a: 17 sum_exp = torch.tensor([0],dtype=torch.float) 18 for k in i: 19 simpleexp = torch.exp(k) 20 sum_exp+=simpleexp 21 print(simpleexp,sum_exp) 22 print("**************************",i) 23 for j in i: 24 simpleexp = torch.exp(j) 25 print(simpleexp,simpleexp/sum_exp) 26 print("***********结束一轮***************") 27 28 输出: 29 tensor(20.0855) tensor([20.0855]) 30 tensor(1096.6332) tensor([1116.7188]) 31 tensor(54.5981) tensor([1171.3169]) 32 ************************** tensor([3., 7., 4.]) 33 tensor(20.0855) tensor([0.0171]) 34 tensor(1096.6332) tensor([0.9362]) 35 tensor(54.5981) tensor([0.0466]) 36 ***********结束一轮*************** 37 tensor(20.0855) tensor([20.0855]) 38 tensor(148.4132) tensor([168.4987]) 39 tensor(2980.9580) tensor([3149.4568]) 40 ************************** tensor([3., 5., 8.]) 41 tensor(20.0855) tensor([0.0064]) 42 tensor(148.4132) tensor([0.0471]) 43 tensor(2980.9580) tensor([0.9465]) 44 ***********结束一轮***************