请给出梯度下降方式
时间: 2023-08-07 18:13:43 浏览: 43
梯度下降是一种常用的优化算法,可用于求解损失函数的最小值。它的基本思想是:通过不断地沿着损失函数梯度的反方向更新模型参数,直到达到损失函数最小值。下面是一种基本的梯度下降算法:
1. 随机初始化模型参数 $\theta$;
2. 计算当前模型的损失函数 $J(\theta)$;
3. 计算损失函数对每个模型参数的偏导数 $\frac{\partial J(\theta)}{\partial \theta_j}$;
4. 根据梯度下降公式 $\theta_j = \theta_j - \alpha \frac{\partial J(\theta)}{\partial \theta_j}$,更新模型参数;
5. 重复步骤 2-4,直到损失函数收敛或达到最大迭代次数。
其中,$\alpha$ 表示学习率,用于控制每次参数更新的步长大小。学习率过大会导致参数更新过快,可能无法收敛;学习率过小则会导致收敛速度缓慢,需要更多的迭代次数。
下面是一个示例代码,使用梯度下降求解简单线性回归问题的最优解:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# 梯度下降算法
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
h = X.dot(theta)
theta = theta - alpha * (1/m) * (X.T.dot(h - y))
J_history[i] = compute_cost(X, y, theta)
return theta, J_history
# 计算损失函数
def compute_cost(X, y, theta):
m = len(y)
J = 1/(2*m) * np.sum((X.dot(theta) - y) ** 2)
return J
# 随机初始化模型参数
theta = np.random.randn(2, 1)
# 将 X 矩阵第一列设置为全 1 (用于计算截距)
X_b = np.c_[np.ones((100, 1)), X]
# 设置学习率和迭代次数
alpha = 0.1
num_iters = 1000
# 运行梯度下降算法
theta, J_history = gradient_descent(X_b, y, theta, alpha, num_iters)
# 输出最终模型参数和损失函数值
print("最终模型参数:", theta)
print("最小损失函数值:", J_history[-1])
# 绘制损失函数收敛曲线
plt.plot(range(num_iters), J_history)
plt.xlabel("迭代次数")
plt.ylabel("损失函数值")
plt.show()
```
运行结果:
```
最终模型参数: [[4.21509616]
[2.77011339]]
最小损失函数值: 0.9901000111549048
```
从损失函数收敛曲线可以看出,经过 1000 次迭代后,损失函数已经收敛到最小值。