介数中心性快速计算

  1. 直接调用networkx
    2001年brandes提出的算法”A faster algorithm for betweenness centrality”
    networkx计算网络的介数中心性
import networkx as nx
G=nx.DiGraph()   # 有向图
# score = nx.betweenness_centrality(G)
# b = nx.betweenness_centrality(G)
for v in G.nodes():
	# print("%0.2d %5.3f" % (v, b[v]))
	print(v)
  1. 2001年brandes提出算法 : A faster algorithm for betweenness centrality
import networkx as nx
from queue import Queue
G = nx.read_gml("dodepend_10_t1.gml") 
algorithm from networkx 
C = nx.centrality.betweenness_centrality(G,normalized=False)

CB = dict.fromkeys(G,0.0)
for s in G.nodes():
	Pred = {w:[] for  w in G.nodes()}
	dist = dict.fromkeys(G,None)
	sigma = dict.fromkeys(G,0.0)
	dist[s] = 0
	sigma[s] = 1
	Q = Queue()
	Q.put(s)
	S = []
	while not Q.empty():
		v = Q.get()
		S.append(v)
		for w in G.neighbors(v):
			if dist[w] == None:
				dist[w] = dist[v] + 1
				Q.put(w)
			if dist[w] == dist[v] + 1:
				sigma[w] += sigma[v]
				Pred[w].append(v)
	delta = dict.fromkeys(G,0.0)
	for w in S[::-1]:
		for v in Pred[w]:
			delta[v] += sigma[v]/sigma[w]*(1+delta[w])
		if w != s:
			CB[w] += delta[w]
for v in CB:
	CB[v] /= 2.0

compare with networkx's implements 
print(sum(abs(CB[v]-C[v]) for v in G)) 

for v in G:
	print(v)
	print(abs(CB[v]-C[v]))
无向图(验证与networkx结果相差28倍)

 posted on 2021-05-30 18:42  My_serendipity  阅读(684)  评论(0编辑  收藏  举报