NN & BP Algorithm

神经网络 & 反向传播算法

神经网络基本的表示方法网上有许多资料,我就不再赘述了。对我来说最难的部分是反向传播算法,我花了许多时间去理解反向传播算法。

链式求导

反向传播算法就是复合函数链式求导的一个应用,什么是链式求导呢?

以求 $ e=(a+b)*(b+1) $ 的偏导数为例子

根据链式法制,

$\frac{\delta e}{\delta a} = \frac{\delta e}{\delta c} \frac{\delta c}{\delta a}$

$\frac{\delta e}{\delta b} = \frac{\delta e}{\delta c} \frac{\delta c}{\delta b} + \frac{\delta e}{\delta d} \frac{\delta d}{\delta b}$

不难发现, $\frac{\delta e}{\delta a}$ 和 $\frac{\delta e}{\delta b}$ 的计算路径有重复项,反向传播算法避免了重复计算,有点类似动态规划的思想。反向传播算法反向逐层计算偏导数,实现只通过一次计算,得出代价函数对所有参数的梯度。

反向传播算法过程

编程作业4给的神经网络模型如下

如何利用反向传播算法求 $\theta^{(1)}$ 和 $\theta^{(2)}$ 呢?

首先假设代价函数的符号为 E,并且有如下表达式

下面内容就是我自己根据链式求导法则推的,因为很多文章直接引入一个叫“误差项”的概念,非常难理解。

根据链式求导法则,可以得出:

$\frac{\delta E}{\delta \theta^{(2)}} = \frac{\delta E}{\delta a^{(3)}} \frac{\delta a^{(3)}}{\delta z^{(3)}} \frac{\delta z^{(3)}}{\delta \theta^{(2)}}$

$\frac{\delta E}{\delta \theta^{(1)}} = \frac{\delta E}{\delta a^{(3)}} \frac{\delta a^{(3)}}{\delta z^{(3)}} \frac{\delta z^{(3)}}{\delta a^{(2)}} \frac{\delta a^{(2)}}{\delta z^{(2)}} \frac{\delta a^{(2)}}{\delta \theta^{(1)}}$

$\delta^{(3)} = \frac{\delta E}{\delta a^{(3)}}\frac{\delta a^{(3)}}{\delta z^{(3)}} = a^{(3)} - y$

$\delta^{(2)} = \frac{\delta E}{\delta a^{(3)}} \frac{\delta a^{(3)}}{\delta z^{(3)}} \frac{\delta z^{(3)}}{\delta a^{(2)}} \frac{\delta a^{(2)}}{\delta z^{(2)}} = (\theta^{(2)})^T\delta^{(3)}g’(z^{(2)})$

代入偏导数公式合并

$\frac{\delta E}{\delta \theta^{(2)}} = \delta^{(3)}g’(z^{3})$

$\frac{\delta E}{\delta \theta^{(1)}} = \delta^{(2)}g’(z^{2})$

用上面这两个公式就可以算梯度了,每一轮迭代算出所有训练集的梯度和,最后用平均梯度来代替当前次迭代的梯度。

$\delta^{(3)}$ 的求导可以看参考文献[4],交叉商的求导。看起来很像平方误差的导数….其实并不是。

lab4 代码

向量化实现 nnCostFunction 代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
function [J grad] = nnCostFunction(nn_params, ...
input_layer_size, ...
hidden_layer_size, ...
num_labels, ...
X, y, lambda)
%NNCOSTFUNCTION Implements the neural network cost function for a two layer
%neural network which performs classification
% [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...
% X, y, lambda) computes the cost and gradient of the neural network. The
% parameters for the neural network are "unrolled" into the vector
% nn_params and need to be converted back into the weight matrices.
%
% The returned parameter grad should be a "unrolled" vector of the
% partial derivatives of the neural network.
%

% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices
% for our 2 layer neural network
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
hidden_layer_size, (input_layer_size + 1));

Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
num_labels, (hidden_layer_size + 1));

% Setup some useful variables
m = size(X, 1);

% You need to return the following variables correctly
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the code by working through the
% following parts.
%
% Part 1: Feedforward the neural network and return the cost in the
% variable J. After implementing Part 1, you can verify that your
% cost function computation is correct by verifying the cost
% computed in ex4.m
%

% reshape y
y_ = zeros(m, num_labels);
for i = 1:m
y_(i, y(i)) = 1;
end
a1 = [ones(m, 1) X];

% hiden layer
z2 = a1 * Theta1';
a2 = [ones(m, 1) sigmoid(z2)];

% output layer
z3 = a2 * Theta2';
a3 = sigmoid(z3);


t = -y_ .* log(a3) - (1 - y_) .* log(1 - (a3));


tmpJ = (1 / m) * sum(sum(t));


% Regularized cost function
T1 = Theta1(:, 2:end).^2;
T2 = Theta2(:, 2:end).^2;
rr = sum(sum(T1)) + sum(sum(T2));
rr = (lambda / (2 * m)) * rr;
J = tmpJ + rr;


% Part 2: Implement the backpropagation algorithm to compute the gradients
% Theta1_grad and Theta2_grad. You should return the partial derivatives of
% the cost function with respect to Theta1 and Theta2 in Theta1_grad and
% Theta2_grad, respectively. After implementing Part 2, you can check
% that your implementation is correct by running checkNNGradients
%
% Note: The vector y passed into the function is a vector of labels
% containing values from 1..K. You need to map this vector into a
% binary vector of 1's and 0's to be used with the neural network
% cost function.
%
% Hint: We recommend implementing backpropagation using a for-loop
% over the training examples if you are implementing it for the
% first time.

% h1: 5000 * 25
% h2: 5000 * 10
sum_Theta2 = zeros(size(Theta2));
sum_Theta1 = zeros(size(Theta1));
for i = 1:m
d3 = (a3(i, :) - y_(i, :))'; % 10 X 1
d2 = (Theta2' * d3 .* sigmoidGradient([1 z2(i, :)])');
d2 = d2(2:end, 1); % 25 X 1

sum_Theta2 = sum_Theta2 + (d3 * a2(i, :));
sum_Theta1 = sum_Theta1 + (d2 * a1(i, :));
end
term1 = lambda .* Theta1;
term2 = lambda .* Theta2;

% Part 3: Implement regularization with the cost function and gradients.
%
% Hint: You can implement this around the code for
% backpropagation. That is, you can compute the gradients for
% the regularization separately and then add them to Theta1_grad
% and Theta2_grad from Part 2.
%

% -------------------------------------------------------------

% =========================================================================

% Unroll gradients
Theta1_grad = (sum_Theta1 + term1) ./ m;
Theta2_grad = (sum_Theta2 + term2) ./ m;
grad = [Theta1_grad(:) ; Theta2_grad(:)];

end

参考

[1] https://zhuanlan.zhihu.com/p/40378224 “Back Propagation(梯度反向传播)实例讲解”
[2] https://www.zhihu.com/question/27239198/answer/89853077 “如何直观地解释 backpropagation 算法?”
[3] http://neuralnetworksanddeeplearning.com/chap2.html “How the backpropagation algorithm works”
[4] https://blog.csdn.net/Jerry_Lu_ruc/article/details/107974072 “关于交叉熵下softmax和sigmoid的求导”


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!