简体   繁体   中英

multiply every element in numpy.array a with every element in numpy.array b

Given two numpy.array s a and b ,

c = numpy.outer(a, b)

returns an two-dimensional array where c[i, j] == a[i] * b[j] . Now, imagine a having k dimensions.

  • Which operation returns an array c of dimension k+1 where c[..., j] == a * b[j] ?

Additionally, let b have l dimensions.

  • Which operation returns an array c of dimension k+1 where c[..., i1, i2, i3] == a * b[i1, i2, i3] ?

The outer method of NumPy ufuncs treats multidimensional input the way you want, so you could do

numpy.multiply.outer(a, b)

rather than using numpy.outer .

All solutions suggested here are equally fast; for small arrays, multiply.outer has a slight edge

在此输入图像描述

Code for generating the image:

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.save(
    "out.png",
    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,
)

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

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

I think np.tensordot also works

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 

np.einsum is what you are looking for.

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

should be

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

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

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

I think you're looking for kroneker product

for example

> 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.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM