moons数据集谱聚类后使用Networkx构建3近邻图及区分集群节点样式
实现代码(可直接衔接你现有代码运行)
# ---------------------- k=3近邻图构建与可视化代码 ---------------------- k = 3 # 转换亲和度矩阵为numpy数组格式 affinity_mat = clustering.affinity_matrix_.toarray() # 初始化图对象 G = nx.Graph() # 批量添加节点,绑定节点坐标和聚类标签属性 for idx in range(len(X)): G.add_node(idx, pos=X[idx], cluster_label=y_predict[idx]) # 为每个节点添加k个近邻边:按亲和度从高到低取前3个非自身节点 for i in range(len(X)): top_k_idx = np.argsort(-affinity_mat[i])[1:k+1] for j in top_k_idx: # 避免重复添加无向边 if not G.has_edge(i, j): G.add_edge(i, j, weight=affinity_mat[i][j]) # 自定义两个集群的节点样式:[填充颜色, 节点形状] cluster_style = { 0: ["#1a56db", "o"], # 集群0:蓝色圆形 1: ["#e53e3e", "^"] # 集群1:红色三角形 } plt.figure(figsize=(8, 6)) # 绘制边:权重越高,边越粗、越明显 pos = nx.get_node_attributes(G, "pos") nx.draw_networkx_edges( G, pos, alpha=0.4, width=[G[u][v]["weight"] * 2 for u, v in G.edges()] ) # 按集群属性分组绘制节点,保留你原有的预测正确/错误的填充逻辑 for node_id, attr in G.nodes(data=True): cluster = attr["cluster_label"] color, marker = cluster_style[cluster] if y[node_id] == cluster: # 预测正确的节点实心显示 nx.draw_networkx_nodes(G, pos, nodelist=[node_id], node_color=color, node_shape=marker, node_size=200) else: # 预测错误的节点空心显示 nx.draw_networkx_nodes(G, pos, nodelist=[node_id], node_color="none", edgecolors=color, node_shape=marker, node_size=200) plt.axis("equal") plt.title("k=3 Nearest Neighbor Graph") plt.show()
核心逻辑说明
- 仅基于谱聚类输出的亲和度矩阵计算近邻,每个节点仅保留亲和度最高的3条边
- 节点颜色、形状可通过修改
cluster_style字典参数自定义调整 - 边的粗细和亲和度权重直接挂钩,亲和度越高的节点对之间的边越突出
内容的提问来源于stack exchange,提问作者Ytt
相关产品推荐
相关产品推荐

