Fast outer tensor product in numpy

2019-01-09 17:31发布

问题:

I have two numpy arrays:

x of shape ((d1,...,d_m)) 
y of shape ((e_1,...e_n)) 

I would like to form the outer tensor product, that is the numpy array

z of shape ((d1,...,d_m,e_1,...,e_n))

such that

z[i_1,...,i_n,i_{n+1}...,i_{m+n}] == x[i_1,...i_m]*y[i_{m+1},...,i_{m+n}]

I have to perform the above outer multiplication several times so I would like to speed this up as much as possible.

回答1:

An alternative to outer is to explicitly expand the dimensions. For 1d arrays this would be

x[:,None]*y   # y[None,:] is automatic.

For 10x10 arrays, and generalizing the dimension expansion, I get the same times

In [74]: timeit x[[slice(None)]*x.ndim + [None]*y.ndim] * y
10000 loops, best of 3: 53.6 µs per loop

In [75]: timeit np.multiply.outer(x,y)
10000 loops, best of 3: 52.6 µs per loop

So outer does save some coding, but the basic broadcasted multiplication is the same.



回答2:

You want np.multiply.outer:

z = np.multiply.outer(x, y)