Multiply each element by numpy.array a with each element in numpy.array b

Given two numpy.array aand b,

c = numpy.outer(a, b)

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

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

In addition, let it bhave dimensions l.

  • What operation returns an array of cdimension k+1, where c[..., i1, i2, i3] == a * b[i1, i2, i3]?
+6
source share
5 answers

outerThe Ufuncs NumPy method handles multidimensional input the way you want, so you can do

numpy.multiply.outer(a, b)

instead of using 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.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,
)
+5

np.outer, reshape -

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

I think that np.tensordotalso 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 
+2
source

np.einsum is what you are looking for.

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

it 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)

+1
source

I think you are looking for a kronecker product

eg

> 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.]])
+1
source

Source: https://habr.com/ru/post/1015764/


All Articles