Path: blob/master/Week 9/Programming Assignment - 8/ex8/cofiCostFunc.m
616 views
function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...1num_features, lambda)2%COFICOSTFUNC Collaborative filtering cost function3% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...4% num_features, lambda) returns the cost and gradient for the5% collaborative filtering problem.6%78% Unfold the U and W matrices from params9X = reshape(params(1:num_movies*num_features), num_movies, num_features);10Theta = reshape(params(num_movies*num_features+1:end), ...11num_users, num_features);121314% You need to return the following values correctly15J = 0;16X_grad = zeros(size(X));17Theta_grad = zeros(size(Theta));1819% ====================== YOUR CODE HERE ======================20% Instructions: Compute the cost function and gradient for collaborative21% filtering. Concretely, you should first implement the cost22% function (without regularization) and make sure it is23% matches our costs. After that, you should implement the24% gradient and use the checkCostFunction routine to check25% that the gradient is correct. Finally, you should implement26% regularization.27%28% Notes: X - num_movies x num_features matrix of movie features29% Theta - num_users x num_features matrix of user features30% Y - num_movies x num_users matrix of user ratings of movies31% R - num_movies x num_users matrix, where R(i, j) = 1 if the32% i-th movie was rated by the j-th user33%34% You should set the following variables correctly:35%36% X_grad - num_movies x num_features matrix, containing the37% partial derivatives w.r.t. to each element of X38% Theta_grad - num_users x num_features matrix, containing the39% partial derivatives w.r.t. to each element of Theta40%41% sum(sum(R.*M)) corresponds to the sum of all elements where 'user-j' has rated 'movie-i'42J = 1/2 * sum(sum((R.* ((X * Theta') - Y)).^2));4344X_grad = (R.*((X * Theta') - Y)) * Theta;45Theta_grad = (R.*((X * Theta') - Y))' * X;4647% Regularization implementation48J = J + (lambda/2) * (sum(sum(Theta.^2)) + sum(sum(X.^2)));49X_grad = X_grad + (lambda * X);50Theta_grad = Theta_grad + (lambda * Theta);51% =============================================================5253grad = [X_grad(:); Theta_grad(:)];5455end565758