Nearest Neighbor Search in Python without k-d tree

后端 未结 4 823
余生分开走
余生分开走 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:47

    If concise is your goal, you can do this one-liner:

    In [14]: X = scipy.randn(10,2)
    
    In [15]: X
    Out[15]: 
    array([[ 0.85831163,  1.45039761],
           [ 0.91590236, -0.64937523],
           [-1.19610431, -1.07731673],
           [-0.48454195,  1.64276509],
           [ 0.90944798, -0.42998205],
           [-1.17765553,  0.20858178],
           [-0.29433563, -0.8737285 ],
           [ 0.5115424 , -0.50863231],
           [-0.73882547, -0.52016481],
           [-0.14366935, -0.96248649]])
    
    In [16]: q = scipy.array([0.91, -0.43])
    
    In [17]: scipy.argmin([scipy.inner(q-x,q-x) for x in X])
    Out[17]: 4
    

    If you have several query points:

    In [18]: Q = scipy.array([[0.91, -0.43], [-0.14, -0.96]])
    
    In [19]: [scipy.argmin([scipy.inner(q-x,q-x) for x in X]) for q in Q]
    Out[19]: [4, 9]
    

提交回复
热议问题