gradientDescent.m 956 B

1234567891011121314151617181920212223242526272829
  1. function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
  2. %GRADIENTDESCENT Performs gradient descent to learn theta
  3. % theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by
  4. % taking num_iters gradient steps with learning rate alpha
  5. % Initialize some useful values
  6. m = length(y); % number of training examples
  7. J_history = zeros(num_iters, 1);
  8. for iter = 1:num_iters
  9. J_history(iter) = computeCost(X, y, theta);
  10. theta = theta - alpha / m * (X' * (X * theta - y));
  11. end
  12. end
  13. % ====================== YOUR CODE HERE ======================
  14. % Instructions: Perform a single gradient step on the parameter vector
  15. % theta.
  16. %
  17. % Hint: While debugging, it can be useful to print out the values
  18. % of the cost function (computeCost) and gradient here.
  19. %
  20. % ============================================================
  21. % Save the cost J in every iteration