用matlab编一段小批量梯度下降法程序绘制数据和拟合曲线(带图像,输入特征和输出目标任意)
时间: 2024-05-01 18:21:37 浏览: 15
好的,这是一个使用小批量梯度下降法的线性回归程序,并且绘制了数据和拟合曲线。以下是Matlab代码:
```matlab
% 生成数据
x = randn(100,1)*10;
y = 2*x + 5 + randn(100,1)*5;
% 绘制数据散点图
figure;
plot(x, y, 'rx', 'MarkerSize', 10);
xlabel('Input Feature');
ylabel('Output Target');
title('Data');
% 初始化参数
theta = randn(2,1);
alpha = 0.01;
batch_size = 10;
epochs = 100;
% 梯度下降
for epoch = 1:epochs
% 随机选择小批量数据
idx = randperm(length(x), batch_size);
x_batch = x(idx);
y_batch = y(idx);
% 计算梯度
grad = (1/batch_size) * [sum((theta(1)*x_batch + theta(2) - y_batch).*x_batch); sum(theta(1)*x_batch + theta(2) - y_batch)];
% 更新参数
theta = theta - alpha * grad;
end
% 绘制拟合曲线
x_fit = linspace(min(x), max(x), 100)';
y_fit = theta(1)*x_fit + theta(2);
hold on;
plot(x_fit, y_fit, 'b-', 'LineWidth', 2);
legend('Data', 'Fit');
hold off;
```
这个程序生成了一个随机的输入特征和输出目标,然后使用小批量梯度下降法来找到一条最合适的直线来拟合这些数据。程序还绘制了数据散点图和拟合曲线,以便更好地可视化拟合效果。