File tree Expand file tree Collapse file tree 2 files changed +26
-12
lines changed Expand file tree Collapse file tree 2 files changed +26
-12
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments