Infomap Python API
infomap 是一种基于Map equation的网络聚类算法
原理
是一种基于层距离编码的无监督社区发现算法,为了区分随机游走从一个群组进入到了另一个群组,除了群组的名字之外,对于每个群组的跳出动作也给予了一个编码。比如,下图(c)中红色节点部分是一个群组,群组名的编码是 111,跳出编码是 0001。这样在描述某个群组内部的一段随机游走路径的时候,总是以群组名的编码开头,以跳出编码结束。
详细原理具体可以参考文末的参考文献列表。
安装
可以使用 PyPI 安装 Infomap。命令:
pip install infomap
如果需要升级的话:
pip install --upgrade infomap
用法
- 查看版本号,终端输入:
infomap -v
- 查看帮助,终端输入:
infomap --help
- Python代码中使用
import infomap
from infomap import Infomap
# Command line flags can be added as a string to Infomap
im = Infomap("--two-level --directed")
# Add weight as optional third argument
im.add_link(0, 1)
im.add_link(0, 2)
im.add_link(0, 3)
im.add_link(1, 0)
im.add_link(1, 2)
im.add_link(2, 1)
im.add_link(2, 0)
im.add_link(3, 0)
im.add_link(3, 4)
im.add_link(3, 5)
im.add_link(4, 3)
im.add_link(4, 5)
im.add_link(5, 4)
im.add_link(5, 3)
# Run the Infomap search algorithm to find optimal modules
im.run()
print(f"Found {im.num_top_modules} modules with codelength: {im.codelength}")
print("Result")
print("\n#node module")
for node in im.tree:
if node.is_leaf:
print(node.node_id, node.module_id)
Found 2 modules with codelength: 2.32073035683379=======================================================
Infomap v2.6.0 starts at
-> Input network:
-> No file output!
-> Configuration: two-level
directed
=======================================================
OpenMP 201307 detected with 48 threads...
-> Ordinary network input, using the Map Equation for first order network flows
Calculating global network flow using flow model 'directed'...
-> Using unrecorded teleportation to links.
-> PageRank calculation done in 50 iterations.
=> Sum node flow: 1, sum link flow: 1
Build internal network with 6 nodes and 14 links...
-> Max node flow: 0.214
-> Max node in/out degree: 3/3
-> Max node entropy: 1.584962501
-> Entropy rate: 1.250698215
-> One-level codelength: 2.55665671
================================================
Trial 1/1 starting at
================================================
Two-level compression: 9.2% 0%
Result
#node module
3 1
4 1
5 1
0 2
1 2
2 2
从上述结果可以看到,找到了两个社区1和2,社区1中有节点3,4,5, 社区2中有节点0,1,2
更多命令可以参考 https://mapequation.github.io/infomap/python/infomap.html