小批梯度下降的python代码实现
时间: 2024-03-29 20:33:39 浏览: 14
小批梯度下降是一种优化算法,它在每次迭代中使用一小批样本来计算梯度并更新模型参数。以下是一个简单的Python代码实现:
```python
import numpy as np
def mini_batch_gradient_descent(X, y, learning_rate=0.01, batch_size=32, num_iterations=100):
num_samples, num_features = X.shape
num_batches = num_samples // batch_size
# 初始化模型参数
theta = np.zeros(num_features)
for i in range(num_iterations):
# 随机打乱样本顺序
permutation = np.random.permutation(num_samples)
X_shuffled = X[permutation]
y_shuffled = y[permutation]
for j in range(num_batches):
# 获取当前批次的样本和标签
start = j * batch_size
end = start + batch_size
X_batch = X_shuffled[start:end]
y_batch = y_shuffled[start:end]
# 计算当前批次的梯度
gradient = np.dot(X_batch.T, np.dot(X_batch, theta) - y_batch) / batch_size
# 更新模型参数
theta -= learning_rate * gradient
return theta
```
这段代码实现了小批梯度下降算法,其中X是输入特征矩阵,y是对应的标签向量。learning_rate表示学习率,batch_size表示每个批次的样本数量,num_iterations表示迭代次数。函数返回训练得到的模型参数theta。