Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 9/Programming Assignment - 8/ex8/cofiCostFunc.m
616 views
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
9
% Unfold the U and W matrices from params
10
X = reshape(params(1:num_movies*num_features), num_movies, num_features);
11
Theta = reshape(params(num_movies*num_features+1:end), ...
12
num_users, num_features);
13
14
15
% You need to return the following values correctly
16
J = 0;
17
X_grad = zeros(size(X));
18
Theta_grad = zeros(size(Theta));
19
20
% ====================== YOUR CODE HERE ======================
21
% Instructions: Compute the cost function and gradient for collaborative
22
% filtering. Concretely, you should first implement the cost
23
% function (without regularization) and make sure it is
24
% matches our costs. After that, you should implement the
25
% gradient and use the checkCostFunction routine to check
26
% that the gradient is correct. Finally, you should implement
27
% regularization.
28
%
29
% Notes: X - num_movies x num_features matrix of movie features
30
% Theta - num_users x num_features matrix of user features
31
% Y - num_movies x num_users matrix of user ratings of movies
32
% R - num_movies x num_users matrix, where R(i, j) = 1 if the
33
% i-th movie was rated by the j-th user
34
%
35
% You should set the following variables correctly:
36
%
37
% X_grad - num_movies x num_features matrix, containing the
38
% partial derivatives w.r.t. to each element of X
39
% Theta_grad - num_users x num_features matrix, containing the
40
% partial derivatives w.r.t. to each element of Theta
41
%
42
% sum(sum(R.*M)) corresponds to the sum of all elements where 'user-j' has rated 'movie-i'
43
J = 1/2 * sum(sum((R.* ((X * Theta') - Y)).^2));
44
45
X_grad = (R.*((X * Theta') - Y)) * Theta;
46
Theta_grad = (R.*((X * Theta') - Y))' * X;
47
48
% Regularization implementation
49
J = J + (lambda/2) * (sum(sum(Theta.^2)) + sum(sum(X.^2)));
50
X_grad = X_grad + (lambda * X);
51
Theta_grad = Theta_grad + (lambda * Theta);
52
% =============================================================
53
54
grad = [X_grad(:); Theta_grad(:)];
55
56
end
57
58