[关闭]
@EtoDemerzel 2017-11-18T14:39:49.000000Z 字数 12617 阅读 2689

机器学习week5 ex4 review


机器学习 吴恩达

这周的作业主要关于反向传播算法(Backpropagation ,or BP)


1 Neural Networks

在上一次exercise里,我们通过使用神经网络的前馈传播算法(feedforward propagation),利用给定的权重来识别手写的数字。在这一此我们需要通过反向传播算法计算出权重

1.1 Visualizing the data

脚本文件ex4.m通过调用函数displayData载入数据,并以二维图像的形式展示。(以下代码随机选择其中的100个数字进行展示)

  1. load('ex4data1.mat');
  2. m = size(X, 1);
  3. % Randomly select 100 data points to display
  4. sel = randperm(size(X, 1));
  5. sel = sel(1:100);
  6. displayData(X(sel, :));


这次的数据与上次exercise相同,都是如下图片:
image_1bu62cukt1lljuqjc99tsc1ctd9.png-61.2kB
包含了5000个training example,每个training example是一张20*20像素的写有数字的灰度图。每一个像素用一个浮点数表示,代表其灰度的强度。把这个20*20的网格“展开成”一个大小为400的向量,放在矩阵 的每一行。

training example的第二部分是一个大小为5000的向量 ,作为每个 的标签。为了适配Octave/MATLAB的下标风格,这里没有0下标:"1"-"9"按"1"-"9"标记,而"0"以10标记。

1.2 Model representation

我们的神经网络如下图所示:
image_1bu64knur16of83tjiu1bu119nam.png-59.5kB
很显然,它具有三个层次:输入层隐藏层,和输出层。注意到,我们的输入数据是一个数字的图片的像素值,而一张图片共有400个像素,这说明我们的输入层单元有400个(不算偏置单元)。

ex4weights.mat已经给我们提供了一组被训练好的参数()。他们会在ex4.m中被载入到Theta1Theta2中,并展开成向量形式,合并存入向量nn_params中。Theta1Theta2的大小被设置为与隐藏层中有25个单元、输出层有10个单元的情况匹配。(也就是说, 的尺寸为 , 而 的尺寸为 )。

ex4.m中这部分代码如下:

  1. % Load the weights into variables Theta1 and Theta2
  2. load('ex4weights.mat');
  3. % Unroll parameters
  4. nn_params = [Theta1(:) ; Theta2(:)];

这里把Theta1Theta2展开,存入了一个向量nn_params

1.3 Feedforward and cost function

现在需要我们为神经网络计算代价函数和梯度。
神经网络的代价函数公式如下(没有经过正规化处理):

之前 的标签被定为1-10的整数,为了训练神经网络,我们需要将他们转换成如下向量形式来表示:

这样我们就可以开始计算代价函数了。
完成nnCostFunction中的代码,如下:

  1. % Part 1
  2. % calculate the hypothetical function
  3. a1 = [ones(m,1) X];
  4. z2 = a1 * Theta1';
  5. h1 = sigmoid(z1);
  6. a2 = [ones(size(h1,1),1) h1];
  7. h = sigmoid(a2 * Theta2');
  8. % transform y into vectors
  9. y_vec = eye(num_labels)(y,:);
  10. % then calculate the cost function
  11. J = -1/m * (sum(sum(y_vec.*log(h) + (1-y_vec).*log(1-h))));

ex4.m中这部分的代码如下:

  1. %% ================ Part 3: Compute Cost (Feedforward) ================
  2. % To the neural network, you should first start by implementing the
  3. % feedforward part of the neural network that returns the cost only. You
  4. % should complete the code in nnCostFunction.m to return cost. After
  5. % implementing the feedforward to compute the cost, you can verify that
  6. % your implementation is correct by verifying that you get the same cost
  7. % as us for the fixed debugging parameters.
  8. %
  9. % We suggest implementing the feedforward cost *without* regularization
  10. % first so that it will be easier for you to debug. Later, in part 4, you
  11. % will get to implement the regularized cost.
  12. %
  13. fprintf('\nFeedforward Using Neural Network ...\n')
  14. % Weight regularization parameter (we set this to 0 here).
  15. lambda = 0;
  16. J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
  17. num_labels, X, y, lambda);
  18. fprintf(['Cost at parameters (loaded from ex4weights): %f '...
  19. '\n(this value should be about 0.287629)\n'], J);
  20. fprintf('\nProgram paused. Press enter to continue.\n');
  21. pause;

