Path: blob/master/Week 9/Programming Assignment - 8/ex8/computeNumericalGradient.m
616 views
function numgrad = computeNumericalGradient(J, theta)1%COMPUTENUMERICALGRADIENT Computes the gradient using "finite differences"2%and gives us a numerical estimate of the gradient.3% numgrad = COMPUTENUMERICALGRADIENT(J, theta) computes the numerical4% gradient of the function J around theta. Calling y = J(theta) should5% return the function value at theta.67% Notes: The following code implements numerical gradient checking, and8% returns the numerical gradient.It sets numgrad(i) to (a numerical9% approximation of) the partial derivative of J with respect to the10% i-th input argument, evaluated at theta. (i.e., numgrad(i) should11% be the (approximately) the partial derivative of J with respect12% to theta(i).)13%1415numgrad = zeros(size(theta));16perturb = zeros(size(theta));17e = 1e-4;18for p = 1:numel(theta)19% Set perturbation vector20perturb(p) = e;21loss1 = J(theta - perturb);22loss2 = J(theta + perturb);23% Compute Numerical Gradient24numgrad(p) = (loss2 - loss1) / (2*e);25perturb(p) = 0;26end2728end293031