Machine Learning Week3

week3的主要内容并不算很多,其实相对于week2,主要是修改了h函数,变成了sigmoid,而不是原来的向量乘法。

不过我觉得有两点需要注意,第一点就是fminunc函数,这个函数接受options作为设置,然后结构initial_theta作为优化的theta参数,之后是一个句柄(不知道是不是这么叫),会通过这个函数计算loss和梯度grad。返回值的loss,grad,我想grad用来更新了,loss用来判断了。

第二点就是在正则化的时候,bias不去平方,也不去正则化的更新。

function [J, grad] = costFunctionReg(theta, X, y, lambda)
%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization
%   J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized logistic regression and the
%   gradient of the cost w.r.t. to the parameters. 

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta

h = sigmoid(X * theta);
J =  sum(-y .* log(h) - (1-y).*log(1-h))/(m) + sum(theta(2:end).^2)*lambda/(2*m);

deltaGrad = zeros(size(theta));
deltaGrad = X' * (h-y) /m;
deltaGrad(2:end) = deltaGrad(2:end) + lambda*theta(2:end)/m;

grad = deltaGrad;

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值