Nearest Neighbor Search in Python without k-d tree

后端 未结 4 816
余生分开走
余生分开走 2021-02-08 08:16

I\'m beginning to learn Python coming from a C++ background. What I am looking for is a quick and easy way to find the closest (nearest neighbor) of some multidimensional query

4条回答
  •  我在风中等你
    2021-02-08 08:59

    Broadcasting is very useful for this kind of thing. I'm not sure if this is what you need, but here I use broadcasting to find the displacement between p (one point in 3 space) and X (a set of 10 points in 3-space).

    import numpy as np
    
    def closest(X, p):
        disp = X - p
        return np.argmin((disp*disp).sum(1))
    
    X = np.random.random((10, 3))
    p = np.random.random(3)
    
    print X
    #array([[ 0.68395953,  0.97882991,  0.68826511],
    #       [ 0.57938059,  0.24713904,  0.32822283],
    #       [ 0.06070267,  0.06561339,  0.62241713],
    #       [ 0.93734468,  0.73026772,  0.33755815],
    #       [ 0.29370809,  0.76298588,  0.68728743],
    #       [ 0.66248449,  0.6023311 ,  0.76704199],
    #       [ 0.53490144,  0.96555923,  0.43994738],
    #       [ 0.23780428,  0.75525843,  0.46067472],
    #       [ 0.84240565,  0.82573202,  0.56029917],
    #       [ 0.66751884,  0.31561133,  0.19244683]])
    print p
    #array([ 0.587416 ,  0.4181857,  0.2539029])
    print closest(X, p)
    #9
    

提交回复
热议问题