我有一个三维空间中的几百个坐标,我需要把比给定半径更近的点合并起来,用邻居平均值来代替它们。
这听起来是一个相当标准的问题,但到目前为止我还没有找到解决办法。数据集足够小,能够计算所有点的成对距离。
不知道,也许是稀疏距离矩阵上的某种图分析/连通成分标记?
我真的不需要平均部分,只需要聚类(聚类是正确的术语吗?)
玩具数据集可以是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()

发布于 2018-05-10 16:46:06
下面是一种使用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}示例输出:

https://stackoverflow.com/questions/50274753
复制相似问题