Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 5/Programming Assignment - 4/machine-learning-ex4/ex4/checkNNGradients.m
864 views
1
function checkNNGradients(lambda)
2
%CHECKNNGRADIENTS Creates a small neural network to check the
3
%backpropagation gradients
4
% CHECKNNGRADIENTS(lambda) Creates a small neural network to check the
5
% backpropagation gradients, it will output the analytical gradients
6
% produced by your backprop code and the numerical gradients (computed
7
% using computeNumericalGradient). These two gradient computations should
8
% result in very similar values.
9
%
10
11
if ~exist('lambda', 'var') || isempty(lambda)
12
lambda = 0;
13
end
14
15
input_layer_size = 3;
16
hidden_layer_size = 5;
17
num_labels = 3;
18
m = 5;
19
20
% We generate some 'random' test data
21
Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size);
22
Theta2 = debugInitializeWeights(num_labels, hidden_layer_size);
23
% Reusing debugInitializeWeights to generate X
24
X = debugInitializeWeights(m, input_layer_size - 1);
25
y = 1 + mod(1:m, num_labels)';
26
27
% Unroll parameters
28
nn_params = [Theta1(:) ; Theta2(:)];
29
30
% Short hand for cost function
31
costFunc = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size, ...
32
num_labels, X, y, lambda);
33
34
[cost, grad] = costFunc(nn_params);
35
numgrad = computeNumericalGradient(costFunc, nn_params);
36
37
% Visually examine the two gradient computations. The two columns
38
% you get should be very similar.
39
disp([numgrad grad]);
40
fprintf(['The above two columns you get should be very similar.\n' ...
41
'(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n']);
42
43
% Evaluate the norm of the difference between two solutions.
44
% If you have a correct implementation, and assuming you used EPSILON = 0.0001
45
% in computeNumericalGradient.m, then diff below should be less than 1e-9
46
diff = norm(numgrad-grad)/norm(numgrad+grad);
47
48
fprintf(['If your backpropagation implementation is correct, then \n' ...
49
'the relative difference will be small (less than 1e-9). \n' ...
50
'\nRelative Difference: %g\n'], diff);
51
52
end
53
54