1 简介
如下图所示,NN 是感知机的升级版,由输入层,若干隐藏层,输出层组成。其主要包含前向传播,反向传播等过程,下文会逐一分享。
2 前向传播
2.1 FP流程
与感知机类似,从输入层到输出层逐层计算,最后利用损失函数计算拟合误差。其中,核心就是神经元节点的权值计算,公式如下。
x
j
l
=
∑
k
w
j
k
l
y
k
l
−
1
+
b
j
l
y
j
l
=
σ
(
x
j
l
)
\begin{array}{l} x_{j}^{l}=\sum_{k} w_{j k}^{l} y_{k}^{l-1}+b_{j}^{l} \\ y_{j}^{l}=\sigma\left(x_{j}^{l}\right) \end{array}
xjl=∑kwjklykl−1+bjlyjl=σ(xjl)
其中,
x
j
l
x_{j}^{l}
xjl 表示第
l
l
l 层的第
j
j
j 个神经元的输入;
y
j
l
y_{j}^{l}
yjl 表示第
l
l
l 层的第
j
j
j 个神经元的输出;
w
j
k
l
w_{j k}^{l}
wjkl 表示第
l
−
1
l-1
l−1 层的第
k
k
k 个神经元指向第
l
l
l 层的第
j
j
j 个神经元的权值;
b
j
l
b_{j}^{l}
bjl 表示第
l
l
l 层的第
j
j
j 个神经元的偏移量,
σ
\sigma
σ 表示激活函数。
2.2 激活函数
激活函数就是非线性处理单元,常用的有 sigmoid, ReLU, tanh, Leaky ReLU, Softmax等。下表给出了激活函数的曲线图,等式,梯度值。
2.3 损失函数
损失函数,别名代价函数,目标函数,误差函数。主要用来度量网络实际输出与期望输出之间的误差,以便指导网络的参数学习。针对回归问题,一般采用平方损失等;针对分类问题,一般采用对数损失,交叉熵等。不同的损失函数会影响网络的训练速度与泛化能力。
-
回归问题
平方损失: L ( y , f ( x ) ) = ( y − f ( x ) ) 2 L(y, f(x))=(y-f(x))^{2} L(y,f(x))=(y−f(x))2
绝对值损失: L ( y , f ( x ) ) = ∣ y − f ( x ) ∣ L(y, f(x))=|y-f(x)| L(y,f(x))=∣y−f(x)∣
均方误差损失: L ( y , f ( x ) ) = 1 2 N ( y − f ( x ) ) 2 L(y, f(x))=\frac{1}{2N} (y-f(x))^{2} L(y,f(x))=2N1(y−f(x))2 -
二分类问题
例:对于样本(x,y),x为样本,y为对应的标签,在二分类问题中,其取值的集合可能为{0,1}。假设某个样本的真实标签为y,该样本的 y=1 的概率为 p p p,则该样本的交叉熵损失函数为: − ( y log ( p ) + ( 1 − y ) log ( 1 − p ) ) -(y \log (p)+(1-y) \log (1-p)) −(ylog(p)+(1−y)log(1−p))。 -
多分类问题
交叉熵与Softmax结合,如下图所示。
3 反向传播
3.1 BP流程
与前向传播相反,从输出层回溯到输入层,根据不同参数的影响更新 NN 的权重与偏移量,最终实现误差值的最小化。其中,核心就是如何计算不同参数对 NN的影响以及如何更新参数实现误差最小化。常用的方法是梯度下降算法。下图举例说明了此过程。
3.2 梯度下降
梯度下降法是最小化损失函数的一种常用的一阶优化方法,前提是凸函数,否则会陷入局部最小值。参数更新公式如下。
w
i
j
new
=
w
i
j
old
−
η
∂
E
∂
w
i
j
w_{i j}^{\text {new }}=w_{i j}^{\text {old }}-\eta \frac{\partial E}{\partial w_{i j}}
wijnew =wijold −η∂wij∂E
b
j
new
=
b
j
old
−
η
∂
E
∂
b
j
b_{j}^{\text {new }}=b_{ j}^{\text {old }}-\eta \frac{\partial E}{\partial b_{j}}
bjnew =bjold −η∂bj∂E
其中,
η
\eta
η 是学习率,值越大学习速度越快,当然不能过大,否则会跳过最优值;过小则训练成本过高,甚至无法收敛。
3.3 梯度下降训练策略
常用的有批次梯度下降BGD,随机梯度下降SGD,小批次梯度下降Mini-batch GD。三者对比图如下。
-
BGD
利用全部训练集计算损失函数的梯度来执行一次参数更新。缺点是更新较慢,不能在线更新网络,对非凸函数一般只能收敛到局部最小值。 -
SGD
对每一个训练样本点执行参数更新。优点是速度快,可在线学习;缺点是精度一般,损失函数下降过程波动较大。 -
Mini-batch GD
每n个训练样本点执行一次参数更新。优点是平稳收敛,速度快。batch大小一般取32,64,128,256等。
3.4 梯度下降优化算法
梯度下降优化算法一般包括如下几种,比较常用的是 SGD+Momentum 以及 Adam。
- SGD+Momentum方法最基本,调参较难
- RMSprop和Adadelta是AdaGrad改进方法
- RMSprop、Adadelta和Adam方法性能相近
- Adadelta方法无需设置学习率参数
- NAG方法在RNN网络中效果显著
下面介绍一下常用的 SGD+Momentum 以及 Adam。
-
SGD+Momentum
动量用来加速SGD,即将过去更新矢量的一部分加到当前矢量更新,公式如下。
v 1 = η ∇ J ( θ 1 ) v k = γ v k − 1 + η ∇ J ( θ k − 1 ) , γ ∈ ( 0 , 1 ) θ k = θ k − 1 − v k \begin{array}{l} v_{1}=\eta \nabla J\left(\theta_{1}\right) \\ v_{k}=\gamma{v_{k-1}}+\eta \nabla J\left(\theta_{k-1}\right), \quad \gamma \in(0,1) \\ \theta_{k}=\theta_{k-1}-v_{k} \end{array} v1=η∇J(θ1)vk=γvk−1+η∇J(θk−1),γ∈(0,1)θk=θk−1−vk -
Adam
Adam 是一种为每一个参数计算自适应学习率的方法,即存储了过去梯度平方的指数衰减均值 v t v_{t} vt,同时存储了过去梯度的指数衰减均值 m t m_{t} mt,类似动量。公式如下。
m t = β 1 m t − 1 + ( 1 − β 1 ) g t v t = β 2 v t − 1 + ( 1 − β 2 ) g t 2 \begin{aligned} m_{t} &=\beta_{1} m_{t-1}+\left(1-\beta_{1}\right) g_{t} \\ v_{t} &=\beta_{2} v_{t-1}+\left(1-\beta_{2}\right) g_{t}^{2} \end{aligned} mtvt=β1mt−1+(1−β1)gt=β2vt−1+(1−β2)gt2
Adam更新规则如下:
θ t + 1 = θ t − η v ^ t + ϵ m ^ t \theta_{t+1}=\theta_{t}-\frac{\eta}{\sqrt{\hat{v}_{t}}+\epsilon} \hat{m}_{t} θt+1=θt−v^t+ϵηm^t
其中, m ^ t = m t 1 − β 1 t v ^ t = v t 1 − β 2 t \begin{aligned} \hat{m}_{t} &=\frac{m_{t}}{1-\beta_{1}^{t}} \\ \hat{v}_{t} &=\frac{v_{t}}{1-\beta_{2}^{t}} \end{aligned} m^tv^t=1−β1tmt=1−β2tvt
4 实例
题目:利用NN实现MNIST手写数字识别。
import numpy as np
from sklearn.datasets import load_digits
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
# 载入数据
digits = load_digits()
print(digits.images.shape)
# 显示图片
plt.imshow(digits.images[0],cmap='gray')
plt.show()
(1797, 8, 8)
# 数据
X = digits.data
# 标签
y = digits.target
print(X.shape)
print(y.shape)
(1797, 64)
(1797,)
# 定义一个NN:64-100-10
# 定义输入层到隐藏层之间的权值矩阵
V = np.random.random((64,100))*2-1
# 定义隐藏层到输出层之间的权值矩阵
W = np.random.random((100,10))*2-1
# 数据切分:1/4为测试集,3/4为训练集
X_train,X_test,y_train,y_test = train_test_split(X,y)
# 标签二值化
labels_train = LabelBinarizer().fit_transform(y_train)
print(y_train[:5])
print(labels_train[:5])
[1 5 5 5 1]
[[0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]]
# 激活函数
def sigmoid(x):
return 1/(1+np.exp(-x))
# 激活函数的导数,注意此处x=y
def dsigmoid(x):
return x*(1-x)
# 训练模型
def train(X,y,steps=10000,lr=0.11):
global V,W
for n in range(steps+1):
# 随机选取一个数据
i = np.random.randint(X.shape[0])
# 获取一个数据
x = X[i]
x = np.atleast_2d(x) # 变成2维作矩阵运算
# 计算隐藏层的输出
L1 = sigmoid(np.dot(x,V))
# 计算输出的输出
L2 = sigmoid(np.dot(L1,W))
# 计算L2_delta,L1_delta
L2_delta = (y[i]-L2)*dsigmoid(L2)
L1_delta = L2_delta.dot(W.T)*dsigmoid(L1)
# 更新权值
W += lr*L1.T.dot(L2_delta)
V += lr*x.T.dot(L1_delta)
# 每训练1000次预测一次准确率
if n%1000==0:
output = predict(X_test)
predictions = np.argmax(output,axis=1)
acc = np.mean(np.equal(predictions,y_test))
print('steps:',n,'accuracy:',acc)
# 模型预测
def predict(x):
# 计算隐藏层的输出
L1 = sigmoid(np.dot(x,V))
# 计算输出的输出
L2 = sigmoid(np.dot(L1,W))
return L2
train(X_train,labels_train,30000)
steps: 0 accuracy: 0.08444444444444445
steps: 1000 accuracy: 0.52
steps: 2000 accuracy: 0.64
steps: 3000 accuracy: 0.7222222222222222
steps: 4000 accuracy: 0.7955555555555556
steps: 5000 accuracy: 0.8266666666666667
steps: 6000 accuracy: 0.84
steps: 7000 accuracy: 0.8444444444444444
steps: 8000 accuracy: 0.8555555555555555
steps: 9000 accuracy: 0.8577777777777778
steps: 10000 accuracy: 0.9488888888888889
steps: 11000 accuracy: 0.94
steps: 12000 accuracy: 0.9444444444444444
steps: 13000 accuracy: 0.9622222222222222
steps: 14000 accuracy: 0.9755555555555555
steps: 15000 accuracy: 0.9511111111111111
steps: 16000 accuracy: 0.9688888888888889
steps: 17000 accuracy: 0.9711111111111111
steps: 18000 accuracy: 0.9688888888888889
steps: 19000 accuracy: 0.9755555555555555
steps: 20000 accuracy: 0.9688888888888889
steps: 21000 accuracy: 0.9622222222222222
steps: 22000 accuracy: 0.9666666666666667
steps: 23000 accuracy: 0.9688888888888889
steps: 24000 accuracy: 0.9755555555555555
steps: 25000 accuracy: 0.9733333333333334
steps: 26000 accuracy: 0.9733333333333334
steps: 27000 accuracy: 0.98
steps: 28000 accuracy: 0.9711111111111111
steps: 29000 accuracy: 0.9644444444444444
steps: 30000 accuracy: 0.98
# 查看准确率,召回率,F1
output = predict(X_test)
predictions = np.argmax(output,axis=1)
print(classification_report(predictions,y_test))
precision recall f1-score support
0 1.00 1.00 1.00 43
1 1.00 0.94 0.97 48
2 1.00 0.98 0.99 54
3 0.95 0.98 0.97 43
4 0.96 1.00 0.98 43
5 1.00 0.98 0.99 48
6 1.00 0.98 0.99 41
7 1.00 0.98 0.99 53
8 0.89 0.98 0.93 43
9 1.00 1.00 1.00 34