潍坊seo建站,谷歌优化技术,简单百度网址大全,广州网站设计与制作公司概念
小批量梯度下降法#xff08;Mini-Batch Gradient Descent#xff09;是梯度下降法的一种变体#xff0c;它结合了批量梯度下降#xff08;Batch Gradient Descent#xff09;和随机梯度下降#xff08;Stochastic Gradient Descent#xff09;的优点。在小批量梯…概念
小批量梯度下降法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:ibatch_size]yi y_shuffled[i:ibatch_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), colorred)
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])