python中不同形状的数组的基本乘法

[英]Elementwise multiplication of arrays of different shapes in python


Say I have two arrays a and b,

假设有两个数组a和b,

  a.shape = (5,2,3)
  b.shape = (2,3)

then c = a * b will give me an array c of shape (5,2,3) with c[i,j,k] = a[i,j,k]*b[j,k].

那么c = a *b会给我一个形状为c(5,2,3)的数组,c[i,j,k] = a[i,j,k]*b[j,k]。

Now the situation is,

现在的情况是,

  a.shape = (5,2,3)
  b.shape = (2,3,8)

and I want c to have a shape (5,2,3,8) with c[i,j,k,l] = a[i,j,k]*b[j,k,l].

我想让c有一个形状(5,2,3,8)c[I,j,k,l] = a[I,j,k]*b[j,k,l]

How to do this efficiently? My a and b are actually quite large.

如何有效地做到这一点?我的a和b实际上很大。

2 个解决方案

#1


13  

This should work:

这应该工作:

a[..., numpy.newaxis] * b[numpy.newaxis, ...]

Usage:

用法:

In : a = numpy.random.randn(5,2,3)

In : b = numpy.random.randn(2,3,8)

In : c = a[..., numpy.newaxis]*b[numpy.newaxis, ...]

In : c.shape
Out: (5, 2, 3, 8)

Ref: Array Broadcasting in numpy

Ref: numpy中的数组广播

Edit: Updated reference URL

编辑:更新引用URL

#2


7  

I think the following should work:

我认为以下方法应该有效:

import numpy as np
a = np.random.normal(size=(5,2,3))
b = np.random.normal(size=(2,3,8))
c = np.einsum('ijk,jkl->ijkl',a,b)

and:

和:

In [5]: c.shape
Out[5]: (5, 2, 3, 8)

In [6]: a[0,0,1]*b[0,1,2]
Out[6]: -0.041308376453821738

In [7]: c[0,0,1,2]
Out[7]: -0.041308376453821738

np.einsum can be a bit tricky to use, but is quite powerful for these sort of indexing problems:

np。einsum的使用可能有点棘手,但对于这类索引问题却非常强大:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html

http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html

Also note that this requires numpy >= v1.6.0

还要注意,这需要numpy >= v1.6.0

I'm not sure about efficiency for your particular problem, but if it doesn't perform as well as needed, definitely look into using Cython with explicit for loops, and possibly parallelize it using prange

我不确定您的特定问题的效率,但是如果它的性能不如需要的那么好,一定要考虑使用Cython显式for循环,并可能使用prange将其并行化

UPDATE

更新

In [18]: %timeit np.einsum('ijk,jkl->ijkl',a,b)
100000 loops, best of 3: 4.78 us per loop

In [19]: %timeit a[..., np.newaxis]*b[np.newaxis, ...]
100000 loops, best of 3: 12.2 us per loop


In [20]: a = np.random.normal(size=(50,20,30))
In [21]: b = np.random.normal(size=(20,30,80))

In [22]: %timeit np.einsum('ijk,jkl->ijkl',a,b)
100 loops, best of 3: 16.6 ms per loop

In [23]: %timeit a[..., np.newaxis]*b[np.newaxis, ...]
100 loops, best of 3: 16.6 ms per loop

In [2]: a = np.random.normal(size=(500,20,30))
In [3]: b = np.random.normal(size=(20,30,800))

In [4]: %timeit np.einsum('ijk,jkl->ijkl',a,b)
1 loops, best of 3: 3.31 s per loop

In [5]: %timeit a[..., np.newaxis]*b[np.newaxis, ...]
1 loops, best of 3: 2.6 s per loop
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/05/20/7202a9de20081c9771df17be0d29b36b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告