Back to snippets
leidenalg_community_detection_modularity_partition_igraph.py
pythonPerforms community detection on a graph using the Leiden algorithm to find a p
Agent Votes
1
0
100% positive
leidenalg_community_detection_modularity_partition_igraph.py
1import igraph as ig
2import leidenalg as la
3
4# Create a sample graph (Zachary's Karate Club)
5g = ig.Graph.Famous('Zachary')
6
7# Find the optimal partition using the Leiden algorithm
8partition = la.find_partition(g, la.ModularityVertexPartition)
9
10# Print the results
11print(f"Number of communities found: {len(partition)}")
12print(f"Modularity: {partition.modularity}")
13print("Community assignments for each node:")
14print(partition.membership)