【题解】编程作业ex2: Logistic Regression (Machine Learning)

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

吐槽:没看完pdf的要求就去写plot的代码的后果就是写完发现后面有标答且比自己的简练= =然后也就不献丑了。。说一下predict和costFunctionReg吧,其他也不难。

题目:

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.

predict.m 我的解法:

其实写到这里只是希望注意下p是0或1,不是直接sigmoid的结果。。注释里面也有说,但是第一次写还是没注意。。以及,我没啥好的实现了就用了循环,感觉不是很美观。。不知道大家写的啥。。

function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic 
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a 
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters. 
%               You should set p to a vector of 0's and 1's
%
p = sigmoid(X * theta);
for i=1:m,
  if p(i)>=0.5,
    p(i)=1;
  else
    p(i)=0;
  endif
endfor
% =========================================================================
end

costFunctionReg.m 我的解法:

要注意的是theta的变化都是j从1到n的,没有0!!

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 = 1/m*(-y' * log(h) - (1-y)' * log(1-h)) + lambda/(2*m) * sum(theta(2:end,1).^2);
grad = 1/m * X' * (h - y) + lambda/m * theta; 
grad(1) = (1/m * X' * (h - y))(1);
% =============================================================

end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值