scikit学习- sklearn半径中的K近邻-椭圆



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

您可以在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)

或者直接使用带有自定义度量的KDTree:

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)

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

相关内容

  • 没有找到相关文章

最新更新