Reputation: 490
Suppose I have a graph defined by this matrix:
test = np.array([[0, 0, 4, 0],
[0, 0, 6, 0],
[4, 6, 0, 10],
[0, 0, 10, 0]])
import networkx as nx
test_nx = nx.from_numpy_array(test)
Next, I'd like to compute the weighted closeness centrality for each node of this graph.
nx.closeness_centrality(test_nx, distance="edges")
I get:
{0: 0.6, 1: 0.6, 2: 1.0, 3: 0.6}
However, this is clearly not considering edge weights. I'm guessing the reason is I'm not passing the "distance" argument properly.
According to the docs:
closeness_centrality(G, u=None, distance=None, normalized=True)
distance (edge attribute key, optional (default=None)) – Use the
specified edge attribute as the edge distance in shortest path
calculations
Can anyone advise me how to pass edge weights to this function? My desired output would be a dictionary of closeness centrality values (one per node) which considers that these edges have weights and they are not simply binary.
Upvotes: 2
Views: 506
Reputation: 389
If you look at the edges using this:
print(test_nx.edges(data=True))
# output: [(0, 2, {'weight': 4}), (1, 2, {'weight': 6}), (2, 3, {'weight': 10})]
you can see that the key used to save the edge weight is weight
. The right distance key will be this one.
nx.closeness_centrality(test_nx, distance="weight")
# output {0: 0.10714285714285714, 1: 0.09375, 2: 0.15, 3: 0.075}
Upvotes: 1