Path: blob/master/Week 9/Programming Assignment - 8/ex8/checkCostFunction.m
616 views
function checkCostFunction(lambda)1%CHECKCOSTFUNCTION Creates a collaborative filering problem2%to check your cost function and gradients3% CHECKCOSTFUNCTION(lambda) Creates a collaborative filering problem4% to check your cost function and gradients, it will output the5% analytical gradients produced by your code and the numerical gradients6% (computed using computeNumericalGradient). These two gradient7% computations should result in very similar values.89% Set lambda10if ~exist('lambda', 'var') || isempty(lambda)11lambda = 0;12end1314%% Create small problem15X_t = rand(4, 3);16Theta_t = rand(5, 3);1718% Zap out most entries19Y = X_t * Theta_t';20Y(rand(size(Y)) > 0.5) = 0;21R = zeros(size(Y));22R(Y ~= 0) = 1;2324%% Run Gradient Checking25X = randn(size(X_t));26Theta = randn(size(Theta_t));27num_users = size(Y, 2);28num_movies = size(Y, 1);29num_features = size(Theta_t, 2);3031numgrad = computeNumericalGradient( ...32@(t) cofiCostFunc(t, Y, R, num_users, num_movies, ...33num_features, lambda), [X(:); Theta(:)]);3435[cost, grad] = cofiCostFunc([X(:); Theta(:)], Y, R, num_users, ...36num_movies, num_features, lambda);3738disp([numgrad grad]);39fprintf(['The above two columns you get should be very similar.\n' ...40'(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n']);4142diff = norm(numgrad-grad)/norm(numgrad+grad);43fprintf(['If your cost function implementation is correct, then \n' ...44'the relative difference will be small (less than 1e-9). \n' ...45'\nRelative Difference: %g\n'], diff);4647end4849