梯度下降法matlab
时间: 2023-06-30 20:26:26 浏览: 77
梯度下降法是一种常见的优化算法,被广泛应用于机器学习和深度学习中。在MATLAB中,可以使用以下代码实现梯度下降法:
1. 定义损失函数:
```matlab
function J = computeCost(X, y, theta)
m = length(y);
J = 1/(2*m) * sum((X*theta - y).^2);
end
```
2. 定义梯度下降函数:
```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
theta = theta - alpha/m * X' * (X*theta - y);
J_history(iter) = computeCost(X, y, theta);
end
end
```
3. 调用梯度下降函数:
```matlab
X = [ones(m,1), data(:,1)]; % data是数据集
y = data(:,2);
theta = zeros(2,1);
alpha = 0.01;
num_iters = 1500;
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters);
```
其中,X是特征矩阵,y是目标变量,theta是模型参数,alpha是学习率,num_iters是迭代次数。函数中的J_history是用来保存每次迭代的损失函数值的。
阅读全文
相关推荐











