在python中使用iGraph进行社区检测,并将每个节点的社区编号写入CSV

Cur*_*tLH 12 python hierarchical-clustering igraph

我有一个网络,我想使用edge_betweennessiGraph中的社区检测算法进行分析.我对NetworkX很熟悉,但我正在尝试学习iGraph,因为它是基于NetworkX的其他社区检测方法.

我的最终目标是运行edge_betweenness社区检测并找到最佳社区数,并为图中的每个节点编写具有社区成员资格的CSV.

以下是我目前的代码.任何帮助计算社区成员资格的人都非常感谢.

输入数据('network.txt'):

1 2
2 3
2 7
3 1
4 2
4 6
5 4
5 6
7 4
7 8
8 9
9 7
10 7
10 8
10 9
Run Code Online (Sandbox Code Playgroud)

iGraph代码

import igraph

# load data into a graph
g = igraph.Graph.Read_Ncol('network.txt')

# plot graph
igraph.plot(g)
Run Code Online (Sandbox Code Playgroud)

igraph.plot(克)

# identify communities
communities = igraph.community_edge_betweenness()

# not really sure what to do next
num_communities = communities.optimal_count
communities.as_clustering(num_communities)
Run Code Online (Sandbox Code Playgroud)

我需要做些什么才能找到最佳社区数量并写下图表中每个节点属于列表的社区?

Tam*_*más 19

你走在正确的轨道上; 最佳社区数量(其中"最优"被定义为"最大化模块化得分的社区数量")可以通过检索得到communities.optimal_count,并且社区结构可以转换为使用的平面不相交聚类communities.as_clustering(num_communities).实际上,社区的数量可以是如果它恰好等于,则省略communities.optimal_count.一旦你完成了这个,就会得到一个VertexClustering带有membership属性的对象,它为你提供图中每个顶点的聚类索引.

为了清楚起见,我将您的communities变量重命名为,dendrogram因为边缘中介社区检测算法实际上产生了树形图::

# calculate dendrogram
dendrogram = graph.community_edge_betweenness()
# convert it into a flat clustering
clusters = dendrogram.as_clustering()
# get the membership vector
membership = clusters.membership
Run Code Online (Sandbox Code Playgroud)

现在我们可以开始将成员资格向量与节点名称一起写入CSV文件::

import csv
from itertools import izip

writer = csv.writer(open("output.csv", "wb"))
for name, membership in izip(graph.vs["name"], membership):
    writer.writerow([name, membership])
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Python 3,请使用zip而不是izip导入而不需要导入itertools.