可以看出,这里设置lambda等于0来调用nnCostFunction函数。这暂时还无关紧要,因为我们还没有进行正规化处理。

这时候运行ex4.m
image_1bu6fppj3lht1rkt139f1hem1spo9.png-7.5kB
显示结果正确。

1.4 Regularized cost function

经过正规化处理后的代价函数公式如下:

以上公式是针对本次练习中的情况写的。说明中特别提到,我们可以仅考虑三层神经网络的情况,但我们的代码必须对各种大小 都奏效。
这时候完成nnCostFunction中的这部分代码:

  1. % remember that you don't have to regularize the first column
  2. J = J + lambda/(2*m)*(sum(sum(Theta1(:,2:end).^2))+sum(sum(Theta2(:,2:end).^2)));

ex4.m中,这部分代码如下:

  1. %% =============== Part 4: Implement Regularization ===============
  2. % Once your cost function implementation is correct, you should now
  3. % continue to implement the regularization with the cost.
  4. %
  5. fprintf('\nChecking Cost Function (w/ Regularization) ... \n')
  6. % Weight regularization parameter (we set this to 1 here).
  7. lambda = 1;
  8. J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
  9. num_labels, X, y, lambda);
  10. fprintf(['Cost at parameters (loaded from ex4weights): %f '...
  11. '\n(this value should be about 0.383770)\n'], J);
  12. fprintf('Program paused. Press enter to continue.\n');
  13. pause;

这里lambda被设置为1。

这里要非常注意, 是不需要进行正规化的
如果你不慎忘记了这一点(就像我一样),就会得到下面的错误结果:
image_1bu6gcpps1f0ib3hcics72mnhm.png-9.6kB

修正之后,得到正确答案:
image_1bu6ggas51ifnss2pbbf1f1kgo26.png-9.7kB


2. Backpropagation

经过之前的步骤,函数nnCostFunction已经可以返回正确的代价函数 ,接下来的步骤我们需要让它能够计算出正确的梯度。

2.1 Sigmoid Gradient

根据公式

其中
接下来利用上述公式,完成函数sigmoidGradient。函数需要对 是数字、向量、矩阵的情况都奏效。
代码如下:

  1. function g = sigmoidGradient(z)
  2. %SIGMOIDGRADIENT returns the gradient of the sigmoid function
  3. %evaluated at z
  4. % g = SIGMOIDGRADIENT(z) computes the gradient of the sigmoid function
  5. % evaluated at z. This should work regardless if z is a matrix or a
  6. % vector. In particular, if z is a vector or matrix, you should return
  7. % the gradient for each element.
  8. g = zeros(size(z));
  9. % ====================== YOUR CODE HERE ======================
  10. % Instructions: Compute the gradient of the sigmoid function evaluated at
  11. % each value of z (z can be a matrix, vector or scalar).
  12. g = sigmoid(z) .* (1 - sigmoid(z))
  13. % =============================================================
  14. end

ex4.m中对这部分的检验代码如下:

  1. %% ================ Part 5: Sigmoid Gradient ================
  2. % Before you start implementing the neural network, you will first
  3. % implement the gradient for the sigmoid function. You should complete the
  4. % code in the sigmoidGradient.m file.
  5. %
  6. fprintf('\nEvaluating sigmoid gradient...\n')
  7. g = sigmoidGradient([-1 -0.5 0 0.5 1]);
  8. fprintf('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n ');
  9. fprintf('%f ', g);
  10. fprintf('\n\n');
  11. fprintf('Program paused. Press enter to continue.\n');
  12. pause;

可以看出,它检验的是矩阵
得到结果如下:
image_1bu836u2i1glrco61hh61n6a15ts37.png-5.8kB

2.2 Random initialization

在使用fminunc等高级优化算法时,我们需要提供一个 的初始值。如果我们像往常一样以零矩阵为初始,会导致每一层神经网络的不同单元相同。利用反向传播算法后,计算得到的偏导数也相同。也就是说,整个过程中,他们始终会保持相同。这是不符合要求的。

