介绍
梯度下降是一种常见的优化算法,通常用于训练机器学习模型。该算法通过反复迭代来逐步调整模型参数,从而最小化损失函数。
原理
梯度
在梯度下降算法中,我们需要计算损失函数的梯度。梯度是一个向量,其方向指向使损失函数增加最快的方向,大小表示该方向上的变化率。对于多元函数 f ( x 1 , x 2 , . . . , x n ) f(x_1, x_2, ..., x_n) f(x1,x2,...,xn),其梯度可表示为:
∇ f = ( ∂ f ∂ x 1 , ∂ f ∂ x 2 , . . . , ∂ f ∂ x n ) \nabla f = (\frac{\partial f}{\partial x_1}, \frac{\partial f}{\partial x_2}, ..., \frac{\partial f}{\partial x_n}) ∇f=(∂x1∂f,∂x2∂f,...,∂xn∂f)
其中, ∂ f ∂ x i \frac{\partial f}{\partial x_i} ∂xi∂f表示函数 f f f对第 i i i个自变量 x i x_i xi的偏导数。
梯度下降算法
梯度下降算法的目标是找到一个使得损失函数最小化的参数值。算法的核心思想是不断地沿着梯度的反方向进行迭代更新,直到达到损失函数的局部最小值或全局最小值。
具体来说,我们可以按照如下方式更新参数:
θ j = θ j − α ∂ ∂ θ j J ( θ 0 , θ 1 , ⋯ , θ n − 1 ; X , y ) \theta_{j}=\theta_{j}-\alpha \frac{\partial}{\partial \theta_{j}} J(\theta_0, \theta_1, \cdots, \theta_{n-1};X,y) θj=θj−α∂θj∂J(θ0,θ1,⋯,θn−1;X,y)
其中, α \alpha α是学习率(learning rate), J ( θ 0 , θ 1 , ⋯ , θ n − 1 ; X , y ) J(\theta_0, \theta_1, \cdots, \theta_{n-1};X,y) J(θ0,θ1,⋯,θn−1;X,y)是损失函数, ∂ ∂ θ j J ( θ 0 , θ 1 , ⋯ , θ n − 1 ; X , y ) \frac{\partial}{\partial \theta_{j}} J(\theta_0, \theta_1, \cdots, \theta_{n-1};X,y) ∂θj∂J(θ0,θ1,⋯,θn−1;X,y)是损失函数对参数 θ j \theta_j θj的偏导数。
通过不断迭代更新参数,我们可以逐步优化模型并提高其预测性能。
批量梯度下降
批量梯度下降(Batch Gradient Descent)是梯度下降算法的一种形式。在批量梯度下降中,我们需要计算所有样本的梯度,然后再根据该梯度来更新模型参数。具体来说,批量梯度下降的更新公式如下:
θ j = θ j − α 1 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) x j ( i ) \theta_{j}=\theta_{j}-\alpha \frac{1}{m} \sum_{i=1}^{m} \left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right) x_{j}^{(i)} θj=θj−αm1i=1∑m(hθ(x(i))−y(i))xj(i)
其中, m m m是样本数量, h θ ( x ) h_\theta(x) hθ(x)是模型对输入 x x x的预测值。
随机梯度下降
随机梯度下降(Stochastic Gradient Descent)是梯度下降算法的另一种形式,与批量梯度下降相比,随机梯度下降每次仅使用一个样本来计算梯度,并更新模型参数。具体来说,随机梯度下降的更新公式如下:
θ j = θ j − α ( h θ ( x ( i ) ) − y ( i ) ) x j ( i ) \theta_{j}=\theta_{j}-\alpha \left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right) x_{j}^{(i)} θj=θj−α(hθ(x(i))−y(i))xj(i)
其中, i i i是一个随机索引,表示当前所选中的样本。
小批量梯度下降
小批量梯度下降(Mini-batch Gradient Descent)是批量梯度下降和随机梯度下降的折中方案。
在小批量梯度下降中,我们每次从训练集中随机选择一小批样本,计算这些样本的梯度,然后更新模型参数。与批量梯度下降相比,小批量梯度下降可以加速收敛,同时避免了随机梯度下降的不稳定性。
具体来说,小批量梯度下降的更新公式如下:
θ j = θ j − α 1 ∣ B ∣ ∑ i ∈ B ( h θ ( x ( i ) ) − y ( i ) ) x j ( i ) \theta_{j}=\theta_{j}-\alpha \frac{1}{|B|} \sum_{i \in B}\left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right) x_{j}^{(i)} θj=θj−α∣B∣1i∈B∑(hθ(x(i))−y(i))xj(i)
其中, B B B表示当前所选中的小批量样本的索引集合, ∣ B ∣ |B| ∣B∣是其大小。
代码演示
下面是一个使用Python实现梯度下降算法的例子。我们将使用Numpy库生成一个样本数据,然后使用批量梯度下降和小批量梯度下降来训练一个简单的线性回归模型。
首先,我们需要导入所需的库和生成样本数据:
import numpy as np
import matplotlib.pyplot as plt
# 生成样本数据
np.random.seed(0)
m = 100
X = np.linspace(0, 10, m).reshape(m, 1)
y = X + np.random.randn(m, 1)
plt.scatter(X, y)
plt.xlabel('X')
plt.ylabel('y')
plt.show()
接下来,我们可以使用批量梯度下降算法来训练一个线性回归模型:
# 批量梯度下降算法
def batch_gradient_descent(X, y, alpha=0.01, num_iters=1000):
m, n = X.shape
theta = np.zeros((n, 1))
J_history = []
for i in range(num_iters):
h = X.dot(theta)
delta = (1/m) * X.T.dot(h-y)
theta -= alpha * delta
J_history.append(compute_cost(X, y, theta))
return theta, J_history
# 计算代价函数
def compute_cost(X, y, theta):
m = len(y)
h = X.dot(theta)
J = (1/(2*m)) * np.sum(np.square(h-y))
return J
# 添加偏置项并进行特征缩放
X_b = np.c_[np.ones((m, 1)), X]
X_norm = (X_b - np.mean(X_b, axis=0)) / np.std(X_b, axis=0)
# 使用批量梯度下降求解模型参数
theta, J_history = batch_gradient_descent(X_norm, y)
print('Theta:', theta)
然后,我们可以使用小批量梯度下降算法来训练同样的线性回归模型:
# 小批量梯度下降算法
def mini_batch_gradient_descent(X, y, alpha=0.01, num_iters=1000, batch_size=10):
m, n = X.shape
theta = np.zeros((n, 1))
J_history = []
for i in range(num_iters):
batch_indices = np.random.randint(0, m, size=batch_size)
X_batch = X[batch_indices]
y_batch = y[batch_indices]
h = X_batch.dot(theta)
delta = (1/batch_size) * X_batch.T.dot(h-y_batch)
theta -= alpha * delta
J_history.append(compute_cost(X, y, theta))
return theta, J_history
# 使用小批量梯度下降求解模型参数
theta, J_history = mini_batch_gradient_descent(X_norm, y)
print('Theta:', theta)
最后,我们可以绘制损失函数随迭代次数变化的曲线来观察优化过程:
plt.plot(J_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.title('Mini-batch Gradient Descent')
plt.show()
以上两张图分别展示了批量梯度下降和小批量梯度下降的优化过程,可以看出随着迭代次数的增加,损失函数逐渐减小并趋于稳定。
总结
梯度下降是一种常见的优化算法,用于训练机器学习模型。在实践中,我们可以根据数据集的大小和计算资源的限制,选择合适的梯度下降算法来优化模型。同时,我们也需要注意调整学习率等超参数以确保算法的稳定性和收敛速度。