How to use the communities module "python-louvain" in networkx 2.2?

Viewed 14912

I used to use this module like this:

import community

if __name__ == '__main__':

    G = nx.karate_club_graph()
    pos = nx.spring_layout(G)

    partition = community.best_partition(G)

I installed the correct module:

sudo pip3 install python-louvain

I get this error:

AttributeError: module 'community' has no attribute 'best_partition'

As far as I know it follows the documentation presented here.

7 Answers

I am a beginner in using Networkx as well but I used following syntax in Jupyter notebook and it worked fine for me.

!pip install python-louvain
from community import community_louvain
communities =community_louvain.best_partition(G)

Kind Regards,

You need the package named python-louvain from here.

!pip install python-louvain

import networkx as nx
import community
import numpy as np
np.random.seed(0)

W = np.random.rand(15,15)
np.fill_diagonal(W,0.0)

G = nx.from_numpy_array(W)
louvain_partition = community.best_partition(G, weight='weight')
modularity2 = community.modularity(louvain_partition, G, weight='weight')
print("The modularity Q based on networkx is {}".format(modularity2))

The modularity Q based on networkx is 0.0849022950503318

I am not sure why the following situation exists, but there appears to be another package called "community" that does not contain the function "community.best_partition". As stated above, you want the "python-louvain" package, which appears to include a "community" part?! In PyCharm 2020.3, under Preferences -> Project: Python Interpreter, I deleted the "community" package and added the "python-louvain" package. After that, "import community" still worked as did "community.best_partition".

you should install the package below. i use it and it works. i install it in windows.
https://pypi.org/project/python-louvain/

write "pip install python-louvain" in cmd and after that write program like this:

import community
import networkx as nx
import matplotlib.pyplot as plt

G = nx.erdos_renyi_graph(30, 0.05)
partition = community.best_partition(G)
size = float(len(set(partition.values())))
pos = nx.spring_layout(G)
count = 0
for com in set(partition.values()) :
    count = count + 1
    list_nodes = [nodes for nodes in partition.keys()if partition[nodes] == com]
    nx.draw_networkx_nodes(G, pos, list_nodes, node_size = 20,node_color = str(count / size))

nx.draw_networkx_edges(G, pos, alpha=0.5)
plt.show()

i use python 3.7

For what it's worth: I had to

pip uninstall community

then

pip install python-louvain

then

pip install networkx

in order to get my conda py37 environment to work correctly and to be able to call community.best_partition() without an attribute error.

I think, if you have networkx installed before python-louvain, it will claim the namespace for community and not allow you to run what you want.

Related