ex4 MACHINE LEARNING COURSERA手写体数字识别

1.灵活应用矩阵运算代替for循环的冗余

2.当使用后向传播时 每次运算一个样本 先计算其feedforward 求出J 再求出最后一层的delta差 以此进行后向传播以得到代价函数J关于每一个权重theta的导数

3.计算正则化后的代价函数,注意不要加上theta0的平方项

4. 利用δ 反求 △时,△(l)=△(l)+δ(l+1)*a(l)

注意skep or remove θ0  (可以先求 后skip 也可以如本文一样 先不求)

==========================================================================

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);% number of samples
         
% 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.
%




% my_code===========part 1 feedforward=====================

a1 = [ones(m, 1) X];  
z2 = a1 * Theta1';  
a2 = sigmoid(z2);  
a2 = [ones(m, 1) a2];  
z3 = a2 * Theta2';  
h = sigmoid(z3);  
%calculate yk  
yk = zeros(m, num_labels);  
for i = 1:m      
    yk(i, y(i)) = 1; %y is class vector  
end  
%costFunction  
J = (1/m)* sum(sum(((-yk) .* log(h) - (1 - yk) .* log(1 - h)))); 


%=========================part 2 regularization============
Theta1_new=Theta1(:,2:size(Theta1,2));  
Theta2_new=Theta2(:,2:size(Theta2,2)); 
J=J+lambda/2/m*( sum(sum(Theta1_new.*Theta1_new))+sum(sum(Theta2_new.*Theta2_new)));


%=========================part 3 backpropagation=======================
Delta_1=zeros(hidden_layer_size,input_layer_size+1);
Delta_2=zeros(num_labels,hidden_layer_size+1);
for t=1:m
  a1=[1 X(t,:)];   %1*401
  z2=a1*Theta1';   %1*25
  a2=sigmoid(z2);  %1*25
  a2_plus=[1 a2];  %1*26
  z3=a2_plus*Theta2';  %1*10
  a3=sigmoid(z3);
  
  delta_3=a3-yk(t,:);  %1*10
  delta_2=Theta2(:,2:end)'*delta_3'.*sigmoidGradient(z2');  %25*1
  
  Delta_1=Delta_1+delta_2*a1; %25*401
  Delta_2=Delta_2+delta_3'*a2_plus; %10*26 


  
end


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




Theta1_grad(:,2:end)=Theta1_grad(:,2:end)+lambda/m*Theta1(:,2:end);
Theta2_grad(:,2:end)=Theta2_grad(:,2:end)+lambda/m*Theta2(:,2:end);








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


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


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




end

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值