重命名节点时NetworkX中的Bipartite无法正常工作

2024-05-15 00:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用networkX将二部图转换为人与人的关系图:

import networkx as nx
import ast
from networkx.algorithms import bipartite
x=(161,1),(589,2),(162,1),(163,1),(589,2)
BI = nx.Graph()
BI.add_edges_from(x)
bottom_nodes, top_nodes = bipartite.sets(BI)
GI = bipartite.projected_graph(BI, top_nodes)
GI.edges()

结果不正确:

^{pr2}$

如果我把x改为:

x=(61,1),(58,2),(62,1),(63,1),(59,2)

我得到正确的结果:

>>> bottom_nodes
{1, 2}
>>> top_nodes
{58, 59, 61, 62, 63}

因此,如果我对节点使用“较低”的数字,那么转换是正确的,否则就不正确。但是,我需要更大的数字,因为我有100多个节点。在


Tags: fromimportnetworkx节点关系top数字nodes
2条回答

二部图中的节点集是等价的(如果我使用了错误的术语,请纠正我的错误)-没有什么主要区别,哪一个命名为“top”和“bottom”。在

根据Choosing which sets of nodes are 'top' and 'bottom' in bipartite graph representations of real-world complex networks. - Mathematics Stack Exchange中的参考文献,对它们进行这样的分类是在特定应用中商定的惯例(为了一致性),而不是任何数学差异。所以,两个答案都是正确的。在

查看networkx.algorithms.bipartite.sets的源代码可以发现,它委托给networkx.algorithms.bipartite.color,后者依次迭代节点。在for n in G中排名第一的节点总是被赋予颜色1,并进入sets中的第一个集合:

In [2]: x=(161,1),(589,2),(162,1),(163,1),(589,2)
In [4]: g=networkx.Graph(x)
In [8]: g2=networkx.Graph(((80,2),(589,2),(162,1),(163,1),(589,2)))

In [11]: [n for n in g]
Out[11]: [161, 2, 163, 1, 162, 589]

In [12]: [n for n in g2]
Out[12]: [1, 2, 163, 162, 589, 80]

In [14]: networkx.algorithms.bipartite.sets(g)
Out[14]: ({2, 161, 162, 163}, {1, 589})

In [13]: networkx.algorithms.bipartite.sets(g2)
Out[13]: ({1, 2}, {80, 162, 163, 589})

因此,如果你有一些特定的想法,一个节点的哪些属性应该归类为“top”/“bottom”,那么你需要把它实际编程到:例如,看看结果,看看结果是什么。在

既然你已经知道你的二部集是什么,你可以显式地指定它们。在

import networkx as nx                                                           
from networkx.algorithms import bipartite                                       
x=(161,1),(589,2),(162,1),(163,1),(589,2)                                       
BI = nx.Graph(x)                                                                
top = set(s for s,t in x)                                                       
print(top)                                                                      
GI = bipartite.projected_graph(BI, top)                                         
print(list(GI.edges()))  

输出

^{pr2}$

相关问题 更多 >

    热门问题