机器学习入门第七篇——Octave/Matlab Tutorial(7)
- Vectorization(向量化)
%unvectorized implementation
%函数体
function J = costFunctionJ(X,y,theta)
m = size(X,1);
predictions = X * theta;
sqrErrors = (predictions-y).^2;
J = 1/(2*m) * sum(sqrErrors);
X=[1 1; 1 2; 1 3]
y=[1; 2; 3]
theta=[0;1]
%调用函数
j=costFunctionJ(X,y,theta) % theta=[0;1]
theta=[0;0]
为什么j=2.3333(theta=[0;0])
j=(1^2+2^2+3^2)/(2*3)
为什么j=0(theta=[0;1])
j=(0^2+0^2+0^2)/(2*3)
%vectorized implementation
prediction = theta'*X;
% it will use OCtaves highly optimized numerical linear algerbra routines to
%compute this inner product between the two vectors theta and X.
%Not only the vectorized implementation simpler, it will also run much more efficiently.
J=1/(2*m)*sum(sqrErrors);
%vectorized example
%unvectorized implementation
%C++
%函数体
double prediction =0.0;
for(int j=0 ; j<=n ; j++)
prediction+=theta[j]*x[j];
%vectorized implementation
%C++
%函数体
double prediction
=theta.transpose()*x;
%Gradient descent
%vectorized implementation
OVER