Skip to main content
 首页 » 编程设计

python之如何将边缘属性作为边缘距离传递给 nx.closeness_centrality()

2024年11月01日12sxdcgaq8080

假设我有一个由这个矩阵定义的图:

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) 

接下来,我想计算该图每个节点的加权接近度中心性。

nx.closeness_centrality(test_nx, distance="edges") 

我得到:

{0: 0.6, 1: 0.6, 2: 1.0, 3: 0.6} 

然而,这显然没有考虑边缘权重。我猜原因是我没有正确传递“距离”参数。

根据文档:

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 
 

谁能告诉我如何将边权重传递给这个函数?我想要的输出是一个包含接近度中心值的字典(每个节点一个),它认为这些边具有权重并且它们不仅仅是二元的。

请您参考如下方法:

如果你用这个看边缘:

print(test_nx.edges(data=True)) 
# output: [(0, 2, {'weight': 4}), (1, 2, {'weight': 6}), (2, 3, {'weight': 10})] 

可以看到保存边权重的key是weight。正确的距离键就是这个。

nx.closeness_centrality(test_nx, distance="weight") 
# output {0: 0.10714285714285714, 1: 0.09375, 2: 0.15, 3: 0.075}