Skip to content

Commit 39bc127

Browse files
committed
refactor univariate gradient descent. confirming univariate version is simply a special case of multivariate version.
1 parent 2c3d729 commit 39bc127

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed

ex1/mlclass-ex1/computeCost.m

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,18 @@
1212
% ====================== YOUR CODE HERE ======================
1313
% Instructions: Compute the cost of a particular choice of theta
1414
% You should set J to the cost.
15-
for i=1:m
16-
dif = (theta'*X(i, :)'-y(i));
17-
J = J + dif*dif;
18-
endfor
19-
%
20-
J = J / (2*m);
15+
16+
% initial version.
17+
% for i=1:m
18+
% dif = (theta'*X(i, :)'-y(i));
19+
% J = J + dif*dif;
20+
% endfor
21+
% J = J / (2*m);
22+
23+
% vectorized version.
24+
% (exactly the same with multivariate version. )
25+
dif = X*theta -y;
26+
J = (dif'*dif)/(2*m);
2127
%
2228
% =========================================================================
2329

ex1/mlclass-ex1/gradientDescent.m

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,24 @@
2121
theta_prev = theta;
2222

2323
% number of features.
24-
p = length(X(1, :));
24+
p = size(X, 2);
2525

2626
% simultaneous update theta using theta_prev.
2727
for j = 1:p
28+
29+
% % calculate dJ/d(theta_j)
30+
% % initial version
31+
% deriv = 0;
32+
% for i = 1:m
33+
% deriv = deriv + (theta_prev'*X(i, :)'-y(i))*X(i, j);
34+
% end
35+
% deriv = deriv/m;
36+
2837
% calculate dJ/d(theta_j)
29-
deriv = 0;
30-
for i = 1:m
31-
deriv = deriv + (theta_prev'*X(i, :)'-y(i))*X(i, j);
32-
end
33-
deriv = deriv/m;
38+
% vectorized version
39+
% (exactly the same with multivariate version)
40+
deriv = ((X*theta_prev - y)'*X(:, j))/m;
41+
3442
% update theta_j
3543
theta(j) = theta_prev(j)-(alpha*deriv);
3644
end

0 commit comments

Comments
 (0)