原理参考:
http://blog.csdn.net/abcjennifer/article/details/7691571
matlab实现参考:
http://www.cnblogs.com/denny402/p/4032381.html
使用梯度下降法迭代实现:
function theta=linearRegression()
% 梯度下降法寻找最合适的theta,使得J最小
options=optimset('GradObj','on','MaxIter',100);
inittheta=[1 1]';
theta=fminunc(@costFunc,inittheta,options);
end
%%
function [J,gradient]= costFunc(theta)
%J为代价函数。
%y=theta(0)*x0+theta(1)*x1; 找出最好的theta来拟合曲线。
%使得J最小的theta就是最好的theta
x=[1;2;3;4];
y=[1.1;2.2;2.7;3.8];
m=size(x,1);
hypothesis=theta(1)+theta(2)*x;
delta=hypothesis-y;
J=sum(delta.^2)/(2*m);
gradient(1)=sum(delta.*1)/m; %x0=1;
gradient(2)=sum(delta.*x)/m;
end