牛客题解 | 实现梯度下降

题目

题目链接

梯度下降是一种在机器学习中常用的优化算法,其计算步骤如下:

  1. 初始化参数
    w 0 = 0 w_0 = 0 w0=0
  2. 计算梯度
    g t = ∇ f ( w t ) g_t = \nabla f(w_t) gt=f(wt)
    本题采用MSE作为损失函数,其梯度为:
    g t = 2 n ∑ i = 1 n ( y i − w t T x i ) x i g_t = \frac{2}{n} \sum_{i=1}^{n} (y_i - w_t^T x_i)x_i gt=n2i=1n(yiwtTxi)xi
  3. 更新参数
    w t + 1 = w t − η ⋅ g t w_{t+1} = w_t - \eta \cdot g_t wt+1=wtηgt
  4. 重复上述步骤,直到收敛。
本题中采用了三种梯度下降方法,分别是批量梯度下降(batch)、随机梯度下降(stochastic)和mini-batch梯度下降(mini_batch)。区别如下:
  1. 批量梯度下降:每次迭代使用所有数据点来计算梯度,更新参数。
  2. 随机梯度下降:每次迭代使用一个数据点来计算梯度,更新参数。
  3. mini-batch梯度下降:每次迭代使用一部分数据点来计算梯度,更新参数。
需要注意的是,本题中随机梯度下降与mini-batch梯度下降都需要对数据集整体进行遍历更新,并不是定义上对单个数据点/小批量数据点进行更新。

标准代码如下

def gradient_descent(X, y, weights, learning_rate, n_iterations, batch_size=1, method='batch'):
    m = len(y)
    
    for _ in range(n_iterations):
        if method == 'batch':
            # Calculate the gradient using all data points
            predictions = X.dot(weights)
            errors = predictions - y
            gradient = 2 * X.T.dot(errors) / m
            weights = weights - learning_rate * gradient
        
        elif method == 'stochastic':
            # Update weights for each data point individually
            for i in range(m):
                prediction = X[i].dot(weights)
                error = prediction - y[i]
                gradient = 2 * X[i].T.dot(error)
                weights = weights - learning_rate * gradient
        
        elif method == 'mini_batch':
            # Update weights using sequential batches of data points without shuffling
            for i in range(0, m, batch_size):
                X_batch = X[i:i+batch_size]
                y_batch = y[i:i+batch_size]
                predictions = X_batch.dot(weights)
                errors = predictions - y_batch
                gradient = 2 * X_batch.T.dot(errors) / batch_size
                weights = weights - learning_rate * gradient
                
    return weights
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值