请用numpy实现小批量随机梯度下降算法
时间: 2023-10-22 09:03:33 浏览: 44
好的,下面是使用numpy实现小批量随机梯度下降算法的示例代码:
```python
import numpy as np
def mini_batch_sgd(X, y, alpha, epochs, batch_size):
"""
X: 训练数据特征,shape为 (m, n),其中 m 为样本数,n 为特征数
y: 训练数据标签,shape为 (m, 1)
alpha: 学习率
epochs: 迭代次数
batch_size: 每次迭代的小批量样本数量
"""
m, n = X.shape
theta = np.zeros((n, 1)) # 初始化模型参数
for epoch in range(epochs):
# 打乱样本顺序
permutation = np.random.permutation(m)
X_shuffle = X[permutation]
y_shuffle = y[permutation]
for i in range(0, m, batch_size):
# 取出一批样本
X_batch = X_shuffle[i:i+batch_size]
y_batch = y_shuffle[i:i+batch_size]
# 计算梯度
gradient = np.dot(X_batch.T, np.dot(X_batch, theta) - y_batch) / batch_size
# 更新模型参数
theta -= alpha * gradient
return theta
```
其中,X 和 y 分别表示训练数据的特征和标签,alpha 表示学习率,epochs 表示迭代次数,batch_size 表示每次迭代的小批量样本数量。函数返回训练得到的模型参数 theta。