我有一个来自 networkx
包的 MultiDiGraph
类型的有向图 G
。
下面两次通话的号码不同。它们不应该是一样的吗?
G.number_of_edges()
networkx.convert_matrix.to_scipy_sparse_matrix(G).nnz
不幸的是,我无法在手动创建的小图中重现此问题,如下例所示,其中两个调用打印相同的数字 5:
import networkx as nx
tmp = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0), (1, 0), (3, 4)])
tmp.number_of_edges(): 5, nx.convert_matrix.to_scipy_sparse_matrix(tmp).nnz: 5
这里是 G
的输出:
G.number_of_edges(): 87780, nx.convert_matrix.to_scipy_sparse_matrix(G).nnz: 84242
G
是其他人生成的巨大图表,我无法在此处共享。
最佳答案
MultiDiGraph
在相同的两个节点之间可以有多个边。
scipy.sparse.csr_matrix
的 nnz
属性返回非空矩阵值的数量。如果图在两个节点之间具有多条边,则 nnz
的值将是每个方向上连接的节点数,而 .number_of_edges()
将是总数图中的边数。这些数字将会有所不同!
如果您想获取边的总数,请使用 csr_matrix
的 .sum()
值。
import networkx as nx
tmp = nx.MultiDiGraph([(0, 1), (1, 2), (2, 0), (1, 0), (3, 4)])
tmp.add_edge(3, 4)
tmp.add_edge(3, 4)
tmp.add_edge(3, 4)
nx_edge_count = tmp.number_of_edges()
scipy_nnz = nx.convert_matrix.to_scipy_sparse_matrix(tmp).nnz
scipy_edge_count = nx.convert_matrix.to_scipy_sparse_matrix(tmp).sum()
print("Number of edges: {}".format(nx_edge_count))
print("Number of non-zero matrix values: {}".format(scipy_nnz))
print("Sum of sparse matrix values: {}".format(scipy_edge_count))
Number of edges: 8
Number of non-zero matrix values: 5
Sum of sparse matrix values: 8
关于Python networkX MultiDiGraph 边数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013736/