首页 > 解决方案 > 如何将简单的线性回归与梯度下降并行化 - 使用 numpy?

问题描述

我无法使用 numpy 并行化下面的 for 循环(get_new_weights)。在我第一次尝试更新权重中的 df_dm 时,权重是完全错误的。在我第二次尝试 df_dm 时,我的体重超过了最佳体重。

注意 - 偏差是单个数字,权重是单个数字(一个变量线性回归),X 是形状 (442,1),y 是形状 (442,1)。另请注意,更新我的偏差项在 update_weights 中非常有效 - 它只是更新我遇到问题的权重。

# This is the for loop that I am trying to parallelize with numpy:
def get_new_weights(X, y, weight, bias, learning_rate=0.01):
    weight_deriv = 0
    bias_deriv = 0
    total = len(X)
    for i in range(total):
        # -2x(y - (mx + b))
        weight_deriv += -2*X[i] * (y[i] - (weight*X[i] + bias))
        # -2(y - (mx + b))
        bias_deriv += -2*(y[i] - (weight*X[i] + bias))

    weight -= (weight_deriv / total) * learning_rate
    bias -= (bias_deriv / total) * learning_rate
    return weight, bias

# This is my attempt at parallelization
def update_weights(X, y, weight, bias, lr=0.01):
    df_dm = np.average(-2*X * (y-(weight*X+bias))) # this was my first guess
    # df_dm = np.average(np.dot((-X).T, ((weight*X+bias)-y))) # this was my second guess
    df_db = np.average(-2*(y-(weight*X+bias)))
    weight = weight - (lr*df_dm)
    bias = bias - (lr*df_db)
    return weight,bias

这是我用来更新体重和偏差的方程式: 这是更新我的体重和偏差的方程式

标签: pythonnumpymachine-learninglinear-regressiongradient-descent

解决方案


感谢所有看过我问题的人。我松散地使用术语并行化来指代我正在寻找的运行时优化,它消除了对 for 循环的需求。这个问题的答案是:

df_dm = (1/len(X)) * np.dot((-2*X).T, (y-(weight*X+bias)))

这里的问题是确保中间步骤产生的所有数组都具有正确的形状。而且 - 对于那些对这两个函数之间的运行时差异感兴趣的人:for 循环花费了 10 倍的时间。


推荐阅读