python - 合并/平均比给定半径更近的邻居
问题描述
我在 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}
示例输出:
推荐阅读
- python - 如何通过浏览器从网络摄像头获取实时流视频详细信息到 python?
- python - Kubernetes:如何使用 python api 获取命名空间中的所有 pod?
- amazon-web-services - AWS SES - Nodemailer - transporter.sendEmail 不是函数
- datatables - 数据表脚本 DOM
- php - Soapclient 和用户 Kerberos 身份验证的转移
- java - 在字符串的开头添加 BOM
- python - 将参数传递给 wsadmin 中的 jython 脚本
- xml - 如何将 Xml 输出到文件?
- ruby-on-rails - mcmire/active_campaign - “联系电子邮件地址无效。”
- graphql - 无法在 GraphQL 查询定义中抽象出解析函数