注:练习答案参考了下列两个博客,感谢分享。
https://blog.csdn.net/zongzongzong2015/article/details/50352818
https://blog.csdn.net/BRAVE_NO1/article/details/82731242
IrCostFunction.m
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = (1/m)*((-y'*log(sigmoid(X*theta)))-(1-y)'*log(1-sigmoid(X*theta)))+lambda/(2*m)*(theta(2:end)'*theta(2:end));
theta_temp=theta;
theta_temp(1)=0;
grad =(1/m)*(X')*(sigmoid(X*theta)-y)+lambda/m*theta_temp;
note:公式按文件中给出。其中求和用矩阵相乘来表示,求和的列向量也用矩阵相乘表示。
oneVsAll.m
% Some useful variables
m = size(X, 1);
n = size(X, 2);
all_theta=zeros(num_labels,n+1);
% Add o