脾气暴躁的“:"运营商广播问题 [英] Numpy ":" operator broadcasting issues
问题描述
在下面的代码中,我编写了2种方法(在我看来)在理论上应该做同样的事情.不幸的是,他们没有这样做,我无法找出为什么他们在numpy文档中没有做同样的事情.
In the following code I have written 2 methods that theoretically(in my mind) should do the same thing. Unfortunately they don't, I am unable to find out why they don't do the same thing per the numpy documentation.
import numpy as np
dW = np.zeros((20, 10))
y = [1 for _ in range(100)]
X = np.ones((100, 20))
# ===================
# Method 1 (works!)
# ===================
for i in range(len(y)):
dW[:, y[i]] -= X[i]
# ===================
# Method 2 (does not work)
# ===================
dW[:, y] -= X.T
推荐答案
如前所述,由于NumPy中的缓冲工作原理,原则上您不能在同一操作中对同一元素进行多次操作.为此,有 at
函数,该函数可以在几乎所有标准NumPy函数上使用( add
, subtract
等).对于您的情况,您可以执行以下操作:
As indicated, in principle you cannot operate multiple times over the same element in a single operation, due to how buffering works in NumPy. For that purpose there is the at
function, which can be used on about any standard NumPy function (add
, subtract
, etc.). For your case, you can do:
import numpy as np
dW = np.zeros((20, 10))
y = [1 for _ in range(100)]
X = np.ones((100, 20))
# at modifies in place dW, does not return a new array
np.subtract.at(dW, (slice(None), y), X.T)
这篇关于脾气暴躁的“:"运营商广播问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!