python实现随机梯度下降(SGD)算法

随机梯度下降算法(Stochastic Gradient Descent,SGD)是梯度下降算法的一种变体,其主要思想是在每次更新模型参数时,随机选择一个样本来计算梯度并进行参数更新,从而提高更新速度。相比于批量梯度下降算法(Batch Gradient Descent,BGD),SGD通常具有更快的收敛速度,在大规模数据集上尤为有效。

与批量梯度下降类似,SGD也需要指定学习率、迭代次数等超参数。SGD的每次迭代可分为两个步骤:首先,从训练集中随机选取一个样本;然后,根据选取的样本计算梯度并更新模型参数。这个过程重复执行直到达到指定的迭代次数或者收敛。

下面是一个使用Python实现SGD算法的示例代码:

import numpy as np

def stochastic_gradient_descent(X, y, theta, alpha, num_iters):
    """
    随机梯度下降算法
    :param X: 特征矩阵,包含m行n列,其中m为样本数,n为特征数
    :param y: 目标变量,包含m行1列
    :param theta: 参数向量,包含n行1列
    :param alpha: 学习率
    :param num_iters: 迭代次数
    :return: 最优参数向量
    """
    m = len(y)
    for i in range(num_iters):
        rand_idx = np.random.randint(m)
        h = np.dot(X[rand_idx], theta)
        delta = (h - y[rand_idx]) * X[rand_idx].reshape(-1, 1)
        theta -= alpha * delta
    return theta

与批量梯度下降算法相比,SGD的主要区别在于每次迭代中只使用一个样本进行计算和更新,因此对内存的消耗较小。

 
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定