taynaud / python-louvain

Louvain Community Detection
BSD 3-Clause "New" or "Revised" License
964 stars 200 forks source link

Modularity are not the same in the same graph with different node labels #37

Closed zhmh163 closed 4 years ago

zhmh163 commented 5 years ago

Hi, I am confusing that I got different modularity in the same graph with different node labels. First, I got one modularity 0.382 in my network. Then I rename the node labels based on some sorted and I got 0.412. Anyone can tell me the reason? For simplicity, I test the karate club network and find the same problem. Here is an example for my code.

~~~~~~~~~~~~~~~

import community import networkx as nx

G1 = nx.karate_club_graph()

rename nodes id

G2=nx.Graph() index={} id=0 for (i,j) in G1.edges(): if i not in index.keys(): index[i]=id id=id+1 if j not in index.keys(): index[j]=id id=id+1 G2.add_edge(index[i], index[j])

calculate the modularity

partition1 = community.best_partition(G1) Q1 = community.modularity(partition1,G1)

partition2=community.best_partition(G2) Q2 = community.modularity(partition2,G2)

print len(G1),len(G2) print G1.number_of_edges(), G2.number_of_edges() print Q1,Q2

taynaud commented 4 years ago

Hello, When I run your snippet, I get very close modularities on both graph. Louvain method is not strictly deterministic (for instance, iteration order on nodes is important but no order is the correct order). Thus you may get different communities on several run, even on the same graph. I try to analyze this in http://hal.archives-ouvertes.fr/inria-00492058/en/

0.38 and 0.41 seems a rather extreme difference, but I have note manager to reproduce this.