下面的代码为给定的图“G”查找社区,并基于它们所属的社区为该图中的节点分配0-n之间的值。然后,代码为每个社区创建新的子图,并在每个社区中找到度最高的节点。最后,每个子图的顶部节点集成到一个整体字典中:
G = 'max : john', 'max : tom', 'jim : john'....'jack : james'
node_partition = dict(community_louvain.best_partition(G))
print node_partition = max: 1, john: 0, james: 3, jim: 4,...tom: 0
"""number of communities = n = list(set(node_partition.values()))"""
dict0 = {k: v for k, v in node_partition.items() if v !=[0]}
G0 = G.copy()
G0.remove_nodes_from(dict0)
degree0 = dict(G.degree(G0))
degree0_dict = dict(sorted(degree0.items(), key=operator.itemgetter(1), reverse=True)[:1])
star_dict = {**degree0_dict, **degree1_dict....**degreek_dict)
这种方法是有效的,但是一个图可以有n个社区,正如您所看到的,上面的代码只适用于社区0中的节点。我必须手动读取已确定的社区数量,并手动重复和编辑每个数字的代码。如何应用一个自动重复此代码的函数,以使“n”代替“0”?你知道吗
假设您的分区存储在
node_partition
,那么我们将生成一个新的字典,它由node_partition
的倒排键、值对组成,这将有助于我们以后降低计算复杂度。(参见this for inverting dicitonary和this for getting key with max value in dictionary。)现在您可以使用字典
max_deg_per_comm
来获取节点,假设您想找到社区0的节点,您可以使用相关问题 更多 >
编程相关推荐