使用numpy.frompyfunc向带有参数的python函数添加广播



根据类似db的数组(近似为(1e6, 300))和mask = [1, 0, 1]向量,我在第一列中将目标定义为1。

我想创建一个out向量,它由1组成,其中db中的相应行与masktarget==1匹配,其他地方为零。

db = np.array([       # out for mask = [1, 0, 1]
# target,  vector     #
  [1,      1, 0, 1],  # 1
  [0,      1, 1, 1],  # 0 (fit to mask but target == 0)
  [0,      0, 1, 0],  # 0
  [1,      1, 0, 1],  # 1
  [0,      1, 1, 0],  # 0
  [1,      0, 0, 0],  # 0
  ])

我定义了一个vline函数,该函数使用np.array_equal(mask, mask & vector)mask应用于每个阵列行,以检查向量101和111是否适合掩码,然后仅保留target == 1处的索引。

out初始化为array([0, 0, 0, 0, 0, 0])

out = [0, 0, 0, 0, 0, 0]

vline函数定义为:

def vline(idx, mask):
    line = db[idx]
    target, vector = line[0], line[1:]
    if np.array_equal(mask, mask & vector):
        if target == 1:
            out[idx] = 1

我通过在for循环中逐行应用这个函数得到了正确的结果:

def check_mask(db, out, mask=[1, 0, 1]):
    # idx_db to iterate over db lines without enumerate
    for idx in np.arange(db.shape[0]):
        vline(idx, mask=mask)
    return out
assert check_mask(db, out, [1, 0, 1]) == [1, 0, 0, 1, 0, 0] # it works !

现在我想通过创建ufunc:来矢量化vline

ufunc_vline = np.frompyfunc(vline, 2, 1)
out = [0, 0, 0, 0, 0, 0]
ufunc_vline(db, [1, 0, 1])
print out

但是ufunc抱怨用这些形状广播输入:

In [217]:     ufunc_vline(db, [1, 0, 1])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-217-9008ebeb6aa1> in <module>()
----> 1 ufunc_vline(db, [1, 0, 1])
ValueError: operands could not be broadcast together with shapes (6,4) (3,)
In [218]:

vline转换为numpy ufunc根本没有意义,因为ufunc总是以元素方式应用于numpy数组。因此,输入参数必须具有相同的形状,或者必须可广播为相同的形状。您正在将两个形状不兼容的数组传递给ufunc_vline函数(db.shape == (6, 4)mask.shape == (3,)),因此您看到的是ValueError

ufunc_vline还有几个其他问题:

  • np.frompyfunc(vline, 2, 1)指定vline应该返回一个输出参数,而vline实际上不返回任何内容(但在适当的位置修改out)。

  • 您将db作为第一个参数传递给ufunc_vline,而vline期望第一个参数是idx,它用作db行的索引。

此外,请记住,与标准Python for循环相比,使用np.frompyfunc从Python函数创建ufunc不会带来任何显著的性能优势。要想看到任何重大改进,您可能需要用C等低级语言对ufunc进行编码(请参阅文档中的此示例)。


话虽如此,您的vline函数可以使用标准布尔数组操作轻松地向量化:

def vline_vectorized(db, mask): 
    return db[:, 0] & np.all((mask & db[:, 1:]) == mask, axis=1)

例如:

db = np.array([       # out for mask = [1, 0, 1]
# target,  vector     #
  [1,      1, 0, 1],  # 1
  [0,      1, 1, 1],  # 0 (fit to mask but target == 0)
  [0,      0, 1, 0],  # 0
  [1,      1, 0, 1],  # 1
  [0,      1, 1, 0],  # 0
  [1,      0, 0, 0],  # 0
  ])
mask = np.array([1, 0, 1])
print(repr(vline_vectorized(db, mask)))
# array([1, 0, 0, 1, 0, 0])

最新更新