Skip to content

Commit f7b3283

Browse files
Vectorized implementation of X and Theta gradients
1 parent 21cfdac commit f7b3283

File tree

1 file changed

+5
-16
lines changed
  • ex8.Anomaly_Detection_and_Recommender_Systems/mlclass-ex8

1 file changed

+5
-16
lines changed

ex8.Anomaly_Detection_and_Recommender_Systems/mlclass-ex8/cofiCostFunc.m

+5-16
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,12 @@
4646
J = J + lambda*sum(sum(Theta.^2))/2; % regularized term of theta.
4747
J = J + lambda*sum(sum(X.^2))/2; % regularized term of x.
4848

49-
% calculating gradient of x.
50-
for i=1:num_movies
51-
idx = find(R(i, :)==1); % users that have rated movie i.
52-
Theta_tmp = Theta(idx, :); % user features of movie i.
53-
Y_tmp = Y(i, idx); % user's ratings of movie i.
54-
X_grad(i, :) = (X(i, :)*Theta_tmp' - Y_tmp)*Theta_tmp;
55-
X_grad(i, :) = X_grad(i, :)+lambda*X(i, :); % regularized term of x.
56-
end
49+
X_grad = (diff.*R)*Theta; %unregularized vectorized implementation
50+
Theta_grad = ((diff.*R)'*X); %unregularized vectorized implementation
5751

58-
% calculating gradient of theta.
59-
for j=1:num_users
60-
idx = find(R(:, j)==1)'; % movies that have rated by user j.
61-
X_tmp = X(idx, :); % features of movies rated by user j.
62-
Y_tmp = Y(idx, j); % user ratings by user j.
63-
Theta_grad(j, :) = (X_tmp*Theta(j, :)'-Y_tmp)'*X_tmp;
64-
Theta_grad(j, :) = Theta_grad(j, :)+lambda*Theta(j, :); % regularized term of theta.
65-
end
52+
53+
X_grad = X_grad + (lambda * X); % regularized
54+
Theta_grad = Theta_grad + (lambda * Theta); % regularized
6655

6756
% =============================================================
6857

0 commit comments

Comments
 (0)