1
0
Fork 0
This repository has been archived on 2019-12-21. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
coursera-ml-007-exercises/ex8/cofiCostFunc.m

60 lines
2.3 KiB
Mathematica
Raw Permalink Normal View History

2014-11-26 00:20:22 +01:00
function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...
num_features, lambda)
%COFICOSTFUNC Collaborative filtering cost function
% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...
% num_features, lambda) returns the cost and gradient for the
% collaborative filtering problem.
%
% 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);
2014-11-27 23:31:49 +01:00
2014-11-26 00:20:22 +01:00
% You need to return the following values correctly
J = 0;
X_grad = zeros(size(X));
Theta_grad = zeros(size(Theta));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost function and gradient for collaborative
% filtering. Concretely, you should first implement the cost
% function (without regularization) and make sure it is
2014-11-27 23:31:49 +01:00
% matches our costs. After that, you should implement the
2014-11-26 00:20:22 +01:00
% gradient and use the checkCostFunction routine to check
% that the gradient is correct. Finally, you should implement
% regularization.
%
% Notes: X - num_movies x num_features matrix of movie features
% Theta - num_users x num_features matrix of user features
% Y - num_movies x num_users matrix of user ratings of movies
2014-11-27 23:31:49 +01:00
% R - num_movies x num_users matrix, where R(i, j) = 1 if the
2014-11-26 00:20:22 +01:00
% i-th movie was rated by the j-th user
%
% You should set the following variables correctly:
%
2014-11-27 23:31:49 +01:00
% X_grad - num_movies x num_features matrix, containing the
2014-11-26 00:20:22 +01:00
% partial derivatives w.r.t. to each element of X
2014-11-27 23:31:49 +01:00
% Theta_grad - num_users x num_features matrix, containing the
2014-11-26 00:20:22 +01:00
% partial derivatives w.r.t. to each element of Theta
%
2014-11-27 23:47:18 +01:00
J = 0.5 * sum(sum(R.*(X*Theta'-Y).^2)) ...
+ 0.5 * lambda * sum(sum(Theta.^2)) ...
+ 0.5 * lambda * sum(sum(X.^2));
2014-11-26 00:20:22 +01:00
2014-11-27 23:50:42 +01:00
% mov X user * uxer X feat = mov X feat
X_grad = (R.*(X*Theta'-Y))*Theta ...
+ lambda*X;
% user X mov * mov X feat = user X feat
Theta_grad = (R.*(X*Theta'-Y))'*X ...
+ lambda*Theta;
2014-11-26 00:20:22 +01:00
% =============================================================
grad = [X_grad(:); Theta_grad(:)];
end