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

时间:2014-08-11 23:47:20

标签: python igraph hierarchical-clustering

我想在iGraph中使用edge_betweenness社区检测算法分析一个网络。我对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

iGraph代码

import igraph

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

# plot graph
igraph.plot(g)

igraph.plot(g)

# identify communities
communities = igraph.community_edge_betweenness()

# not really sure what to do next
num_communities = communities.optimal_count
communities.as_clustering(num_communities)

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

1 个答案:

答案 0 :(得分: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

现在我们可以开始将成员资格向量和节点名称一起写入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])

如果您使用的是Python 3,请使用zip代替izip,而无需导入itertools