computeNumericalGradient.m 1.1 KB

1234567891011121314151617181920212223242526272829
  1. function numgrad = computeNumericalGradient(J, theta)
  2. %COMPUTENUMERICALGRADIENT Computes the gradient using "finite differences"
  3. %and gives us a numerical estimate of the gradient.
  4. % numgrad = COMPUTENUMERICALGRADIENT(J, theta) computes the numerical
  5. % gradient of the function J around theta. Calling y = J(theta) should
  6. % return the function value at theta.
  7. % Notes: The following code implements numerical gradient checking, and
  8. % returns the numerical gradient.It sets numgrad(i) to (a numerical
  9. % approximation of) the partial derivative of J with respect to the
  10. % i-th input argument, evaluated at theta. (i.e., numgrad(i) should
  11. % be the (approximately) the partial derivative of J with respect
  12. % to theta(i).)
  13. %
  14. numgrad = zeros(size(theta));
  15. perturb = zeros(size(theta));
  16. e = 1e-4;
  17. for p = 1:numel(theta)
  18. % Set perturbation vector
  19. perturb(p) = e;
  20. loss1 = J(theta - perturb);
  21. loss2 = J(theta + perturb);
  22. % Compute Numerical Gradient
  23. numgrad(p) = (loss2 - loss1) / (2*e);
  24. perturb(p) = 0;
  25. end
  26. end