2017-03-15 45 views

回答

5

NumPy的ufuncs对待多维输入你想要的方式,所以你可以做

numpy.multiply.outer(a, b) 

,而不是使用的outer methodnumpy.outer

这里建议的所有解决方案同样快;对于小数组,multiply.outer有轻微的边缘

enter image description here

代码生成图像:

import numpy 
import perfplot 


def multiply_outer(data): 
    a, b = data 
    return numpy.multiply.outer(a, b) 


def outer_reshape(data): 
    a, b = data 
    return numpy.outer(a, b).reshape((a.shape + b.shape)) 


def tensor_dot(data): 
    a, b = data 
    return numpy.tensordot(a, b, 0) 


perfplot.show(
     setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n, n)), 
     kernels=[multiply_outer, outer_reshape, tensor_dot], 
     n_range=[2**k for k in range(7)], 
     logx=True, 
     logy=True, 
     ) 
2

一种方法是使用np.outer然后reshape -

np.outer(a,b).reshape((a.shape + b.shape)) 
1

np.einsum是你在找什么。

c[..., j] == a * b[j]

应该

c = np.einsum('...i,j -> ...ij', a, b)

c[..., i1, i2, i3] == a * b[i1, i2, i3]

c = np.einsum('i,...jkl -> ...ijkl', a, b)

1

我认为你正在寻找kroneker产品

例如

> np.kron(np.eye(2), np.ones((2,2))) 

array([[ 1., 1., 0., 0.], 
     [ 1., 1., 0., 0.], 
     [ 0., 0., 1., 1.], 
     [ 0., 0., 1., 1.]]) 
2

我觉得np.tensordot也适用

c = np.tensordot(a, b, 0) 

inds = np.reshape(np.indices(b.shape), (b.ndim, -1)) 
for ind in inds.T: 
    ind = tuple(ind) 
    assert np.allclose(a * b[ind], c[(...,) + ind]) 
else: 
    print('no error') 
# no error 
相关问题