# 吴恩达机器学习 - 神经网络的反向传播算法

## 首先让数据可视化

#### 执行代码

```load('ex4data1.mat');
m = size(X, 1);

sel = randperm(size(X, 1));     %乱序后随机选择100组数据进行展示
sel = sel(1:100);

displayData(X(sel, :));```

#### 用到是函数是displayData.m：

```function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid
% [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
% stored in X in a nice grid. It returns the figure handle h and the
% displayed array if requested.

% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2)));
end

% Gray Image
colormap(gray);

% Compute rows, cols
[m n] = size(X);
example_height = (n / example_width);

% Compute number of items to display
display_rows = floor(sqrt(m));
display_cols = ceil(m / display_rows);

% Setup blank display

% Copy each example into a patch on the display array
curr_ex = 1;
for j = 1:display_rows
for i = 1:display_cols
if curr_ex > m,
break;
end
% Copy the patch

% Get the max value of the patch
max_val = max(abs(X(curr_ex, :)));
display_array(pad + (j - 1) * (example_height + pad) + (1:example_height), ...
pad + (i - 1) * (example_width + pad) + (1:example_width)) = ...
reshape(X(curr_ex, :), example_height, example_width) / max_val;
curr_ex = curr_ex + 1;
end
if curr_ex > m,
break;
end
end

% Display Image
h = imagesc(display_array, [-1 1]);

% Do not show axis
axis image off

drawnow;

end```

## 表示一下神经网络模型：

#### 我们可以得到以下信息：

• 3层网络
• 输入层有400（20*20的图像样本）个单元（这里不包括偏置单元）
• 输出层有10个（表示0，1，2，…，9）单元
• 隐藏层有25个单元

## 代价函数

#### sigmoid.m代码（这个已经没有难度，只是下面要调用，先粘出来）：

```function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
% J = SIGMOID(z) computes the sigmoid of z.

g = 1.0 ./ (1.0 + exp(-z));
end```

#### 代价函数的计算：nnCostFunction.m中填充的代码（暂时没加正则化）（这里要求有任意维度的输出层都通用）：

```%计算各层的z(x)
a1 = [ones(m,1), X];        %input
z2 = a1*Theta1';       %hidden
a2 = [ones(m,1), sigmoid(z2)];
z3 = a2*Theta2';       %output
a3 = sigmoid(z3);

%转换y向量
Y = zeros(m, size(Theta2, 1));        %适应不同维度的输出层
for i = 1:size(Theta2, 1)
Y(find(y==i), i) = 1;
end

%然后计算J
J = sum(sum(-(Y.*log(a3)+(1-Y).*log(1-a3))))/m;```

#### 代价函数正则化（在上面的代码下添加）：

```%对J进行正则化
J = J + lambda/(2.0*m)* ...
(sum(sum(Theta1(:,2:size(Theta1,2)).^2))+ ...
sum(sum(Theta2(:,2:size(Theta2,2)).^2)));```

## 反向传播

```function g = sigmoidGradient(z)
%evaluated at z
% evaluated at z. This should work regardless if z is a matrix or a
% vector. In particular, if z is a vector or matrix, you should return
% the gradient for each element.

g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the gradient of the sigmoid function evaluated at
% each value of z (z can be a matrix, vector or scalar).

g = sigmoid(z).*(1-sigmoid(z));

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

end```

#### 随机初始化（randInitializeWeights.m）（因为权重不能全为0嘛，笔记上解释了为什么）：

```function W = randInitializeWeights(L_in, L_out)
%RANDINITIALIZEWEIGHTS Randomly initialize the weights of a layer with L_in
%incoming connections and L_out outgoing connections
% W = RANDINITIALIZEWEIGHTS(L_in, L_out) randomly initializes the weights
% of a layer with L_in incoming connections and L_out outgoing
% connections.
%
% Note that W should be set to a matrix of size(L_out, 1 + L_in) as
% the first column of W handles the "bias" terms
%

% You need to return the following variables correctly
W = zeros(L_out, 1 + L_in);

% ====================== YOUR CODE HERE ======================
% Instructions: Initialize W randomly so that we break the symmetry while
% training the neural network.
%
% Note: The first column of W corresponds to the parameters for the bias unit
%

epsilon_init = 0.12;        %这个数字要小一点从而保证较高的学习效率
W = rand(L_out, 1+L_in)*2*epsilon-epsilon_init;

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

end```

#### 反向传播（填充在nnCostFunction.m中，代价函数计算代码之下，注意这里没有正则化）：

```%开始反向传播，分5部计算梯度
%1.对于输入层，计算每个样本的激活值（上面已经实现）

%2.计算输出层的误差值
delta3 = a3 - Y;

%3.计算l=2层的误差值（这里由于矩阵的方向的不同，和文档中式子不太一样）

%4.用公式计算DELTA（delta的大写形式）
DELTA1 = delta2'*a1;
DELTA2 = delta3'*a2;

%5.除以样本数得到梯度

```function checkNNGradients(lambda)
%CHECKNNGRADIENTS Creates a small neural network to check the
% CHECKNNGRADIENTS(lambda) Creates a small neural network to check the
% result in very similar values.
%

