用matlab写了线性回归小程序,主程序如下:后面调用了函数,名字function1
通过一些坐标点,来线性回归拟合一条直线y=ax+b,学习步长theta可以设置,一般0.01,0.001。。。。
function1里用的梯度下降法,
a=a-theta*a的偏导数
b=b-theta*b的偏导数
返回m、n是新的a和b,tt是最小二乘法的方差结果,可以设定小于一定的值就停止
coex=[1 2 3 4 5 6 7 8 9 10];
coey=[2 4 5 7 9 11 13.5 16.2 18.2 20.2];
a=2;
b=2;
theta=0.01;
for idx=1:100000
[m,n,tt] = function1(coex,coey,a,b,theta);
a=m;
b=n;
fprintf('%d: a:%f, b:%f, tt:%f\n',idx,a,b,tt);
if tt<0.2
break
end
end
plot(coex,coey,'*r');
hold on;
yy=a*coex+b;
plot(coex,yy,'-b');
reta=0;
retb=0;
size1=size(x,2);
sum1=0;
sum2=0;
sum3=0;
for i=1:size1
sum1 = sum1+ (a*x(i)+b-y(i))*x(i);
sum2 = sum2 + (a*x(i)+b-y(i));
sum3 = sum3 + (a*x(i)+b-y(i)).^2;
end
ja=sum1/size1;
jb=sum2/size1;
retc=sum3/2/size1;
reta=a-theta*ja;
![]()
通过一些坐标点,来线性回归拟合一条直线y=ax+b,学习步长theta可以设置,一般0.01,0.001。。。。
function1里用的梯度下降法,
a=a-theta*a的偏导数
b=b-theta*b的偏导数
返回m、n是新的a和b,tt是最小二乘法的方差结果,可以设定小于一定的值就停止
test.m如下
coex=[1 2 3 4 5 6 7 8 9 10];
coey=[2 4 5 7 9 11 13.5 16.2 18.2 20.2];
a=2;
b=2;
theta=0.01;
for idx=1:100000
[m,n,tt] = function1(coex,coey,a,b,theta);
a=m;
b=n;
fprintf('%d: a:%f, b:%f, tt:%f\n',idx,a,b,tt);
if tt<0.2
break
end
end
plot(coex,coey,'*r');
hold on;
yy=a*coex+b;
plot(coex,yy,'-b');
下面是函数细节,function1.m如下:
reta=0;
retb=0;
size1=size(x,2);
sum1=0;
sum2=0;
sum3=0;
for i=1:size1
sum1 = sum1+ (a*x(i)+b-y(i))*x(i);
sum2 = sum2 + (a*x(i)+b-y(i));
sum3 = sum3 + (a*x(i)+b-y(i)).^2;
end
ja=sum1/size1;
jb=sum2/size1;
retc=sum3/2/size1;
reta=a-theta*ja;
retb=b-theta*jb;