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

时间:2014-09-27 00:13:31

标签: python graph networkx igraph

有人可以请我提供一个简单的例子,说明如何使用python界面在igraph中运行louvain社区检测算法。有没有文件?

谢谢!

2 个答案:

答案 0 :(得分:7)

它被称为multilevel.community

根据https://bugs.launchpad.net/igraph/+bug/925038 ...此功能确实存在,它只是名为igraph_community_multilevel

如果你在github存储库中查找igraph

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

igraph_community_multilevel确实存在并且用C语言编写。我不是100%肯定这是你想要的算法,但它可能是。

  

这是个好消息!谢谢!   此功能是否已导出到R?   为什么函数带有通用名称(igraph_community_multilevel)   而不是作者给出的名字(“louvain方法”)?   使用“louvain”这个名称可以让用户更容易找到这个功能!

答案 1 :(得分:2)

以下是在Python中的3个不同模块(Qlouvainigraph)中使用networkx算法估算模块性bct的方法。

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
相关问题