if ~exist('lambda', 'var') || isempty(lambda)
lambda = 0;
end

input_layer_size = 3;
hidden_layer_size = 5;
num_labels = 3;
m = 5;

% We generate some 'random' test data
Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size);
Theta2 = debugInitializeWeights(num_labels, hidden_layer_size);
% Reusing debugInitializeWeights to generate X
X  = debugInitializeWeights(m, input_layer_size - 1);
y  = 1 + mod(1:m, num_labels)'; % Unroll parameters nn_params = [Theta1(:) ; Theta2(:)]; % Short hand for cost function costFunc = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size, ... num_labels, X, y, lambda); [cost, grad] = costFunc(nn_params); numgrad = computeNumericalGradient(costFunc, nn_params); % Visually examine the two gradient computations. The two columns % you get should be very similar. disp([numgrad grad]); fprintf(['The above two columns you get should be very similar.\n' ...

% Evaluate the norm of the difference between two solutions.
% If you have a correct implementation, and assuming you used EPSILON = 0.0001
% in computeNumericalGradient.m, then diff below should be less than 1e-9

fprintf(['If your backpropagation implementation is correct, then \n' ... 'the relative difference will be small (less than 1e-9). \n' ... '\nRelative Difference: %g\n'], diff);

end```

#### 好了，检验通过我们进行下一步：正则化梯度（nnCostFunction.m）（在上面计算梯度的代码下填充）：

```%正则化梯度

#### 到此为止，计算代价以及计算梯度的过程我们已经完成了，下面贴出nnCostFunction.m的完整代码：

```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;

% ====================== 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
%
% Part 2: Implement the backpropagation algorithm to compute the gradients
% the cost function with respect to Theta1 and Theta2 in Theta1_grad and
% Theta2_grad, respectively. After implementing Part 2, you can check
%
% 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.
%
% 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
% and Theta2_grad from Part 2.
%

%本地数据的矩阵大小
%Theta1:25*401
%Theta2:10*26
%X:5000*400
%z1:5000*401
%z2:5000*25
%z3:5000*10
%y:5000*1
%Y:5000*10
%a1:5000*401
%a2:5000*26
%a3:5000*10
%delta3:5000*10
%delta2:5000*25

%计算各层的z(x)
a1 = [ones(m,1), X];        %input
z2 = a1*Theta1';       %hidden
a2 = [ones(m,1), sigmoid(z2)];
z3 = a2*Theta2';       %output
a3 = sigmoid(z3);

%转换y向量
Y = zeros(m, size(Theta2, 1));        %适应不同维度的输出层
for i = 1:size(Theta2, 1)
Y(find(y==i), i) = 1;
end

%然后计算J
J = sum(sum(-(Y.*log(a3)+(1-Y).*log(1-a3))))/m;

%对J进行正则化
J = J + lambda/(2.0*m)* ...
(sum(sum(Theta1(:,2:size(Theta1,2)).^2))+ ...
sum(sum(Theta2(:,2:size(Theta2,2)).^2)));

%开始反向传播，分5部计算梯度
%1.对于输入层，计算每个样本的激活值（上面已经实现）

%2.计算输出层的误差值
delta3 = a3 - Y;

%3.计算l=2层的误差值（这里由于矩阵的方向的不同，和文档中式子不太一样）

%4.用公式计算DELTA（delta的大写形式）
DELTA1 = delta2'*a1;
DELTA2 = delta3'*a2;

%5.除以样本数得到梯度

%正则化梯度

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

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

end```

## 学习使用高级优化来求解（如果对写法有疑惑，可以参考这篇文章：点击打开链接）：

```% Create "short hand" for the cost function to be minimized
costFunction = @(p) nnCostFunction(p, ...
input_layer_size, ...
hidden_layer_size, ...
num_labels, X, y, lambda);

% Now, costFunction is a function that takes in only one argument (the
% neural network parameters)
[nn_params, cost] = fmincg(costFunction, initial_nn_params, options);```

## 可视化隐藏层（使用`displayData(Theta1(:, 2:end));`）：

##### displayData.m：
```function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid
% [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
% stored in X in a nice grid. It returns the figure handle h and the
% displayed array if requested.

% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2)));
end

% Gray Image
colormap(gray);

% Compute rows, cols
[m n] = size(X);
example_height = (n / example_width);

% Compute number of items to display
display_rows = floor(sqrt(m));
display_cols = ceil(m / display_rows);

% Setup blank display

% Copy each example into a patch on the display array
curr_ex = 1;
for j = 1:display_rows
for i = 1:display_cols
if curr_ex > m,
break;
end
% Copy the patch

% Get the max value of the patch
max_val = max(abs(X(curr_ex, :)));
display_array(pad + (j - 1) * (example_height + pad) + (1:example_height), ...
pad + (i - 1) * (example_width + pad) + (1:example_width)) = ...
reshape(X(curr_ex, :), example_height, example_width) / max_val;
curr_ex = curr_ex + 1;
end
if curr_ex > m,
break;
end
end

% Display Image
h = imagesc(display_array, [-1 1]);

% Do not show axis
axis image off

drawnow;

end```