Matlab 线性回归的向量化

环境: Ubuntu 12.04, Matlab 2013

数据如下:

jerry@hq:~/ml-class/mlclass-ex1$ more ex1data1.txt
6.1101,17.592
5.5277,9.1302
8.5186,13.662
7.0032,11.854
5.8598,6.8233
8.3829,11.886
7.4764,4.3483
8.5781,12
6.4862,6.5987
5.0546,3.8166
5.7107,3.2522
14.164,15.505
5.734,3.1551
8.4084,7.2258
……

 

做一个线性回归,用梯度下降方法,代码如下:

matlab -nodesktop

data = load(‘ex1data1.txt’);
X = data(:, 1), y = data(:, 2);
m = length(y);
X = [ones(m, 1), X];
theta = zeros(size(data, 2), 1);

for i = 1:1500
htheta = X * theta;
theta = theta – (0.01 / m * sum(repmat((htheta – y), 1, 2) .* X, 1))’;
end

 

另一种简洁的方法如下:

inv(X’ * X) * X’ * y

作者: hqiang1984

量化自我,极简主义