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.
c
of dimension k+1
where c[..., j] == a * b[j]
?Additionally, let b
have l
dimensions.
c
of dimension k+1
where c[..., i1, i2, i3] == a * b[i1, i2, i3]
?You can use np. multiply to multiply two same-sized arrays together. This computes something called the Hadamard product. In the Hadamard product, the two inputs have the same shape, and the output contains the element-wise product of each of the input values.
If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
The outer
method of NumPy ufuncs treats multidimensional input the way you want, so you could do
np.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 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")
One approach would be using np.outer
and then reshape
-
np.outer(a,b).reshape((a.shape + b.shape))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With