0

I have written gradient descent algorithm in Octave but it is not giving me the exact answer. The answer differs from one to two digits.

Here is my code:

function theta = gradientDescent(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
s = 0;
temp = theta;
for iter = 1:num_iters
  for j = 1:size(theta, 1)
    for i = 1:m
      h = theta' * X(i, :)';
      s = s + (h - y(i))*X(i, j);
    end
    s = s/m;
    temp(j) = temp(j) - alpha * s;
  end 
  theta = temp; 
end

end

For:

theta = gradientDescent([1 5; 1 2; 1 4; 1 5],[1 6 4 2]',[0 0]',0.01,1000);

My gradient descent gives this:

 4.93708
-0.50549

But it is expected to give this:

 5.2148
-0.5733
5
  • Why are the results wrong? As in: how did you determine the "expected" output, and why are you convinced those are right?
    – Adriaan
    Sep 12, 2019 at 13:00
  • As those results are given by the machine learning course provider.
    – D buiss
    Sep 12, 2019 at 13:02
  • So what do you want from us? What you implemented is a gradient descent (supposedly). We're not going to fiddle parameters or change algorithms for you until we get the exact values. You'll have to find out exactly where the two algorithms start to diverge and investigate from there what is wrong. If you can, get the code as provided by the teacher and compare those for differences
    – Adriaan
    Sep 12, 2019 at 13:08
  • I just wanted to know whether my algorithm is correct, Sorry for any unintentional inconvenience.
    – D buiss
    Sep 12, 2019 at 13:11
  • You already determined that it is incorrect, given the fact that your results differ from that of the teacher. The problem is that we cannot say why they differ, or help you get the same results, because we do not know how the teacher got those. We'd need the full book/course/webinar/wherever you learn to see what the teacher did. Hence, we simply cannot help you. Sorry.
    – Adriaan
    Sep 12, 2019 at 13:15

1 Answer 1

1

Minor fixes :

  1. Your variable s probably the delta is initialised incorrectly.
  2. So it the temp variable probably the new theta
  3. Incorrectly calculating the delta

Try with below changes.

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
temp = theta;
for iter = 1:num_iters
    temp = zeros(length(theta), 1);
    for j = 1:size(theta)
        s = 0
        for i = 1:m
            s = s + (X(i, :)*theta - y(i)) * X(i, j);
        end
    end
    s = s/m;
    temp(j) = temp(j) - alpha * s;
end 
    theta = temp; 
    J_history(iter) = computeCost(X, y, theta);
end
end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.