MATLAB Answers

# To compute cost and gradient for a logistic regression problem:the function returns only zeroes even though the correct value is being computed(I know it because I executed the function body separately in command line and checked)

158 views (last 30 days)
Nesara S R on 3 Jul 2019
Commented: spurgin waters on 14 May 2021
function [J,grad]=costFunction(theta, X, y)
m = length(y);
z=X*theta;
h=sigmoid(z);
H=h.';
h1=log(H)*(-y);
h2=(log(1-H))*(1-y);
J=(h1-h2)/m;
s=h-y;
s=s.';
for i=1:3,
temp=(s)*X(:,i);
grad(i)=temp(1);
end
grad=grad./m;
% =============================================================
end
##### 2 CommentsShowHide 1 older comment
spurgin waters on 14 May 2021
How does the ex2.m dataset get called into the function?

Sign in to comment.

### Answers (1)

Antoine Jonathan on 26 Apr 2020
There is a problem somewhere in your data manipulation. the cost function is right.
I started from the beginning for the gradients, now it works:
Z2 = X * theta;
A2 = sigmoid(Z2);
D = (A2 - y);
grad(1) = D' * X(:,1);
grad(2) = D' * X(:,2);
grad(3) = D' * X(:,3);
grad = grad/m;
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!