【题解】编程作业ex4: Neural Network Learning (Machine Learning)

9 篇文章 0 订阅
8 篇文章 0 订阅

吐槽:最近事情有点多,居然鸽到了下一周orz。。咳咳终于写完了= =顺便反向传播原理目前还不是非常理解,所以笔记也要鸽一阵orz。。。

题目:

Download the programming assignment here. This ZIP file contains the instructions in a PDF and the starter code. You may use either MATLAB or Octave (>= 3.8.0).

To submit this assignment, call the included submit function from MATLAB / Octave. You will need to enter the token provided on the right-hand side of this page.

nnCostFunction我的解法:

感觉其实从头到尾都在编写这个函数,所以我就只放了个这。。编写过程中需要验证输出size的我都注释了。。郁闷的地方在于求J的时候A都是可以用矩阵解决的,但是在求Y的时候用了1到m的循环,实在没想到什么不用循环的方法QAQ。。然后求grad的部分也不够简洁,算法都是直接按照pdf上面的步骤实现的。。

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
%
% 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.
%
% 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.
%

% Add ones to the X data matrix
X = [ones(m, 1) X];
A1 = X;
Z2 = A1 * Theta1';
A2 = [ones(m, 1) sigmoid(Z2)];
Z3 = A2 * Theta2';
A3 = sigmoid(Z3);
H = A3;
all_y = [1: num_labels];
Y = zeros(m, num_labels);
for i = 1:m,
  Y(i, :) = (all_y == y(i));
endfor
J = 1/m * sum(sum(-Y.*log(H)-(ones(size(Y))-Y).*log(1-H))) + lambda/(2*m)*(sum(sum(Theta1(:, 2:end).^2))+sum(sum(Theta2(:, 2:end).^2)))
%fprintf('A1 = %d*%d, A2 = %d*%d, A3 = %d*%d, Y = %d*%d\n', ...
%    size(A1)(1),size(A1)(2),size(A2)(1),size(A2)(2),size(A3)(1),size(A3)(2),size(Y)(1),size(Y)(2));
% -------------------------------------------------------------

Delta_1 = zeros(size(Theta1));
Delta_2 = zeros(size(Theta2));
for t = 1:m,
  % Step1
  a_1 = A1(t, :)';
  z_2 = Z2(t, :)';
  a_2 = A2(t, :)';
  z_3 = Z3(t, :)';
  a_3 = A3(t, :)';
  y_temp = Y(t, :)';
  %fprintf('a_1 = %d*%d, a_2 = %d*%d, a_3 = %d*%d, y_temp = %d*%d\n', ...
  %  size(a_1)(1),size(a_1)(2),size(a_2)(1),size(a_2)(2),size(a_3)(1),size(a_3)(2),size(y_temp)(1),size(y_temp)(2));
  % Step2
  delta_3 = a_3 - y_temp;
  % Step3
  delta_2 = Theta2' * delta_3 .* sigmoidGradient([1;z_2]);
  % Step4
  delta_2 = delta_2(2:end);
  %fprintf('delta_2 = %d*%d, a_1 = %d*%d\n',size(delta_2)(1),size(delta_2)(2),size(a_1)(1),size(a_1)(2));
  Delta_1 = Delta_1 + delta_2 * a_1';
  Delta_2 = Delta_2 + delta_3 * a_2';
  
endfor

% Step5
Theta1_grad = 1/m*Delta_1;
Theta2_grad = 1/m*Delta_2;

% regularization
Delta_para1 = lambda/m*ones(size(Theta1));
Delta_para1(:, 1) = 0;
Delta_para2 = lambda/m*ones(size(Theta2));
Delta_para2(:, 1) = 0;
Theta1_grad = Theta1_grad + Delta_para1 .* Theta1;
Theta2_grad = Theta2_grad + Delta_para2 .* Theta2;

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

% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)];


end

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值