首页 > 解决方案 > 合并/平均比给定半径更近的邻居

问题描述

我在 3d 空间中有几百个坐标,我需要合并比给定半径更近的点,并用邻居平均值替换它们。

这听起来像是一个非常标准的问题,但到目前为止我还没有找到解决方案。数据集足够小,可以计算所有点的成对距离。

不知道,也许是稀疏距离矩阵上的某种图形分析/连通分量标记?

我真的不需要平均部分,只需要聚类(在这里聚类是正确的术语吗?)

玩具数据集可以是coords = np.random.random(size=(100,2))

这是我到目前为止尝试使用的scipy.cluster.hierarchy. 它似乎工作正常,但我愿意接受更多建议(DBSCAN也许?)

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

from scipy.cluster.hierarchy import fclusterdata
from scipy.spatial.distance import pdist

np.random.seed(0)

fig = plt.figure(figsize=(10,5))

gs = mpl.gridspec.GridSpec(1,2)
gs.update(wspace=0.01, hspace= 0.05)

coords = np.random.randint(30, size=(200,2))
img = np.zeros((30,30))
img[coords.T.tolist()] = 1

ax = plt.subplot(gs[0])
ax.imshow(img, cmap="nipy_spectral")

clusters = fclusterdata(coords, 2, criterion="distance", metric="euclidean")
print(len(np.unique(clusters)))

img[coords.T.tolist()] = clusters

ax = plt.subplot(gs[1])
ax.imshow(img, cmap="nipy_spectral")

plt.show()

集群

标签: pythonnumpyscipydistance

解决方案


这是一种使用 KDTree 查询邻居和 networkx 模块来收集连接组件的方法。

from scipy import spatial
import networkx as nx

cutoff = 2

components = nx.connected_components(
    nx.from_edgelist(
        (i, j) for i, js in enumerate(
            spatial.KDTree(coords).query_ball_point(coords, cutoff)
        )
        for j in js
    )
)

clusters = {j: i for i, js in enumerate(components) for j in js}

示例输出:

在此处输入图像描述


推荐阅读