梯度下降法matlab代码
时间: 2023-06-30 18:09:06 浏览: 44
以下是一个简单的梯度下降法的 Matlab 代码示例:
```matlab
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % 训练样本数
J_history = zeros(num_iters, 1); % 记录每次迭代的代价函数值
for iter = 1:num_iters
% 计算假设函数
h = X * theta;
% 计算误差
error = h - y;
% 计算梯度
gradient = (1 / m) * X' * error;
% 更新参数
theta = theta - alpha * gradient;
% 记录代价函数值
J_history(iter) = computeCost(X, y, theta);
end
end
function J = computeCost(X, y, theta)
m = length(y);
J = 1/(2*m) * sum((X * theta - y).^2);
end
```
其中,X 是一个 m×n 的矩阵,表示 m 个样本的特征,n 个特征值;y 是一个 m×1 的向量,表示每个样本的真实输出;theta 是一个 n×1 的向量,表示模型参数;alpha 是学习率,num_iters 是迭代次数。在函数中,我们使用了 computeCost 函数来计算代价函数值。每次迭代后,我们更新 theta 并记录对应的代价函数值。最终返回的 theta 是经过训练得到的最优参数,J_history 是每次迭代的代价函数值。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)