概念
小批量梯度下降法(Mini-Batch Gradient Descent)是梯度下降法的一种变体,它结合了批量梯度下降(Batch Gradient Descent)和随机梯度下降(Stochastic Gradient Descent)的优点。在小批量梯度下降中,每次更新模型参数时,不是使用全部训练数据(批量梯度下降)或仅使用一个样本(随机梯度下降),而是使用一小部分(小批量)样本。
代码实现
import numpy as np
import matplotlib.pyplot as plt# 生成随机数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)# 添加偏置项
X_b = np.c_[np.ones((100, 1)), X]# 初始化参数
theta = np.random.randn(2, 1)# 学习率
learning_rate = 0.01# 迭代次数
n_iterations = 1000# 小批量大小
batch_size = 10# 小批量梯度下降
for iteration in range(n_iterations):shuffled_indices = np.random.permutation(100)X_b_shuffled = X_b[shuffled_indices]y_shuffled = y[shuffled_indices]for i in range(0, 100, batch_size):xi = X_b_shuffled[i:i+batch_size]yi = y_shuffled[i:i+batch_size]gradients = 2 / batch_size * xi.T.dot(xi.dot(theta) - yi)theta = theta - learning_rate * gradients# 绘制数据和拟合直线
plt.scatter(X, y)
plt.plot(X, X_b.dot(theta), color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression with Mini-Batch Gradient Descent')
plt.show()print("Intercept (theta0):", theta[0][0])
print("Slope (theta1):", theta[1][0])