这里是如何在 python (igraph,networkx,bct) 的 3 个不同模块中使用 louvain 算法估计模块化 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