KDTree 的 Python 实现.

From: Python实现KNN与KDTree

1. KDTree 实现

scipy.spatial.KDTree - doc

import numpy as np
from scipy import spatial

datas = np.array([[0,0,0],
                  [0,0,128],
                  [0,0,139],
                  [0,0,156],
                  [0,0,205],
                  [0,0,238],
                  [0,0,255]])

#构建模型 - 最近邻
kdtree_model = spatial.KDTree(datas)

# 
qy = [0,0,205]
idx = kdtree_model.query(qy)[1]
#4

2. sklearn - KNeighborsClassifier

import numpy as np
from sklearn import neighbors

X = np.array([[0,0,0],
              [0,0,128],
              [0,0,139],
              [0,0,156],
              [0,0,205],
              [0,0,238],
              [0,0,255]])
Y = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

classifier = neighbors.KNeighborsClassifier()
classifier.fit(X, Y)

#
qy = np.array([[0,0,202]])
pred = classifier.predict(qy)
#['c']

3. 参考

[1] - Python实现KNN与KDTree

[2] - 【量化课堂】一只兔子帮你理解 kNN

[3] - kd 树算法之详细篇

Last modification:November 22nd, 2019 at 02:07 pm