1. 使用自己生成数据(代码实现)
function GenerRand_Linear( a,num ) %y=ax,生成num个随机数
Xbuf=zeros(num,1);
Ybuf=zeros(num,1);
for i=1:num
Xbuf(i,1)=10*rand(); %随机生成0-10之间的数字
Ybuf(i,1)=a*Xbuf(i,1)+rand()*2; %Ybuf中加入随机扰动:0-2
end
plot(Xbuf,Ybuf,'.r');
end
调用函数生成数据集:
GenerRand_Linear(3,100);
执行结果:
2. 算术法求解(代码实现)
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=zeros(num,1);
y=zeros(num,1);
for i=1:num
x(i,1)=10*rand(); %随机生成0-10之间的数字
y(i,1)=a*x(i,1)+rand()*2; %Ybuf中加入随机扰动:0-2
end
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
3. 向量法求解(代码实现)
function [ theta ] = linearReg(Xbuf,Ybuf,num)
%线性回归
X=ones(num,2);
Y=ones(num,1);
for i=1:num
X(i,2)= Xbuf(i,1); %注意第一列全为1,即x0=1,第二列才为x1
Y(i,1)=Ybuf(i,1);
end
A=inv(X'*X);
theta=A*X'*Y; %根据公式theta=(X'*X)^(-1)*X'*Y;
end
通过矩阵运算,直接算出系数a
4. 算术法、 向量法性能比较
向量法实现更直观,计算速度快。