因此我们需要进行随机初始化
采取的做法是使 处在 的范围上。
约定 。(一般的方法是根据 来得到 。)
完成randInitializeWeights中的代码如下:

  1. function W = randInitializeWeights(L_in, L_out)
  2. %RANDINITIALIZEWEIGHTS Randomly initialize the weights of a layer with L_in
  3. %incoming connections and L_out outgoing connections
  4. % W = RANDINITIALIZEWEIGHTS(L_in, L_out) randomly initializes the weights
  5. % of a layer with L_in incoming connections and L_out outgoing
  6. % connections.
  7. %
  8. % Note that W should be set to a matrix of size(L_out, 1 + L_in) as
  9. % the first column of W handles the "bias" terms
  10. %
  11. % You need to return the following variables correctly
  12. W = zeros(L_out, 1 + L_in);
  13. % ====================== YOUR CODE HERE ======================
  14. % Instructions: Initialize W randomly so that we break the symmetry while
  15. % training the neural network.
  16. %
  17. % Note: The first column of W corresponds to the parameters for the bias unit
  18. %
  19. % Randomly initialize the weights to small values
  20. epsilon_init = 0.12;
  21. W = rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init
  22. % =========================================================================
  23. end

ex4.m中这部分代码如下:

  1. %% ================ Part 6: Initializing Pameters ================
  2. % In this part of the exercise, you will be starting to implment a two
  3. % layer neural network that classifies digits. You will start by
  4. % implementing a function to initialize the weights of the neural network
  5. % (randInitializeWeights.m)
  6. fprintf('\nInitializing Neural Network Parameters ...\n')
  7. initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size);
  8. initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels);
  9. % Unroll parameters
  10. initial_nn_params = [initial_Theta1(:) ; initial_Theta2(:)];

初始化完成后,再将Theta1Theta2展开存入一个向量中。

2.3 Backpropagation

image_1bu7cr4bnmho13hcvh8j2d1uea9.png-53.6kB

按照上面两张图所示的步骤,我们实现反向传播算法的步骤大致如下:
使用一个对i = 1:mfor循环,i表示的是training example的编号,即
在每次循环中,
1. 设置输入层 。使用前向传播,计算出 应该添加偏置单元。
2. 对输出层的每个单元(编号为 ), 令 ,其中 ,代表当前training example是否是第 类。
3. 对于第二层(隐藏层), 令 。而输入层不存在误差。
4. 累加以计算梯度(注意要去掉 ):

5. 计算(未经正规化的)神经网络的梯度如下:

这部分代码如下:

  1. % Part 2
  2. d3 = h - y_vec;
  3. d2 = (d3*Theta2)(:,2:end).* sigmoidGradient(z2);
  4. D1 = d2' * a1;
  5. D2 = d3' * a2;
  6. Theta1_grad = Theta1_grad + (1/m) * D1;
  7. Theta2_grad = Theta2_grad + (1/m) * D2;

ex4.m中对这部分的检验代码:

  1. %% =============== Part 7: Implement Backpropagation ===============
  2. % Once your cost matches up with ours, you should proceed to implement the
  3. % backpropagation algorithm for the neural network. You should add to the
  4. % code you've written in nnCostFunction.m to return the partial
  5. % derivatives of the parameters.
  6. %
  7. fprintf('\nChecking Backpropagation... \n');
  8. % Check gradients by running checkNNGradients
  9. checkNNGradients;
  10. fprintf('\nProgram paused. Press enter to continue.\n');
  11. pause;

其中checkNNGradient是为我们提供的检验梯度的函数。

运行后结果如下:
image_1bu83ikh111ap91inhb126tlmt3k.png-53.6kB
和正确答案相符。并且与gradient checking求出的差异很小:
image_1bu83k594a6qd6d1iaighg1i0241.png-7.6kB

2.4 Gradient checking

Gradient checking是用于对反向传播算法计算结果的检验。用如下方法计算:
image_1bu849op61je91m8ss8jv5qc123.png-64.1kB
实现代码如下:

  1. function numgrad = computeNumericalGradient(J, theta)
  2. %COMPUTENUMERICALGRADIENT Computes the gradient using "finite differences"
  3. %and gives us a numerical estimate of the gradient.
  4. % numgrad = COMPUTENUMERICALGRADIENT(J, theta) computes the numerical
  5. % gradient of the function J around theta. Calling y = J(theta) should
  6. % return the function value at theta.
  7. % Notes: The following code implements numerical gradient checking, and
  8. % returns the numerical gradient.It sets numgrad(i) to (a numerical
  9. % approximation of) the partial derivative of J with respect to the
  10. % i-th input argument, evaluated at theta. (i.e., numgrad(i) should
  11. % be the (approximately) the partial derivative of J with respect
  12. % to theta(i).)
  13. %
  14. numgrad = zeros(size(theta));
  15. perturb = zeros(size(theta));
  16. e = 1e-4;
  17. for p = 1:numel(theta)
  18. % Set perturbation vector
  19. perturb(p) = e;
  20. loss1 = J(theta - perturb);
  21. loss2 = J(theta + perturb);
  22. % Compute Numerical Gradient
  23. numgrad(p) = (loss2 - loss1) / (2*e);
  24. perturb(p) = 0;
  25. end
  26. end

