numpy 中的快速外张量积 [英] Fast outer tensor product in numpy
本文介绍了numpy 中的快速外张量积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 numpy 数组:
I have two numpy arrays:
x of shape ((d1,...,d_m))
y of shape ((e_1,...e_n))
我想形成外张量积,即numpy数组
I would like to form the outer tensor product, that is the numpy array
z of shape ((d1,...,d_m,e_1,...,e_n))
这样
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.
推荐答案
outer
的替代方法是显式扩展维度.对于一维数组,这将是
An alternative to outer
is to explicitly expand the dimensions. For 1d arrays this would be
x[:,None]*y # y[None,:] is automatic.
对于 10x10 数组,并概括维度扩展,我得到相同的次数
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
所以outer
确实节省了一些编码,但是基本的广播乘法是一样的.
So outer
does save some coding, but the basic broadcasted multiplication is the same.
这篇关于numpy 中的快速外张量积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文