PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] What is the best way to calculate centralities for a single node in networkx?

 June 28, 2022     graph, networkx, node-centrality, python-3.x, sna     No comments   

Issue

I am able to calculate different kinds of centralities such as degree, betweenness, closeness, and eigenvector for all the nodes in graph G. For instance, this code calculates the betweenness centrality for all of the included nodes of graph G:

import networkx as nx
# build up a graph
G = nx.Graph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
G.add_edges_from([('A', 'B'), ('B','C'), ('C', 'D'), ('D', 'E')])
bw_centrality = nx.betweenness_centrality(G, normalized=True)
print (bw_centrality)

For large networks, it is very time consuming to calculate some of the centralities, such as betweenness and closeness. Therefore, I would like to calculate the centrality of only a subset of nodes, instead of calculating all of the nodes' centrality. In the example above, how can I calculate the betweenness of node A, by Networkx library in Python?


Solution

In a graph, I found a solution for calculating the closeness centrality of a single node. But, for betweenness, I have not been able to find a solution. Let's calculate a node's closeness centrality in a graph. Here is how the closeness of all the nodes can be calculated: import networkx as nx

# build up a graph

G = nx.Graph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
G.add_edges_from([('A', 'B'), ('B','C'), ('C', 'D'), ('D', 'E')])
cc_centrality = nx.closeness_centrality(G)

print (cc_centrality )

Therefore, the above code produces the following result:

{'A': 0.4, 'B': 0.5714285714285714, 'C': 0.6666666666666666, 'D': 0.5714285714285714, 'E': 0.4}

In the next step, we will calculate the closeness of node A separately. According to the source code for Neworkx, closeness centrality has the following meaning:

closeness_centrality(G, u=None, distance=None, wf_improved=True)

The graph G shows the defined graph, and u represents the node you want to determine its closeness separately. To calculate the closeness of node A, follow these steps:

nx.closeness_centrality(G, u='A')

The result equals to 0.4. Similarly, nx.closeness_centrality(G, u='B') gives you 0.5714285714285714.



Answered By - Hamed Baziyad
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing