Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph Theory in Networkx

I am starting to use this interface now, I have some experience with Python but nothing extensive. I am calculating the transitivity and community structure of a small graph:

import networkx as nx

G = nx.read_edgelist(data, delimiter='-', nodetype=str)
nx.transitivity(G)

#find modularity
part = best_partition(G)
modularity(part, G)

I get the transitivity just fine, however - there is the following error with calculating modularity.

NameError: name 'best_partition' is not defined

I just followed the documentation provided by the networkx site, is there something I am doing wrong?

like image 803
Workhorse Avatar asked Jun 17 '14 03:06

Workhorse


2 Answers

As far as I can tell best_partition isn't part of networkx. It looks like you want to use https://sites.google.com/site/findcommunities/ which you can install from https://bitbucket.org/taynaud/python-louvain/src

Once you've installed community try this code:

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

G = nx.random_graphs.powerlaw_cluster_graph(300, 1, .4)
nx.transitivity(G)

#find modularity
part = community.best_partition(G)
mod = community.modularity(part,G)

#plot, color nodes using community structure
values = [part.get(node) for node in G.nodes()]
nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.show()

enter image description here

edit: How I installed the community detection library

ryan@palms ~/D/taynaud-python-louvain-147f09737714> pwd
/home/ryan/Downloads/taynaud-python-louvain-147f09737714
ryan@palms ~/D/taynaud-python-louvain-147f09737714> sudo python3 setup.py install
like image 95
dranxo Avatar answered Oct 04 '22 06:10

dranxo


I just met the same error NameError: name 'best_partition' is not defined when using this example code.

This error occurs because I named my python file as networkx.py, then when we execute this program

import networkx as nx

This program may import the networkx we defined instead of the library. In the program, best_partition is not defined. So this error occur.

Having same name with library is not appropriate. Maybe you should check this!

like image 25
Sinya Peng Avatar answered Oct 04 '22 05:10

Sinya Peng