merge/average 个比给定半径更近的邻居
merge/average neighbors closer than a given radius
我在 3d space 中有几百个坐标,我需要合并比给定半径更近的点并将它们替换为邻居平均值。
这听起来像是一个非常标准的问题,但到目前为止我还没有找到解决方案。数据集足够小,能够计算所有点的成对距离。
不知道,也许在稀疏距离矩阵上进行某种图形分析/连通分量标记?
我真的不需要平均部分,只需要聚类(这里的聚类是正确的术语吗?)
玩具数据集可以是 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}
示例输出:
我在 3d space 中有几百个坐标,我需要合并比给定半径更近的点并将它们替换为邻居平均值。
这听起来像是一个非常标准的问题,但到目前为止我还没有找到解决方案。数据集足够小,能够计算所有点的成对距离。
不知道,也许在稀疏距离矩阵上进行某种图形分析/连通分量标记?
我真的不需要平均部分,只需要聚类(这里的聚类是正确的术语吗?)
玩具数据集可以是 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}
示例输出: