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;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));
%传入的参数y是一个列向量,每个元素就是每个样本对应的数字
%有两个求和,依然是向量化后进行矩阵运算,最后用两次sum即可
%在神经网络的CostFunction中要求y和h用0/1矩阵来表示,所以对于每个样本,其结果要从数字改成一个0/1向量
%最后的J应是一个数
X=[ones(m,1) X];
z2=X*Theta1';
a2=[ones(m,1) sigmoid(z2)];
z3=a2*Theta2';
h=sigmoid(z3);%h的元素并非都是0/1而是代表概率的数,不需要把他们改为0/1!!!但是CostFunction公式中的y一定要改成0/1矩阵!!!
%非常骚气的操作,for循环真正作用的地方:
yk=zeros(m,num_labels);
for i=1:m
yk(i,y(i))=1;%得到修改后用于公式中的0/1矩阵
end;
J=(1/m)*sum(sum(-1*yk.*log(h)-(1.-yk).*log(1.-h)));
%正则项,注意Theta1和Theta2里的第一列是怎么去除的
r=(lambda/(2*m))*(sum(sum(Theta1(:,2:end).^2))+sum(sum(Theta2(:,2:end).^2)));
J=J+r
%BackPropagation
for ex=1:m
a1=X(ex,:);
a1=a1';
z2=Theta1*a1;
a2=[1;sigmoid(z2)];
z3=Theta2*a2;
a3=sigmoid(z3);
y=yk(ex,:);
delta3=a3-y';
delta2=Theta2(:,2:end)'*delta3.*sigmoidGradient(z2);
Theta1_grad=Theta1_grad+delta2*a1';
Theta2_grad=Theta2_grad+delta3*a2';
end;
Theta1_grad=Theta1_grad./m;
Theta2_grad=Theta2_grad./m;
%正则化
Theta1(:,1)=0;
Theta2(:,1)=0;
Theta1_grad=Theta1_grad+lambda/m*Theta1;
Theta2_grad=Theta2_grad+lambda/m*Theta2;
% Unroll gradients
grad = [Theta1_grad(:) ; Theta2_grad(:)];
end
BP算法的流程,结合代码理解!