2.5 Regularized neural networks

正规化后的偏导数公式如下:

只需增加如下代码:

  1. % Part 3
  2. Theta1_grad(:,2:end) = Theta1_grad(:,2:end) + (lambda/m)*(Theta1(:,2:end));
  3. Theta2_grad(:,2:end) = Theta2_grad(:,2:end) + (lambda/m)*(Theta2(:,2:end));

ex4.m中这部分检验代码:

  1. %% =============== Part 8: Implement Regularization ===============
  2. % Once your backpropagation implementation is correct, you should now
  3. % continue to implement the regularization with the cost and gradient.
  4. %
  5. fprintf('\nChecking Backpropagation (w/ Regularization) ... \n')
  6. % Check gradients by running checkNNGradients
  7. lambda = 3;
  8. checkNNGradients(lambda);
  9. % Also output the costFunction debugging values
  10. debug_J = nnCostFunction(nn_params, input_layer_size, ...
  11. hidden_layer_size, num_labels, X, y, lambda);
  12. fprintf(['\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' ...
  13. '\n(for lambda = 3, this value should be about 0.576051)\n\n'], lambda, debug_J);
  14. fprintf('Program paused. Press enter to continue.\n');
  15. pause;

注意到这里checkNNGradient函数这里带上了参数lambda。这里它被设置为3.
因为在该函数里可以看到如下部分:

  1. if ~exist('lambda', 'var') || isempty(lambda)
  2. lambda = 0;
  3. end

可以看到不输入参数时,lambda被设置为0。
再次检验可以看出,结果依然正确。
image_1bu844857m82bnp18v8c8a1ur39.png-53.4kB
image_1bu844r5l173kr7j1cv3us35e7m.png-7.6kB
image_1bu84q1e91n2k1bq21nb6v3o1jn62t.png-6.7kB

2.6 Learning parameters using fmincg

计算完成后,将training example代入检验准确率。一般来说,准确率大概在95.3%左右。
ex4.m中这部分代码如下:

  1. %% =================== Part 8: Training NN ===================
  2. % You have now implemented all the code necessary to train a neural
  3. % network. To train your neural network, we will now use "fmincg", which
  4. % is a function which works similarly to "fminunc". Recall that these
  5. % advanced optimizers are able to train our cost functions efficiently as
  6. % long as we provide them with the gradient computations.
  7. %
  8. fprintf('\nTraining Neural Network... \n')
  9. % After you have completed the assignment, change the MaxIter to a larger
  10. % value to see how more training helps.
  11. options = optimset('MaxIter', 50);
  12. % You should also try different values of lambda
  13. lambda = 1;
  14. % Create "short hand" for the cost function to be minimized
  15. costFunction = @(p) nnCostFunction(p, ...
  16. input_layer_size, ...
  17. hidden_layer_size, ...
  18. num_labels, X, y, lambda);
  19. % Now, costFunction is a function that takes in only one argument (the
  20. % neural network parameters)
  21. [nn_params, cost] = fmincg(costFunction, initial_nn_params, options);
  22. % Obtain Theta1 and Theta2 back from nn_params
  23. Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
  24. hidden_layer_size, (input_layer_size + 1));
  25. Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
  26. num_labels, (hidden_layer_size + 1));
  27. fprintf('Program paused. Press enter to continue.\n');
  28. pause;

按照迭代次数50次,lambda设置为1来计算,得到如下结果:
image_1bu84mejgrunfqvksnhigsud2g.png-11.2kB
基本吻合。

3 Visualizing the hidden layer

输出隐藏层图形。

3.1 Optional exercise

如果未经正规化,可能会出现overfit的情况:对于training examples可能非常吻合,却不一定适用于新出现的情况。
我们把lambda设置得很小,迭代次数设置得很大,就容易出现这样的情况。
迭代次数:50, lambda=1,如下图:
iter:50 lambda:1
迭代次数:400, lambda=1, 如下图:
iter:400 lambda:1

迭代次数:700, lambda=0.1, 如下图:
iter:700 lambda:0.1

后两次的training accuracy都接近100%。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注