由随机梯度上升算法,实现小批量梯度上升算法,python
时间: 2023-09-24 14:06:21 浏览: 47
小批量梯度上升算法是梯度上升算法的一种变形,它每次使用一小部分样本来计算梯度,从而减少了计算量,同时还能够降低模型的方差。下面是用 Python 实现小批量梯度上升算法的代码:
```python
import numpy as np
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
def gradient_ascent(X, y, alpha=0.001, max_iter=5000, batch_size=32):
n_samples, n_features = np.shape(X)
weights = np.random.rand(n_features)
for i in range(max_iter):
# 随机抽取一小部分样本
batch_index = np.random.choice(n_samples, batch_size)
X_batch = X[batch_index]
y_batch = y[batch_index]
# 计算梯度
error = y_batch - sigmoid(np.dot(X_batch, weights))
gradient = np.dot(X_batch.T, error) / batch_size
# 更新权重
weights += alpha * gradient
return weights
```
其中,`X` 是输入数据矩阵,`y` 是对应的标签向量,`alpha` 是学习率,`max_iter` 是最大迭代次数,`batch_size` 是每次随机抽取的样本数。函数返回训练好的权重向量。