小批量梯度下降算法原理和python代码
时间: 2023-11-12 08:02:49 浏览: 51
小批量梯度下降(Mini-batch Gradient Descent)是梯度下降算法的一种变体,它将全部的训练数据分为若干个小批量,每次只用一个小批量数据来更新模型参数。相比于批量梯度下降,小批量梯度下降具有更快的收敛速度和更好的泛化能力。
其算法原理如下:
1. 随机选取一个小批量数据;
2. 计算该小批量数据的梯度;
3. 更新模型参数;
4. 重复1-3,直到达到最大迭代次数或者收敛。
下面是Python代码示例:
```
import numpy as np
def mini_batch_gradient_descent(X, y, learning_rate, batch_size, max_iterations):
m, n = X.shape
theta = np.random.randn(n, 1)
iterations = 0
while iterations < max_iterations:
batch_indices = np.random.randint(m, size=batch_size)
X_batch = X[batch_indices]
y_batch = y[batch_indices]
gradient = 2 * X_batch.T.dot(X_batch.dot(theta) - y_batch) / batch_size
theta = theta - learning_rate * gradient
iterations += 1
return theta
```
其中,X和y分别是训练数据和标签,learning_rate是学习率,batch_size是每个小批量数据的大小,max_iterations是最大迭代次数。函数返回最终的模型参数theta。