快速外部张量乘积 [英] Fast outer tensor product in numpy

查看:182
本文介绍了快速外部张量乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个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.

这篇关于快速外部张量乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