当我在knn
中使用sklearn
算法时,我可以获得我指定的半径内的最近邻居,即它返回该半径内最近邻居的圆形形状。是否有一个实现,您可以指定两个半径值以返回最近邻居的椭圆形状?
答案 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 KDTree
与custom 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)
当然,您可以选择在距离度量中应用任何仿射变换,以获得定向椭圆的旋转和缩放。