当我在Python中使用Igraph检测图表上的社区时,我得到如下结果:
print g.community_multilevel(return_levels=False)
Clustering with 100 elements and 4 clusters
[0] 16, 17, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 39, 40, 44
[1] 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 19, 38, 92, 94, 96,
97, 98, 99
[2] 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 66, 67, 69
[3] 21, 41, 65, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91, 93, 95
我将相应的社区号作为属性添加到每个顶点,如下所示:
for v in g.vs():
c = 0
for i in g.community_multilevel(return_levels=False):
if v.index in i:
print v.index,i,c
v["group"] = c
c += 1
有没有更优雅的方法来实现这一目标?
答案 0 :(得分:2)
你正在做的事情是非常低效的,因为你正在为外循环的每一次迭代运行社区检测算法,即使它的结果应该是相同的,无论你运行多少次。一个更简单的方法是:
cl = g.community_multilevel(return_levels=False)
g.vs["group"] = cl.membership