Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy np.multiply vs *-Operator [duplicate]

Tags:

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.

like image 973
Honeybear Avatar asked Mar 26 '18 14:03

Honeybear


People also ask

Is * Same as NP multiply?

There is no difference. However, the np. multiply function can take in additional, optional arguments, making it more versatile.

Is Matmul same as *?

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.

What is the difference between NP dot and NP multiply?

np. dot is the dot product of two matrices. Whereas np. multiply does an element-wise multiplication of two matrices.

Is NumPy matrix multiplication faster?

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


2 Answers

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__.

like image 188
jmd_dk Avatar answered Sep 22 '22 14:09

jmd_dk


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.

like image 36
hpaulj Avatar answered Sep 22 '22 14:09

hpaulj