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)
12 views (last 30 days)
Show older comments
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 Comments
Sahithi Kanumarlapudi
on 17 Jul 2019
The way the function is implemented looks correct. There might be something wrong where this function is being called.
Could you provide me the dataset with which you are trying to call this function so that I can verify.
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 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!