神经网络基础-神经网络补充概念-44-minibatch梯度下降法

本文介绍了小批量梯度下降法的概念,展示了如何在Python中使用这种方法对线性回归模型进行训练,通过随机选择小批量数据更新模型参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念

小批量梯度下降法(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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丰。。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值