sklearn半径中的K最近邻 - 椭圆

时间:2016-06-28 18:27:43

标签: scikit-learn knn

当我在knn中使用sklearn算法时,我可以获得我指定的半径内的最近邻居,即它返回该半径内最近邻居的圆形形状。是否有一个实现,您可以指定两个半径值以返回最近邻居的椭圆形状?

1 个答案:

答案 0 :(得分:1)

您可以在NearestNeighbors中指定自定义距离指标:

# aspect of the axis a, b of the ellipse
aspect = b / a
dist = lambda p0, p1: math.sqrt((p1[0] - p0[0]) * (p1[0] - p0[0]) + (p1[1] - p0[1]) * (p1[1] - p0[1]) * aspect)
nn = NearestNeighbors(radius=1.0, metric=dist)

或直接use the KDTreecustom metric

from sklearn.neighbors import KDTree
import numpy as np
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])

# aspect of the axis a, b of the ellipse
aspect = b / a
dist = DistanceMetric.get_metric('pyfunc', func = lambda p0, p1: math.sqrt((p1[0] - p0[0]) * (p1[0] - p0[0]) + (p1[1] - p0[1]) * (p1[1] - p0[1]) * aspect))
kdt = KDTree(X, leaf_size=30, metric=dist)

# now kdt allows queries with ellipses with aspect := b / a
kdt.query([0.1337, -0.42], k=6)

当然,您可以选择在距离度量中应用任何仿射变换,以获得定向椭圆的旋转和缩放。