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

问题描述 投票:2回答:1

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

scikit-learn knn
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.