用numpy.array a中的每个元素乘以numpy.array b中的每个元素

6

给定两个 numpy.array 数组 ab

c = numpy.outer(a, b)

返回一个二维数组,其中c[i, j] == a[i] * b[j]。现在,想象一下a具有k个维度。

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

另外,让b具有l个维度。

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

7

NumPy的ufunc的outer方法可以按你想要的方式处理多维输入,所以你可以这样做:

np.multiply.outer(a, b)

使用 numpy.outer 不如其他方法快。

这里提出的所有解决方案速度都相同;对于小数组,multiply.outer 稍微占优势。

enter image description here

生成该图像的代码:

import numpy as np
import perfplot


def multiply_outer(a, b):
    return np.multiply.outer(a, b)


def outer_reshape(a, b):
    return np.outer(a, b).reshape((a.shape + b.shape))


def tensor_dot(a, b):
    return np.tensordot(a, b, 0)


b = perfplot.bench(
    setup=lambda n: (np.random.rand(n, n), np.random.rand(n, n)),
    kernels=[multiply_outer, outer_reshape, tensor_dot],
    n_range=[2 ** k for k in range(7)],
)
b.save("out.png")

2

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

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

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 

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
我认为您正在寻找克罗内克积。
例如:
> 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.]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接