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

2024-04-29 09:19:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个网络,我想用iggraph中的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)

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


Tags: 代码networkxtxt节点plot成员network社区
1条回答
网友
1楼 · 发布于 2024-04-29 09:19:22

您正处在正确的轨道上;可以通过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

相关问题 更多 >