python - 如何将简单的线性回归与梯度下降并行化 - 使用 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
解决方案
感谢所有看过我问题的人。我松散地使用术语并行化来指代我正在寻找的运行时优化,它消除了对 for 循环的需求。这个问题的答案是:
df_dm = (1/len(X)) * np.dot((-2*X).T, (y-(weight*X+bias)))
这里的问题是确保中间步骤产生的所有数组都具有正确的形状。而且 - 对于那些对这两个函数之间的运行时差异感兴趣的人:for 循环花费了 10 倍的时间。
推荐阅读
- r - R - 基于重复虚拟变量调整起始变量,带有 lag() - 每行多次测量
- python - Caml Query 在 sharepoint Online 上无法使用 Python
- android - Nativescript 6.5.2 Android apk“解析包时出现问题”
- javascript - *ngFor 带有多个图像标签 - 如何知道所有图像 src 何时加载
- php - 如何使用codeigniter中的会话ID从表中检索数据
- c++ - 如何在 gdb 中检查 C++ 向量中的元素?
- java - 守护进程的Android Studio问题
- python - 如何在具有多层的python(colab)中读取文件?
- c# - 如何在开发过程中在主体上下文上公开 EmailAddress 属性
- terraform - 如何在脚本中使用 terraform 输出