[英]numpy.vectorize function signature
I have 2 arrays:我有 2 个 arrays:
>>> a.shape
(9, 3, 11)
>>> b.shape
(9,)
I would like to compute the equivalent of c[i, j] = f(a[i, j, :], b[i])
where f(a0, b0)
is a function that takes 2 parameters, with len(a0) == 11
and len(b0) == 9
.我想计算
c[i, j] = f(a[i, j, :], b[i])
的等价物,其中f(a0, b0)
是一个 function ,它需要 2 个参数, len(a0) == 11
和len(b0) == 9
。 Here, i
is iterating on range(9)
and j
is iterating on range(3)
.这里,
i
在range(9)
上迭代, j
在range(3)
上迭代。
Is there a way to code this using numpy.vectorize
?有没有办法使用
numpy.vectorize
对此进行编码? Or is it simpler with some clever broadcasting?还是通过一些巧妙的广播更简单?
I have been trying for 2 hours and I just don't understand how to make it work... I tried to broadcast or to use signatures but to no avail.我已经尝试了 2 个小时,但我只是不明白如何使它工作......我尝试广播或使用签名但无济于事。
numpy.apply_along_axis
is what you need. numpy.apply_along_axis
是您所需要的。
import numpy as np
a = np.ones( (9,3,11) )
b = np.ones( 9 )
def f(a0, b0):
return a0[:9]+b0
c = np.apply_along_axis( f, 2, a, b )
print(c)
c
's shape is (9,3). c
的形状是 (9,3)。
In the end, I could make it work like this:最后,我可以让它像这样工作:
>>> f = np.vectorize(f, signature="(k),(1)->()")
>>> print(a.shape)
(9, 3, 11)
>>> print(b.shape)
(9,)
>>> print(f(a, b[:, None, None]).shape)
(9, 3)
This ensures that f
gets called with the correct shapes and iterates properly.这确保
f
以正确的形状被调用并正确迭代。 It is frankly not straightforward from the Numpy documentation to understand the trick to use a (1)
in the signature for this purpose.坦率地说,从 Numpy 文档中了解为此目的在签名中使用
(1)
的技巧并不简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.