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

如何在KD-Tree中忽略间距获取多维空间的直接邻点?

多维空间直接邻点查找问题(最多7维)

需要在最多7维的多维空间中查找给定点的直接邻点,该空间具备以下特点:

  • 单维度内点的间距呈非线性变化
  • 不同维度间的间距不等

非等距网格生成示例代码

x_values = np.linspace(-0.3, 0.3, 5)
y_values = np.linspace(-0.3, 0.3, 5)
z_values = np.linspace(1, 6, 6) # z方向间距更大(非等距)

最小可复现代码(MWE)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.neighbors import KDTree
import numpy as np


# 定义X、Y、Z的取值范围
x_values = np.linspace(-0.3, 0.3, 5)
y_values = np.linspace(-0.3, 0.3, 5)
z_values = np.linspace(1, 6, 6) # z方向间距更大(非等距)
# z_values = np.linspace(-0.3, 0.3, 5) # 等距情况测试

# 生成网格点组合
X, Y, Z = np.meshgrid(x_values, y_values, z_values)

# 将网格点重塑为单个数组
points = np.column_stack((X.ravel(), Y.ravel(), Z.ravel()))

# 创建KDTree对象
kdtree = KDTree(points, leaf_size=30, metric='euclidean')

# 待查询的目标点
# query_point = np.array([[0, 0, 0]]) # 等距情况测试点
query_point = np.array([[0, 0, 2]]) # 非等距情况测试点

# 查询最近邻点的索引和距离
distances, indices = kdtree.query(query_point, k=27)

# 3D可视化所有点
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:, 0], points[:, 1], points[:, 2], color='blue', label='所有点')

# 绘制查询点
ax.scatter(query_point[:, 0], query_point[:, 1], query_point[:, 2], color='red', label='查询点')

# 绘制最近邻点
nearest_neighbors = points[indices[0]]  # 通过索引获取最近邻点
ax.scatter(nearest_neighbors[:, 0], nearest_neighbors[:, 1], nearest_neighbors[:, 2], color='green', label='最近邻点')

# 连接查询点与最近邻点
for neighbor in nearest_neighbors:
    ax.plot([query_point[0, 0], neighbor[0]], [query_point[0, 1], neighbor[1]], [query_point[0, 2], neighbor[2]], color='gray', linestyle='--')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D空间中KD-Tree最近邻结果')
ax.legend()
plt.show()

print()

当前代码运行结果

代码运行结果

期望结果

无论实际距离如何,从每个维度中选择直接邻点。
期望结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:05:55