MATLAB二次函数拟合:使用梯度下降法拟合样本数据
% 生成样本数据 n = 4; % 样本数量 rs = -2:0; t = [0.33976 0.41737 0.49166 0.61688]; r = log(t); z = [25.5 42.249 55.35 73.2];
% 初始化模型参数 theta = [80; 110; 0]; % 参数向量,包括二次项系数、一次项系数和常数项 alpha = 0.01; % 学习率 iterations = 100000; % 迭代次数
% 使用梯度下降法进行二次函数拟合 for iter = 1:iterations % 计算预测值 z_pred = theta(1) * r.^2 + theta(2) * r + theta(3);
% 计算误差
error = z_pred - z;
% 更新参数
theta(1) = theta(1) - alpha * (1/n) * sum(error .* r.^2);
theta(2) = theta(2) - alpha * (1/n) * sum(error .* r);
theta(3) = theta(3) - alpha * (1/n) * sum(error);
% 计算损失函数(均方误差)
loss = (1/(2*n)) * sum(error.^2);
% 打印损失函数值
fprintf('Iteration %d, Loss = %f
', iter, loss); end
% 打印最终参数值 fprintf('Final parameters: theta0 = %f, theta1 = %f, theta2 = %f ', theta(3), theta(2), theta(1));
% 绘制拟合结果 plot(r, z, 'b.'); % 绘制样本数据点 hold on; plot(rs, theta(1) * rs.^2 + theta(2) * rs + theta(3), 'r-'); % 绘制拟合曲线 legend('样本数据', '拟合曲线'); set(gca,'YLim',[20,90]); set(gca,'XLim',[-1.1,-0.32]); xlabel('log(ratio)'); ylabel('浓度'); title('拟合曲线(二次函数)') set(gcf,'color','w') set(gcf,'Position',[70,70,1400,670]); box off grid on
原文地址: https://www.cveoy.top/t/topic/qnmH 著作权归作者所有。请勿转载和采集!