Numpy Broadcast to perform euclidean distance vectorized

后端 未结 5 2072
无人共我
无人共我 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:44

    This functionality is already included in scipy's spatial module and I recommend using it as it will be vectorized and highly optimized under the hood. But, as evident by the other answer, there are ways you can do this yourself.

    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.sqrt((np.square(a[:,np.newaxis]-b).sum(axis=2)))
    # array([[ 3.74165739,  0.        ,  8.06225775],
    #       [ 2.44948974,  2.        ,  7.14142843]])
    from scipy.spatial.distance import cdist
    cdist(a,b)
    # array([[ 3.74165739,  0.        ,  8.06225775],
    #       [ 2.44948974,  2.        ,  7.14142843]])
    

提交回复
热议问题