Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 9/Programming Assignment - 8/ex8/checkCostFunction.m
616 views
1
function checkCostFunction(lambda)
2
%CHECKCOSTFUNCTION Creates a collaborative filering problem
3
%to check your cost function and gradients
4
% CHECKCOSTFUNCTION(lambda) Creates a collaborative filering problem
5
% to check your cost function and gradients, it will output the
6
% analytical gradients produced by your code and the numerical gradients
7
% (computed using computeNumericalGradient). These two gradient
8
% computations should result in very similar values.
9
10
% Set lambda
11
if ~exist('lambda', 'var') || isempty(lambda)
12
lambda = 0;
13
end
14
15
%% Create small problem
16
X_t = rand(4, 3);
17
Theta_t = rand(5, 3);
18
19
% Zap out most entries
20
Y = X_t * Theta_t';
21
Y(rand(size(Y)) > 0.5) = 0;
22
R = zeros(size(Y));
23
R(Y ~= 0) = 1;
24
25
%% Run Gradient Checking
26
X = randn(size(X_t));
27
Theta = randn(size(Theta_t));
28
num_users = size(Y, 2);
29
num_movies = size(Y, 1);
30
num_features = size(Theta_t, 2);
31
32
numgrad = computeNumericalGradient( ...
33
@(t) cofiCostFunc(t, Y, R, num_users, num_movies, ...
34
num_features, lambda), [X(:); Theta(:)]);
35
36
[cost, grad] = cofiCostFunc([X(:); Theta(:)], Y, R, num_users, ...
37
num_movies, num_features, lambda);
38
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
diff = norm(numgrad-grad)/norm(numgrad+grad);
44
fprintf(['If your cost function implementation is correct, then \n' ...
45
'the relative difference will be small (less than 1e-9). \n' ...
46
'\nRelative Difference: %g\n'], diff);
47
48
end
49