NumPy: how to quickly normalize many vectors?

前端 未结 6 979
梦毁少年i
梦毁少年i 2021-01-31 04:47

How can a list of vectors be elegantly normalized, in NumPy?

Here is an example that does not work:

from numpy import *

vectors = array([arange         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 05:48

    For the two-dimensional case, using np.hypot(vectors[:,0],vectors[:,1]) looks to be faster than Freddie Witherden's np.sqrt(np.einsum('...i,...i', vectors, vectors)) for calculating the magnitudes. (Referencing answer by Geoff)

    import numpy as np
    
    # Generate array of 2D vectors.
    vectors = np.random.random((1000,2))
    
    # Using Freddie's
    %timeit np.sqrt(np.einsum('...i,...i', vectors, vectors))
    # Output: 11.1 µs ± 173 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    # Using numpy.hypot()
    %timeit np.hypot(vectors[:,0], vectors[:,1])
    # Output: 6.81 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

    To get the normalised vectors then do:

    vectors /= np.hypot(vectors[:,0], vectors[:,1])
    

提交回复
热议问题