我正在编写一个程序,该程序应该选择位于另一个点附近的点。邻域大小由半径指定。我为此使用sklearn.neighbors.KDTree算法。但是,它没有按我预期的那样工作。
为了向您展示我正在处理的内容,我有两个数据框:
df_example_points
,这是我要搜索的一组点,
>>> import pandas as pd
>>> from sklearn.neighbors import KDTree
>>> df_example_points = pd.DataFrame(
... {
... 'X': [-845.204, -845.262, -845.262, -845.262],
... 'Y': [-1986.243, -1986.077, -1986.077, -1986.079],
... 'Z': [246.655, 246.741, 246.742, 246.743],
... }
... )
>>> print(df_example_points)
X Y Z
0 -845.204 -1986.243 246.655
1 -845.262 -1986.077 246.741
2 -845.262 -1986.077 246.742
3 -845.262 -1986.079 246.743
和df_reference_point
,它由一个点组成,我想用它来定义其邻域。
>>> df_reference_point = pd.DataFrame({'X': [-845.002], 'Y': [-1986.32], 'Z': [246.508]})
>>> print(df_reference_point)
X Y Z
0 -845.002 -1986.32 246.508
[当我尝试对KDTree的期望进行硬编码时,似乎[K0Tree]中的每个点都应由KDTree提取为位于参考点附近的点。
df_example_points
但是,当我尝试使用KDTree时,仅提取了一个点。
>>> radius = 0.27
>>> x_ref, y_ref, z_ref = df_reference_point.iloc[0]
>>> x_min, x_max = x_ref - radius, x_ref + radius
>>> y_min, y_max = y_ref - radius, y_ref + radius
>>> z_min, z_max = z_ref - radius, z_ref + radius
>>> for i, (x, y, z) in df_example_points.iterrows():
... if all([x_min <= x <= x_max, y_min <= y <= y_max, z_min <= z <= z_max]):
... print(f'Point {i} SHOULD be extracted.')
... else:
... print(f'Point {i} SHOULD NOT be extracted.')
Point 0 SHOULD be extracted.
Point 1 SHOULD be extracted.
Point 2 SHOULD be extracted.
Point 3 SHOULD be extracted.
我想使用KDTree,因为实现要快得多。但是,当结果不可靠时,我将无法使用它。拜托,你能帮我吗,我在做什么错?我想念什么?
正如@Gabriel所说,您正在使用两个不同的距离度量。当您使用>>> tree = KDTree(df_example_points.values)
>>> extracted_points_indices = tree.query_radius(df_reference_point.values.reshape(1, -1), radius)[0]
>>> print(f'Number of extracted points: {len(extracted_points_indices)}')
Number of extracted points: 1
时,KDTree
默认值为minkowski
(您可以在此处检查sklearn可能的度量标准:chebyshev
)。
更改默认设置将获得预期的结果:
DistanceMetric