如何使用Python Networkx计算N次迭代后的命中率(权限和中心)分数

2024-09-29 21:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在使用PythonNetworkX的N次迭代之后找到命中率(权威和中心)

示例-

import networkx as nx
G1 = nx.DiGraph()
G1.add_edges_from([('A', 'B'),
                   ('A','C'),
                   ('D','C'),
                   ('D', 'C'),
                   ('C', 'A'),
                   ('B','C')
                  ])

#nx.draw_networkx(G1,arrows=True,pos=nx.spring_layout(G1))

对于int迭代,我得到以下错误。如何修复它

nx.hits(G1, max_iter=5)

NetworkXError: HITS: power iteration failed to converge in 5 iterations.


Tags: fromimportnetworkxadd示例as中心nx
1条回答
网友
1楼 · 发布于 2024-09-29 21:40:01

max_iter参数仅控制幂次迭代的最大迭代次数。您希望中止迭代并获得当前结果。为此,您可以轻松地修改^{}的现有实现:

import networkx as nx


def hits(graph, iterations, tolarance=1.0e-8):
    hubs = dict.fromkeys(graph, 1.0 / graph.number_of_nodes())
    authorities = {}
    # power iteration, which stops after given iterations or reaching tolerance
    for _ in range(iterations):
        last_hubs = hubs
        hubs = dict.fromkeys(last_hubs.keys(), 0)
        authorities = dict.fromkeys(last_hubs.keys(), 0)
        for node in hubs:
            for neighbor in graph[node]:
                authorities[neighbor] += last_hubs[node] * graph[node][neighbor].get('weight', 1)
        for node in hubs:
            for neighbor in graph[node]:
                hubs[node] += authorities[neighbor] * graph[node][neighbor].get('weight', 1)
        scaling = 1.0 / max(hubs.values())
        for node in hubs:
            hubs[node] *= scaling
        scaling = 1.0 / max(authorities.values())
        for node in authorities:
            authorities[node] *= scaling
        err = sum([abs(hubs[node] - last_hubs[node]) for node in hubs])
        if err < tolarance:
            break
    return hubs, authorities


G1 = nx.DiGraph()
G1.add_edges_from([('A', 'B'),
                   ('A', 'C'),
                   ('D', 'C'),
                   ('D', 'C'),
                   ('C', 'A'),
                   ('B', 'C')
                   ])

print(hits(G1, 5))
# ({'A': 1.0, 'B': 0.7071428571428572, 'C': 0.0017857142857142852, 'D': 0.7071428571428572}, {'A': 0.0025252525252525246, 'B': 0.4141414141414141, 'C': 1.0, 'D': 0.0})

相关问题 更多 >

    热门问题