根据类似db
的数组(近似为(1e6, 300)
)和mask = [1, 0, 1]
向量,我在第一列中将目标定义为1。
我想创建一个out
向量,它由1组成,其中db
中的相应行与mask
和target==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])