3

I am not able to compute centralities for a simple NetworkX weighted graph.
Is it normal or I am rather doing something wrong?

I add edges with a simple add_edge(c[0],c[1],weight = my_values), where c[0],c[1] are strings (names of the nodes) and my_values integers, within a for loop. This is an example of the resulting edges:

('first node label', 'second node label', {'weight': 14})

(the number of nodes does't really matter — for now I keep it to only 20)

The edge list of my graph is a list of tuples, with (string_node1,string_node2,weight_dictionary) - everything looks fine, as I am also able to draw/save/read/ the graph...

Why?:

  • nx.degree_centrality gives me all 1s ?
  • nx.closeness_centrality gives me all 1s ?

example:

{'first node name': 1.0,
...
'last node name': 1.0}

Thanks for your help.

jjrr
  • 1,038
  • 2
  • 13
  • 26
  • If you post a complete (non)working example it will be easier to discover what the problem is. – Aric Jan 28 '17 at 17:05
  • yeah, I understand, but I am a bit scared for the sensibility of the data - names of real people, still alive. I can tell that I just fixed this 'issue' by adding the `weight='weight'` to `nx.clustering` , `nx.degree_assortativity_coefficient` and `nx.betweenness_centrality` ...that's why I am wondering if I can really get the _weighted degree_ with the implemented functions...probably I have to define my own, in order to compute the weighted degree...even if this seems a bit weird to me – jjrr Jan 28 '17 at 17:27

3 Answers3

4

It was easy:

instead of using nx.degree_centrality() I use my_graph.degree(weight='weight') - still I think this is a basic lack in the module...

...but, the issue is still open for nx.closeness_centrality

jjrr
  • 1,038
  • 2
  • 13
  • 26
4

For making closeness_centrality consider weight, you have to add a distance attribute of 1 / weight to graph edges, as suggested in this issue.

Here's code to do it (graph is g):

g_distance_dict = {(e1, e2): 1 / weight for e1, e2, weight in g.edges(data='weight')}
nx.set_edge_attributes(g, g_distance_dict, 'distance')
fjsj
  • 10,995
  • 11
  • 41
  • 57
2

I know this is a pretty old question, but just wanted to point out that the reason why your degree centrality values are all 1 is probably because your graph is complete (i.e., all nodes are connected to every other node), and degree centrality refers to the proportion of nodes in the graph to which a node is connected.

Per networkx's documentation:

The degree centrality for a node v is the fraction of nodes it is connected to.

The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1 where n is the number of nodes in G.

Community
  • 1
  • 1
gusjc
  • 21
  • 3