Using iGraph in python for community detection and writing community number for each node to CSV

前端 未结 1 1114
青春惊慌失措
青春惊慌失措 2021-02-05 17:09

I have an network that I would like to analyze using the edge_betweenness community detection algorithm in iGraph. I\'m familiar with NetworkX, but am trying to le

相关标签:
1条回答
  • 2021-02-05 18:05

    You are on the right track; the optimal number of communities (where "optimal" is defined as "the number of communities that maximizes the modularity score) can be retrieved by communities.optimal_count and the community structure can be converted into a flat disjoint clustering using communities.as_clustering(num_communities). Actually, the number of communities can be omitted if it happens to be equal to communities.optimal_count. Once you've done that, you get a VertexClustering object with a membership property which gives you the cluster index for each vertex in the graph.

    For sake of clarity, I'm renaming your communities variable to dendrogram because the edge betweenness community detection algorithm actually produces a 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
    

    Now we can start writing the membership vector along with the node names into a CSV file::

    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])
    

    If you are using Python 3, use zip instead of izip and there is no need to import itertools.

    0 讨论(0)
提交回复
热议问题