Skip to main content
 首页 » 编程设计

python之合并/平均比给定半径更近的邻居

2024年12月31日17sxdcgaq8080

我在 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() 

请您参考如下方法:

这里是一个使用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} 

示例输出: