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

vgo*_*ani 4 python graph igraph networkx

有人可以请给我一个简单的例子,说明如何使用python接口在igraph中运行louvain社区检测算法.有文件吗?

谢谢!

Gre*_*bet 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"这个名称可以让用户更容易找到这个功能!


mak*_*kis 6

以下是如何在 python ( , , ) 中Q使用louvain3 个不同模块中的算法来估计模块性。igraphnetworkxbct

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))


Run Code Online (Sandbox Code Playgroud)

这打印:

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
Run Code Online (Sandbox Code Playgroud)