Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy calculate square of norm 2 of vector

I have vector a.
I want to calculate np.inner(a, a)
But I wonder whether there is prettier way to calc it.

[The disadvantage of this way, that if I want to calculate it for a-b or a bit more complex expression, I have to do that with one more line. c = a - b and np.inner(c, c) instead of somewhat(a - b)]

like image 229
zardav Avatar asked Feb 04 '16 23:02

zardav


1 Answers

Honestly there's probably not going to be anything faster than np.inner or np.dot. If you find intermediate variables annoying, you could always create a lambda function:

sqeuclidean = lambda x: np.inner(x, x)

np.inner and np.dot leverage BLAS routines, and will almost certainly be faster than standard elementwise multiplication followed by summation.

In [1]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)
((a - b) ** 2).sum()
   ....: 
The slowest run took 36.13 times longer than the fastest. This could mean that an intermediate result is being cached 
1 loops, best of 100: 6.45 ms per loop

In [2]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)                                                                                                                                                                              
np.linalg.norm(a - b, ord=2) ** 2
   ....: 
1 loops, best of 100: 2.74 ms per loop

In [3]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000)
sqeuclidean(a - b)
   ....: 
1 loops, best of 100: 2.64 ms per loop

np.linalg.norm(..., ord=2) uses np.dot internally, and gives very similar performance to using np.inner directly.

like image 152
ali_m Avatar answered Sep 16 '22 12:09

ali_m