将numpy.array中的每个元素与numpy.array中的每个元素相乘

时间:2017-03-15 21:36:20

标签: python arrays numpy

鉴于两个numpy.array s ab

c = numpy.outer(a, b)

返回c[i, j] == a[i] * b[j]的二维数组。现在,假设a具有k维度。

  • 哪个操作返回维c的数组k+1,其中c[..., j] == a * b[j]

此外,让b具有l尺寸。

  • 哪个操作返回维c的数组k+1,其中c[..., i1, i2, i3] == a * b[i1, i2, i3]

5 个答案:

答案 0 :(得分:5)

NumPy ufunc的outer method以你想要的方式对待多维输入,所以你可以做到

numpy.multiply.outer(a, b)

而不是使用numpy.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,
        )

答案 1 :(得分:2)

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

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

答案 2 :(得分: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 

答案 3 :(得分: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)

答案 4 :(得分: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.]])
相关问题