Numpy Broadcast to perform euclidean distance vectorized

后端 未结 5 2090
无人共我
无人共我 2020-12-04 14:44

I have matrices that are 2 x 4 and 3 x 4. I want to find the euclidean distance across rows, and get a 2 x 3 matrix at the end. Here is the code with one for loop that compu

5条回答
  •  一向
    一向 (楼主)
    2020-12-04 15:42

    Using numpy.linalg.norm also works well with broadcasting. Specifying an integer value for axis will use a vector norm, which defaults to Euclidean norm.

    import numpy as np
    
    a = np.array([[1,1,1,1],[2,2,2,2]])
    b = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]])
    np.linalg.norm(a[:, np.newaxis] - b, axis = 2)
    
    # array([[ 3.74165739,  0.        ,  8.06225775],
    #       [ 2.44948974,  2.        ,  7.14142843]])
    

提交回复
热议问题