后向传播(backpropagation)算法介绍
一、引入
后向传播算法在Learning representations by back-propagating errors这篇文章中被提到。
这个算法和链式法则结合用于有效地训练神经网络。在每次对网络的前向传播之后,后向传播算法进行后向传播以调整模型(model)参数(权重和偏差)。
二、神经网络基本结构介绍
1.神经网络定义
以下定义了一个4层神经网络。它的输入层有4个神经元,隐藏层有4个神经元,输出层有一个神经元。

2.输入层
上图中紫色的神经元是输入层,代表了输入数据(可以是标量或者向量甚至是多维矩阵。

第一套activation(a)其实就是输入的值。“activation”是执行了激活函数之后的神经元的值。
3.隐藏层
隐藏层神经元的值,是基于z^l (第l层的权重)和a^l(第l层的激活)进行计算的。对第二层和第三层,有以下公式:
- l=2

- l=3

a^2 和 a^3是用激活函数f来计算的。相关阅读链接
注意以上的x,z,a,b是不含下标的。因为所有的参数值都隐藏在了每一层的对应矩阵的具体参数(含下标)中。以第二层(隐藏层)和其参数为例:
W^1是尺寸为(n,m)的权重矩阵,n为输出神经元的数目,m为输入神经元的数目。对我们的神经网络来说,n=2,m=4。

权重矩阵公式中,下标的第一个数字对应下一层的神经元的需要,第二个数字代表上一层的神经元序号。
x是尺寸为(m,1)的输入向量,m是输入神经元的数目。在我们的例子中,m=4。

b^1是尺寸为(n,1)权重向量。n为当前层的神经元的数目。在我们的例子中,n=2。

进而有以下公式:

z^2 能由 (z_1)^2 和 (z_2)^2 来表示。 (z_1)^2 和 (z_2)^2 是网络输入和对应权重的乘积之和。
4. 输出层

类似地,我们用矩阵表达式来简化公式。把矩阵表达式具体化就可以得到更具体的运算过程。
三、前向传播(forward propagation)和结果评价(evaluation)
上面的公式其实就诠释了前向传播。以下是一个总体概览,公式颜色和神经元的颜色对应:

前向传播的最后一步是对比预测结果(predicted output) s和期待结果(expected output) y,损失函数(cost function)可以计算出对比的结果。

基于C的值,模型能去感知需要调整多少参数以接近预期输出y。这个调整是通过后向传播算法实现的。
损失函数介绍总结
MSE
cross-entropy交叉熵
四、后向传播(backpropagation)和梯度计算
1. 后向传播算法
根据后向传播最原始的论文,后向传播的定义如下:
repeatedly adjusts the weights of the connections in the network so as to minimize a measure of the difference between the actual output vector of the net and the desired output vector.
和
the ability to create useful new features distinguishes back-propagation from earlier, simpler methods…
也就是说,后向传播算法通过调整网络的权重和偏差来最小化损失函数。调整的程度取决于损失函数的梯度。
2. 梯度计算
为什么要计算梯度?
为了回答这个问题,我们先来复习如下微积分理论:
函数C(x_1, x_2, …, x_m) 在点x(即(x_1, x_2, …, x_m))处的梯度是x对函数C的偏微分组成的向量。

函数C的导数度量了函数的输出对改变输入x的敏感程度。可以理解为,导数告诉我们C的走向。
梯度展现了我么需要改变多少x以最小化C。
计算梯度常常需要用到链式法则。
对某一个权重 (w_jk)^l ,梯度计算如下:

sidenote: 对上面公式的理解,C是损失函数,损失函数对权重求导反应了权重的改变量将会如何影响损失函数。z是这一层的激活前输出,具体是该权重和上一层的输入相乘再相应偏差相加计算得到的对应神经元的值;a是上一层的输出(激活后的输出)。
类似地,对某一个偏差的导数 (b_j)^l 的导数计算:

两个公式中的共同部分是“局部梯度”(local gradient),表达如下:

局部梯度能通过链式法则很容易地计算出来。
梯度能最优化模型参数:(w沿着C对w的导数下降的方向改变能达到最小化C的效果)

梯度下降算法(gradient descent)
- 初始化w和b
- 上述公式中的e是学习率。学习率决定了梯度的影响程度
- w和b是代表权重和偏差的矩阵。w和b对函数C的微分可以由每一个独立的权重和偏差对C的偏导数计算出来。
- 终止条件(Termination condition)是损失函数被最小化了。
五、 梯度下降算法的例子
我们去看上述神经网络的最底层。我们以计算C对W_22的导数为例。

(W_22)^2 连接了 (a_2)^2 和 (z_2)^3,因此计算权重需要我们把链式法则应用于 (z_2)^3 and (a_2)^3:

第二个式子的第二项即 (a_2)^2,第一项可以用链式法则分解成两项。
这里是推导过程,但是可以总结为:对反向传播到(a_2)^2前的每一个神经元的值逐一求偏导。
C对 (a_2)³ 的导数的计算需要知道C的函数表达式。C是依赖于 (a_2)³ 的,因此对导数的计算应该是很直接的。
sidenote:这里举个例子,如果C=S-Y=(W^3)*(a_2)³-Y,那么C对 (a_2)³ 的导数就是(W^3)。
额外阅读材料:Stanford’s NLP series where Richard Socher gives 4 great explanations of backpropagation.