You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找数组中不等于给定点的最近邻点

问题解决方案

不需要更换现有KDTree方案,仅需要补充少量过滤逻辑即可实现需求,比替换其他近邻查询工具或手写实现效率更高,以下是两种常用实现方式:

方案1:多查若干最近邻,跳过等值点

KDTree的query方法支持返回前k个最近点,你可以查询k≥2的结果,遍历返回结果跳过和x等值的点,取第一个非等值点即可:

import numpy as np
from scipy.spatial import KDTree

# 示例数据
point_arr = np.array([[1, 2], [3, 4], [1, 2], [5, 6]])
x = np.array([1, 2])

# 构建KDTree
tree = KDTree(point_arr)
# 多查询几个近邻,避免数组内存在多个和x等值的点
query_k = 3
dists, indices = tree.query(x, k=query_k)

target_y = None
min_distance = None
# 浮点数比较加极小容差,避免精度问题导致误判
tolerance = 1e-9
for d, idx in zip(dists, indices):
    if d > tolerance:
        target_y = point_arr[idx]
        min_distance = d
        break

if target_y is None:
    print("数组内所有点均和x相等,无符合要求的近邻点")
else:
    print(f"符合条件的最近邻:{target_y},距离:{min_distance}")

方案2:先对数组去重再构建KDTree

如果你的数值数组内存在大量重复点,可以提前对数组去重后再构建KDTree,后续直接查询k=1即可,能有效降低查询开销:

import numpy as np
from scipy.spatial import KDTree

point_arr = np.array([[1, 2], [3, 4], [1, 2], [5, 6]])
# 按行去重
unique_points = np.unique(point_arr, axis=0)
x = np.array([1, 2])

tree = KDTree(unique_points)
min_dist, idx = tree.query(x, k=1)

tolerance = 1e-9
if min_dist < tolerance and len(unique_points) == 1:
    print("数组内所有点均和x相等,无符合要求的近邻点")
else:
    target_y = unique_points[idx]
    print(f"符合条件的最近邻:{target_y},距离:{min_dist}")

注意:如果所有点都和x相等,两种方案都需要加兜底判断,避免运行报错。

内容的提问来源于stack exchange,提问作者CBBAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:57:00