Is there any difference in using
import numpy as np a, b = np.random([1024, 1024]), np.random([1024, 1024]) c = np.multiply(a, b)
over
c = a * b
or is the *
-Operator on numpy-arrays simply overridden with np.multiply
?
Edit: This question is marked as duplicate because a question asks the same thing about the division operator (np.divide()
vs /
) and similar answers followed, but unless it is changed to "numpy arithmetic vs. python arithmetic" or something of the kind, it won't help people wondering the same thing as I did (about multiplication) and not being "clever" enough to assume a question about a related arithmetic operation (division) generalizes to all the basic arithmetic operations. To make it easier finding answers, I'd advocate for keeping this question as is.
There is no difference. However, the np. multiply function can take in additional, optional arguments, making it more versatile.
np. matmul and @ are the same thing, designed to perform matrix multiplication. @ is added to Python 3.5+ to give matrix multiplication its own infix. np.
np. dot is the dot product of two matrices. Whereas np. multiply does an element-wise multiplication of two matrices.
Matrix multiplications in NumPy are reasonably fast without the need for optimization. However, if every second counts, it is possible to significantly improve performance (even without a GPU).
There is no difference. However, the np.multiply
function can take in additional, optional arguments, making it more versatile. See the docs.
Saying that *
is overwritten with np.multiply
would not be very precise. Generally, *
maps to calls to the __mul__
and __rmul__
methods on the objects on which it acts. Thus, *
is rather "overwritten" with np.ndarray.__mul__
.
speed differences - none:
In [65]: timeit c = np.multiply(a,b) 4.95 ms ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [66]: timeit c = a*b 5.06 ms ± 180 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
For smaller arrays we might see differences due to a different calling stack, but with these, the actual computation dominates the time.
But as you can see from the docs, np.multiply
is a ufunc
with access to all the machinery that that implies.
For np.matrix
objects, *
is matrix product, np.multiply
is element multiplication.
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