You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cofiCostFunc.m 2.4 kB

8 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...
  2. num_features, lambda)
  3. %COFICOSTFUNC Collaborative filtering cost function
  4. % [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...
  5. % num_features, lambda) returns the cost and gradient for the
  6. % collaborative filtering problem.
  7. %
  8. % Unfold the U and W matrices from params
  9. X = reshape(params(1:num_movies*num_features), num_movies, num_features);
  10. Theta = reshape(params(num_movies*num_features+1:end), ...
  11. num_users, num_features);
  12. % You need to return the following values correctly
  13. J = 0;
  14. X_grad = zeros(size(X));
  15. Theta_grad = zeros(size(Theta));
  16. % ====================== YOUR CODE HERE ======================
  17. % Instructions: Compute the cost function and gradient for collaborative
  18. % filtering. Concretely, you should first implement the cost
  19. % function (without regularization) and make sure it is
  20. % matches our costs. After that, you should implement the
  21. % gradient and use the checkCostFunction routine to check
  22. % that the gradient is correct. Finally, you should implement
  23. % regularization.
  24. %
  25. % Notes: X - num_movies x num_features matrix of movie features
  26. % Theta - num_users x num_features matrix of user features
  27. % Y - num_movies x num_users matrix of user ratings of movies
  28. % R - num_movies x num_users matrix, where R(i, j) = 1 if the
  29. % i-th movie was rated by the j-th user
  30. %
  31. % You should set the following variables correctly:
  32. %
  33. % X_grad - num_movies x num_features matrix, containing the
  34. % partial derivatives w.r.t. to each element of X
  35. % Theta_grad - num_users x num_features matrix, containing the
  36. % partial derivatives w.r.t. to each element of Theta
  37. %
  38. %sum(R .* (((X * Theta') .- Y) .^ 2)) 1*4 matrix
  39. J = 1 / 2 * sum(sum(R .* (((X * Theta') .- Y) .^ 2)));
  40. J = J + lambda / 2 * sum(sum(X .^ 2)) + lambda / 2 * sum(sum(Theta .^ 2));
  41. % (((X * Theta') .- Y) * Theta)
  42. X_grad = (R .* ((X * Theta') .- Y)) * Theta;
  43. X_grad = X_grad + lambda .* X;
  44. Theta_grad = (R .* ((X * Theta') .- Y))' * X;
  45. Theta_grad = Theta_grad + lambda .* Theta;
  46. % =============================================================
  47. grad = [X_grad(:); Theta_grad(:)];
  48. end

机器学习

Contributors (1)