当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python NetworkX girvan_newman用法及代码示例


本文简要介绍 networkx.algorithms.community.centrality.girvan_newman 的用法。

用法:

girvan_newman(G, most_valuable_edge=None)

使用Girvan-Newman 方法在图中查找社区。

参数

GNetworkX 图
most_valuable_edge函数

将图形作为输入并输出边的函数。此函数返回的边将在算法的每次迭代中重新计算并删除。

如果未指定,将使用具有最高networkx.edge_betweenness_centrality() 的边。

返回

迭代器

迭代 G 中节点集的元组。每组节点是一个社区,每个元组是算法特定级别的社区序列。

注意

Girvan-Newman 算法通过从原始图中逐步删除边来检测社区。该算法在每一步都删除了“most valuable” 边,传统上是具有最高中介中心性的边。随着图表分解成碎片,紧密结合的社区结构暴露出来,结果可以描绘为树状图。

例子

要获得第一对社区:

>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

要仅获取社区的前 k 元组,请使用 itertools.islice()

>>> import itertools
>>> G = nx.path_graph(8)
>>> k = 2
>>> comp = girvan_newman(G)
>>> for communities in itertools.islice(comp, k):
...     print(tuple(sorted(c) for c in communities))
...
([0, 1, 2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5, 6, 7])

要在社区数量大于 k 时停止获取社区元组,请使用 itertools.takewhile()

>>> import itertools
>>> G = nx.path_graph(8)
>>> k = 4
>>> comp = girvan_newman(G)
>>> limited = itertools.takewhile(lambda c: len(c) <= k, comp)
>>> for communities in limited:
...     print(tuple(sorted(c) for c in communities))
...
([0, 1, 2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5, 6, 7])
([0, 1], [2, 3], [4, 5], [6, 7])

仅根据权重选择要删除的边:

>>> from operator import itemgetter
>>> G = nx.path_graph(10)
>>> edges = G.edges()
>>> nx.set_edge_attributes(G, {(u, v): v for u, v in edges}, "weight")
>>> def heaviest(G):
...     u, v, w = max(G.edges(data="weight"), key=itemgetter(2))
...     return (u, v)
...
>>> comp = girvan_newman(G, most_valuable_edge=heaviest)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9])

在选择具有例如最高中介中心性的边时利用边权重:

>>> from networkx import edge_betweenness_centrality as betweenness
>>> def most_central_edge(G):
...     centrality = betweenness(G, weight="weight")
...     return max(centrality, key=centrality.get)
...
>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G, most_valuable_edge=most_central_edge)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

要为边指定不同的排名算法,请使用 most_valuable_edge 关键字参数:

>>> from networkx import edge_betweenness_centrality
>>> from random import random
>>> def most_central_edge(G):
...     centrality = edge_betweenness_centrality(G)
...     max_cent = max(centrality.values())
...     # Scale the centrality values so they are between 0 and 1,
...     # and add some random noise.
...     centrality = {e: c / max_cent for e, c in centrality.items()}
...     # Add some random noise.
...     centrality = {e: c + random() for e, c in centrality.items()}
...     return max(centrality, key=centrality.get)
...
>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G, most_valuable_edge=most_central_edge)

相关用法


注:本文由纯净天空筛选整理自networkx.org大神的英文原创作品 networkx.algorithms.community.centrality.girvan_newman。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。