numpy vectorize a function to accepts vectors of d

2019-02-27 11:43发布

问题:

I want to vectorize a function f(a, b) so that, when I enter a and b as two vectors, the tensor of combinations is returned. Here is an illustrative example:

import numpy as np
def tester(a, b):
   mysumm = 0.
   for ii in range(a):
       for jj in range(b):
           mysumm += a * b
   return mysumm
tester = np.vectorize(tester)
x, y = [2, 4], [3, 5, 8] 
print(tester(x, 3)) # [ 36. 144.]
print(tester(x, 5)) # [100. 400.]
print(tester(x, 8)) # [ 256. 1024.]
print(tester(2, y)) # [ 36. 100. 256.]
print(tester(4, y)) # [ 144.  400. 1024.]
print(tester(x, y)) # ValueError: operands could not be broadcast together with shapes (2,) (3,) 

I expected the tester(x, y) call to return a 2x3 matrix, something like [[ 36. 100. 256.], [ 144. 400. 1024.]] and I was surprised that this isn't the default behavior.

How can I make the vecotirzed function return the tensor of possible combinations of the input vectors?

回答1:

You can chain with np.ix_:

>>> import functools
>>> 
>>> def tensorize(f):
...     fv = np.vectorize(f)
...     @functools.wraps(f)
...     def ft(*args):
...         return fv(*np.ix_(*map(np.ravel, args)))
...     return ft
... 
>>> tester = tensorize(tester)
>>> tester(np.arange(3), np.arange(2))
array([[0., 0.],
       [0., 1.],
       [0., 4.]])