首页 > 解决方案 > 使用 networkx 上的权重从邻接矩阵创建网络

问题描述

这是我的问题:从我创建的 HMM 模型中,我想创建一个使用转换矩阵(具有从一个状态到另一个状态的概率)作为邻接矩阵的网络。这个矩阵中没有 0,对角线上也没有,因为您可以再次从状态 1 转到状态 1。我如何确定创建的网络实际上是使用权重(转换矩阵中的值)来创建社区?

我正在使用以下代码:

import community
import networkx as nx

G = nx.from_numpy_matrix(tm, parallel_edges=False, create_using=None)

# Relabel nodes
G = nx.relabel_nodes(G, {i: f"node_{i}" for i in G.nodes})

# Compute partition
partition = community.best_partition(G)

# Get a set of the communities
communities = set(partition.values())

# Create a dictionary mapping community number to nodes within that community
communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}
communities_dict

并且输出有意义:5 个社区(0 到 4)分组 25 个节点(从 0 到 24)

{0: ['node_0', 'node_1', 'node_14', 'node_17'],
 1: ['node_5', 'node_10', 'node_11', 'node_12'],
 2: ['node_2', 'node_20', 'node_24'],
 3: ['node_3', 'node_8', 'node_9', 'node_15', 'node_18', 'node_22'],
 4: ['node_4',   'node_6',   'node_7',  'node_13', 'node_16', 'node_19', 'node_21', 'node_23']}

我注意到这里有一篇关于堆栈溢出的帖子,他们在其中使用了

partition = community.best_partition(G, weight='weights')

我尝试实现它,结果很糟糕:每个节点都是一个社区(25 个节点上总共有 25 个社区)。

我的问题是:我对第一个代码做得好吗?或者正确的一个是返回坏社区的另一个?

标签: graphnetworkxadjacency-matrix

解决方案


推荐阅读