目录
一、解释
线性回归:使用直线对数据拟合,达到预测效果
为了评价拟合的效果,需要一个评价函数 J(或称,损失函数),如下:
,其是参数 w 的函数
当评价函数达到最小(估计值与实际值差距最小),拟合效果最佳
梯度下降:一种寻优(eg:找到函数最值)手段
综上,目标转化为寻找最佳的w值使得评价函数最小
而,参数 w 更新(迭代)的公式如下:
二、matlab 代码
1.引入数据
代码如下(示例):
%数据
data=[
2.92887826637931
3.21836590215517
2.12771740086207
1.98811333310345
1.33286091547414
1.19538487534483
0.982254900646552
0.860660796896552
0.767939403965517
0.621031541293104
0.504935130301724
0.436285662931034
0.406308128189655
0.351795786767241
0.331874443017241
0.272457624956897
];
x(:,2)=1:length(data);
x(:,1)=ones(length(x(:,2)),1);
scatter(x(:,2),data,[],linspace(1,10, ...
length(data)));%绘制散点图
2.梯度下降优化参数
ite=1;%计数器
theta(:,1)=rand(2,1);%初始化参数
y_bar=x*theta(:,ite);%估计值
error=y_bar-data;%计算误差
MSE(ite,1)=sum(error.^2);%计算均方误差
while ite<100000 %设置退出条件
pian_theta=sum(error.*x)/length(data);
alpha=0.0002;%学习率
theta(:,ite+1)=theta(:,ite)-alpha*pian_theta';%更新并记录下参数的变化
ite=1+ite;
y_bar=x*theta(:,ite);
error=y_bar-data;
MSE(ite,1)=sum(error.^2);
end
3.绘图
%MSE迭代与参数变化情况
plot(MSE);
title('iteration of MSE','FontWeight','bold');plot(theta(1,:));
hold on
plot(theta(2,:));
hold off
title('iteration of theta 1&2','FontWeight','bold');
legend(["theta1","theta2"]);
ax = gca;
chart = ax.Children(2);
datatip(chart,5.181e+04,2.486,"Location","southwest");
chart = ax.Children(1);
datatip(chart,8.696e+04,-0.176)
4.结果
%画出拟合直线
scatter(x(:,2),data,[],linspace(1,10, ...
length(data)));
hold on
plot(x(:,2),y_bar,'LineWidth',2);
hold off
legend(["data","Fit"]);
title('Fit','FontWeight','bold');
三、附
在while 循环的退出方式上也值得优化,上述退出机制以循环次数为条件,可以使用“学习效率”作为退出机制
学习效率定义
本文介绍如何使用线性回归进行数据拟合,并通过梯度下降法优化参数以达到最佳预测效果。文中详细展示了MATLAB实现过程,包括数据导入、参数优化、绘图展示及结果分析。

1万+

被折叠的 条评论
为什么被折叠?



