a b/combinedDeepLearningActiveContour/functions/checkNumericalGradient.m
1
function [] = checkNumericalGradient()
2
% This code can be used to check your numerical gradient implementation 
3
% in computeNumericalGradient.m
4
% It analytically evaluates the gradient of a very simple function called
5
% simpleQuadraticFunction (see below) and compares the result with your numerical
6
% solution. Your numerical gradient implementation is incorrect if
7
% your numerical solution deviates too much from the analytical solution.
8
  
9
% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)
10
x = [4; 10];
11
[value, grad] = simpleQuadraticFunction(x);
12
13
% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.
14
% (The notation "@simpleQuadraticFunction" denotes a pointer to a function.)
15
numgrad = computeNumericalGradient(@simpleQuadraticFunction, x);
16
17
% Visually examine the two gradient computations.  The two columns
18
% you get should be very similar. 
19
disp([numgrad grad]);
20
fprintf('The above two columns you get should be very similar.\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n');
21
22
% Evaluate the norm of the difference between two solutions.  
23
% If you have a correct implementation, and assuming you used EPSILON = 0.0001 
24
% in computeNumericalGradient.m, then diff below should be 2.1452e-12 
25
diff = norm(numgrad-grad)/norm(numgrad+grad);
26
disp(diff); 
27
fprintf('Norm of the difference between numerical and analytical gradient (should be < 1e-9)\n\n');
28
end
29
30
31
  
32
function [value,grad] = simpleQuadraticFunction(x)
33
% this function accepts a 2D vector as input. 
34
% Its outputs are:
35
%   value: h(x1, x2) = x1^2 + 3*x1*x2
36
%   grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2 
37
% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we're assuming
38
% that computeNumericalGradients will use only the first returned value of this function.
39
40
value = x(1)^2 + 3*x(1)*x(2);
41
42
grad = zeros(2, 1);
43
grad(1)  = 2*x(1) + 3*x(2);
44
grad(2)  = 3*x(1);
45
46
end