一维1D阵列和3D阵列的高效乘积-NumPy [英] Efficient product of 1D array and 3D array along one dimension - NumPy
问题描述
我有两个numpy数组:
I have two numpy arrays:
- 一个称为t的形状为(70L,)的一维数组,其元素名为ti.
- 一个名为I的3D数组,形状为(70L,1024L,1024L),每个元素称为Ii.因此,ii的尺寸为(1024L,1024L)
我想沿第一维制作两个数组的乘积,即:
I would like to make a product of the two array along the first dimension, i.e.:
tI = t1*I1,t2*I2,...,tN*IN
例如,再次获得一个新的维度数组(70L,1024L,1024L),然后沿第一个维度取和,以获得一个维度数组(1024L,1024L):
such as to obtain again a new array of dimension (70L, 1024L, 1024L) and then take the sum along the first dimension in order to obtain an array of dimension (1024L, 1024L):
tsum = t1*I1 + t2*I2 + ... +tN*IN
目前,我对执行以下操作感到满意:
For the moment I am satisfied with doing the following:
tI = np.asarray([t[i]*I[i,:,:] for i in range(t.shape[0])])
tsum = np.sum(tI,axis=0)
但是随着数组尺寸的增加,它会有点慢. 我想知道是否存在一个numpy或scipy函数,该函数针对该特定任务进行了优化?
But it is going to be a bit slow is the dimensions of my array are increasing. I was wondering if there exist a numpy or scipy function, more optimized for that particular task?
首先感谢任何链接或信息.
Thanks in advance of any link or information.
格雷格
推荐答案
You can use np.tensordot
-
np.tensordot(t,I, axes=([0],[0]))
您还可以使用 np.einsum
-
You can also use np.einsum
-
np.einsum('i,ijk->jk',t,I)
运行时测试和输出验证-
Runtime test and output verification -
In [21]: def original_app(t,I):
...: tI = np.asarray([t[i]*I[i,:,:] for i in range(t.shape[0])])
...: tsum = np.sum(tI,axis=0)
...: return tsum
...:
In [22]: # Inputs with random elements
...: t = np.random.rand(70,)
...: I = np.random.rand(70,1024,1024)
...:
In [23]: np.allclose(original_app(t,I),np.tensordot(t,I, axes=([0],[0])))
Out[23]: True
In [24]: np.allclose(original_app(t,I),np.einsum('i,ijk->jk',t,I))
Out[24]: True
In [25]: %timeit np.tensordot(t,I, axes=([0],[0]))
1 loops, best of 3: 110 ms per loop
In [26]: %timeit np.einsum('i,ijk->jk',t,I)
1 loops, best of 3: 201 ms per loop
这篇关于一维1D阵列和3D阵列的高效乘积-NumPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!