用matlab编一段小批量梯度下降法程序绘制数据和拟合曲线(带图像,输入特征和输出目标任意)
时间: 2024-05-04 21:17:27 浏览: 9
好的,以下是一个用 Matlab 编写的小批量梯度下降法程序,可用于绘制数据和拟合曲线:
```matlab
% 定义数据
X = [1, 1; 1, 2; 1, 3; 1, 4; 1, 5];
y = [2; 3; 4; 5; 6];
% 初始化参数
theta = [0; 0];
alpha = 0.01;
iterations = 1000;
batch_size = 2;
% 迭代更新参数
for i = 1:iterations
% 随机抽取一部分数据
batch_indices = randsample(size(X, 1), batch_size);
X_batch = X(batch_indices, :);
y_batch = y(batch_indices);
% 计算梯度
grad = (1 / batch_size) * X_batch' * (X_batch * theta - y_batch);
% 更新参数
theta = theta - alpha * grad;
end
% 绘制数据和拟合曲线
plot(X(:, 2), y, 'rx', 'MarkerSize', 10);
hold on;
plot(X(:, 2), X * theta, 'b-', 'LineWidth', 2);
legend('Training data', 'Linear regression');
xlabel('Feature');
ylabel('Output target');
```
这个程序使用了一个简单的数据集,其中 `X` 是输入特征矩阵,`y` 是对应的输出目标向量。程序首先初始化了参数,包括初始权重 `theta`,学习率 `alpha`,迭代次数 `iterations` 和小批量大小 `batch_size`。然后,程序使用随机梯度下降法来更新权重,每次随机抽取一部分数据进行计算。最后,程序将数据和拟合曲线绘制出来。
运行程序后,你应该可以看到一个包含数据点和拟合曲线的图像,这个图像是根据输入特征和输出目标绘制的。请注意,由于随机梯度下降法的随机性,每次运行程序得到的结果可能会略有不同。