如何在igraph中运行Louvain社区检测算法?

8

请问有没有人能够为我提供一个简单的示例,演示如何使用Python接口在igraph中运行Louvain社区检测算法?是否有任何文档可供参考?

谢谢!


1
http://igraph.org/python/doc/igraph.Graph-class.html#community_multilevel - Gabor Csardi
主要问题是 multilevel.community 的结果与我通过在 networkx 中重建相同的图然后运行此命令得到的结果不匹配:http://perso.crans.org/aynaud/communities/community.py 我已经仔细检查了代码,没有发现任何特定参数的选择。 - vgoklani
1
Louvain 中的一些处理是随机的,因此即使多次处理完全相同的图形,也正常不会具有完全相同的结果。 - Vincent Labatut
2个回答

9

它被称为multilevel.community

根据https://bugs.launchpad.net/igraph/+bug/925038,这个功能确实存在,只不过被称为igraph_community_multilevel

如果您在 igraph 的 github 存储库中查看

https://github.com/igraph/igraph/blob/master/src/community.c

igraph_community_multilevel 确实存在,并且是用 C 写的。我不能百分之百确定这是您想要的算法,但它可能是。

这是个好消息!谢谢! 这个功能是否导出到 R 中? 为什么这个函数有一个通用名称(igraph_community_multilevel), 而不是作者给出的名称(“Louvain方法”)? 使用“Louvain”名称将使用户更容易找到该函数!


7

以下是如何使用Python中的Louvain算法在3个不同模块( igraph , networkx , bct )中估计模块度 Q 的方法。

import numpy as np
import networkx as nx
np.random.seed(9)

# I will generate a stochastic block model using `networkx` and then extract the weighted adjacency matrix.
sizes = [50, 50, 50] # 3 communities
probs = [[0.25, 0.05, 0.02],
         [0.05, 0.35, 0.07],
         [0.02, 0.07, 0.40]]

# Build the model
Gblock = nx.stochastic_block_model(sizes, probs, seed=0)

# Extract the weighted adjacency
W = np.array(nx.to_numpy_matrix(Gblock, weight='weight'))
W[W==1] = 1.5
print(W.shape)
# (150, 150)

#* Modularity estimation using Louvain algorithm 
# 1. `igraph` package

from igraph import *
graph = Graph.Weighted_Adjacency(W.tolist(), mode=ADJ_UNDIRECTED, attr="weight", loops=False)
louvain_partition = graph.community_multilevel(weights=graph.es['weight'], return_levels=False)
modularity1 = graph.modularity(louvain_partition, weights=graph.es['weight'])
print("The modularity Q based on igraph is {}".format(modularity1))

# 2. `networkx`package using `python-louvain`
# https://python-louvain.readthedocs.io/en/latest/

import networkx as nx
import community
G = nx.from_numpy_array(W)
louvain_partition = community.best_partition(G, weight='weight')
modularity2 = community.modularity(louvain_partition, G, weight='weight')
print("The modularity Q based on networkx is {}".format(modularity2))

# 3. `bct` module
# https://github.com/aestrivex/bctpy

import bct
com, q = bct.community_louvain(W)
print("The modularity Q based on bct is {}".format(q))


这将打印:

The modularity Q based on igraph is 0.4257613861340037
The modularity Q based on networkx is 0.4257613861340036
The modularity Q based on bct is 0.42576138613400366

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接