checkCostFunction.m 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. % Set lambda
  10. if ~exist('lambda', 'var') || isempty(lambda)
  11. lambda = 0;
  12. end
  13. %% Create small problem
  14. X_t = rand(4, 3);
  15. Theta_t = rand(5, 3);
  16. % Zap out most entries
  17. Y = X_t * Theta_t';
  18. Y(rand(size(Y)) > 0.5) = 0;
  19. R = zeros(size(Y));
  20. R(Y ~= 0) = 1;
  21. %% Run Gradient Checking
  22. X = randn(size(X_t));
  23. Theta = randn(size(Theta_t));
  24. num_users = size(Y, 2);
  25. num_movies = size(Y, 1);
  26. num_features = size(Theta_t, 2);
  27. numgrad = computeNumericalGradient( ...
  28. @(t) cofiCostFunc(t, Y, R, num_users, num_movies, ...
  29. num_features, lambda), [X(:); Theta(:)]);
  30. [cost, grad] = cofiCostFunc([X(:); Theta(:)], Y, R, num_users, ...
  31. num_movies, num_features, lambda);
  32. disp([numgrad grad]);
  33. fprintf(['The above two columns you get should be very similar.\n' ...
  34. '(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n']);
  35. diff = norm(numgrad-grad)/norm(numgrad+grad);
  36. fprintf(['If your cost function implementation is correct, then \n' ...
  37. 'the relative difference will be small (less than 1e-9). \n' ...
  38. '\nRelative Difference: %g\n'], diff);
  39. end