Dujana Abrar
Dujana Abrar

Reputation: 111

Why my cost function is giving wrong answer?

I have written a code for the cost function and it is giving incorrect answer.

I have read the code many times but I cannot find the mistake.

Here is my code:-

function J = computeCost(X, y, theta)

m = length(y); % number of training examples
s = 0;
h = 0;
sq = 0;

J = 0;

for i = 1:m
 h = theta' * X(i, :)';
 sq = (h - y(i))^2;
 s = s + sq;
end 

J = (1/2*m) * s;


end

Example:-

computeCost( [1 2; 1 3; 1 4; 1 5], [7;6;5;4], [0.1;0.2] )

ans = 11.9450

Here the answer should be 11.9450 but my code is giving me this:-

ans =  191.12

I have checked the the matrix multiplication and the code is calculating it right.

Upvotes: 2

Views: 94

Answers (1)

flawr
flawr

Reputation: 11628

It seems you misunderstood the operator evaluation order. In fact

1/2*m ~= 1/(2*m)

With this in mind it seems you're computing an average. Instead of reinventing the wheel it is usually a good idea to use the built in functions to do the job which results in a much clearer (and less error prone) implementation:

function J = computeCost(X, y, theta)
    h = X * theta;
    sq = (h - y).^2;
    J = 1/2 * mean(sq);
end
computeCost( [1,2;1,3;1,4;1,5], [7;6;5;4], [0.1;0.2] )
% ans = 11.9450

Try it online!

Upvotes: 2

Related Questions