Skip to content

Instantly share code, notes, and snippets.

@AdroitAnandAI
Created February 11, 2021 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdroitAnandAI/c69f995b78c0d174bb66cc56eeb5535a to your computer and use it in GitHub Desktop.
Save AdroitAnandAI/c69f995b78c0d174bb66cc56eeb5535a to your computer and use it in GitHub Desktop.
collaborative filtering
function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...
num_features, lambda)
% Unfold the U and W matrices from params
X = reshape(params(1:num_movies*num_features), num_movies, num_features);
Theta = reshape(params(num_movies*num_features+1:end), ...
num_users, num_features);
% You need to return the following values correctly
J = 0;
X_grad = zeros(size(X));
Theta_grad = zeros(size(Theta));
% Compute the cost function and gradient for collaborative filtering.
% Implemented the cost function and gradient
J = sum(sum(R.*((X*Theta' - Y).^2)))/2 + ...
(sum(sum(Theta.^2)) + sum(sum(X.^2)))*lambda/2;
X_grad = (R.*(X*Theta' - Y))*Theta + lambda.*X;
Theta_grad = (R.*(X*Theta' - Y))'*X + lambda.*Theta;
grad = [X_grad(:); Theta_grad(:)];
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment