gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:59:28 25 4
gpt4 key购买 nike

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

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}

关于python - 如何将边缘属性作为边缘距离传递给 nx.closeness_centrality()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com