Betweenness(中介中心度)这个度量很有意思。类似于我们身边那种社交达人,我们认识的不少朋友可能都是通过他/她认识的,这个人起到了中介的作用。
中介中心性指的是一个结点担任其它两个结点之间最短路的桥梁的次数。一个结点充当“中介”的次数越高,它的中介中心度就越大。如果要考虑标准化的问题,可以用一个结点承担最短路桥梁的次数除以所有的路径数量。
其公式可以表述为:
C
b
(
v
i
)
=
∑
s
≠
v
i
≠
t
∈
V
σ
s
t
(
v
i
)
σ
s
t
C_b(v_i)=\sum_{s\not=v_i\not=t\in V} \frac{\sigma_{st}(v_i)}{\sigma_{st}}
Cb(vi)=s=vi=t∈V∑σstσst(vi)
其中:
σ
s
t
\sigma_{st}
σst是结点
v
i
到
v
j
的
最
短
路
径
的
个
数
v_i到v_j的最短路径的个数
vi到vj的最短路径的个数
σ
s
t
(
v
i
)
代
表
v
i
到
v
j
的
最
短
路
径
中
经
过
v
i
的
路
径
个
数
\sigma_{st}(v_i)代表v_i到v_j的最短路径中经过v_i的路径个数
σst(vi)代表vi到vj的最短路径中经过vi的路径个数
代码实现如下:
def getNeighbor(nodes,edges):
#此函数是为了创建图的数据结构,结构为
#{"1":[2,3,4]
#"2":[4]
#"3":[1,2]
#"4":[3]
#}
#key为结点,value为其指向的结点的列表
nodeDict={}
for node in nodes:
neighbor=[]
for edge in edges:
if edge[0]==node:
neighbor.append(edge[1])
nodeDict[node]=neighbor
return nodeDict
def findAllPath(graph,start,end,path=[]):
#获取start到end的所有路径,返回列表,[start,node1,node2,...,end]
path = path +[start]
if start == end:
return [path]
paths = [] #存储所有路径
for node in graph[start]:
if node not in path:
newpaths = findAllPath(graph,node,end,path)
for newpath in newpaths:
paths.append(newpath)
return paths
def getAllShortestPath(nodes,edges):
#获取start到end的所有最短路径
shortestDict={}
graph=getNeighbor(nodes,edges)
for start in nodes:
for end in nodes:
paths=findAllPath(graph,start,end)
if len(paths)>=1:
shortestPath=getAllShortestRow(paths) #找到路径最短的序列对应的行号
shortestDict[str(start)+","+str(end)]=shortestPath #key值为start与end的拼接字符串
return shortestDict
def getAllShortestRow(paths):
#找到start到end的所有路径中,最短的路径
lengthDict={}
count=0
for path in paths:
lengthDict[len(path)]=[]
for path in paths:
lengthDict[len(path)].append(count)
count+=1
lens=list(sorted(lengthDict.keys()))
shortest=[]
for row in lengthDict[lens[0]]:
shortest.append(paths[row])
return shortest
def getBetweenness(node,shortestDict):
#计算Betweenness
sum=0
for k,vs in shortestDict.items():
count=0
for v in vs:
if node in v:
count+=1
sum+=count/len(v)
return sum
def getResult(nodes,edges):
shortestDict=getAllShortestPath(nodes,edges)
resultDict={}
for node in nodes:
resultDict[node]=getBetweenness(node,shortestDict)
return resultDict
if __name__ == "__main__":
vertices = []
edges = []
f=open("BetweennessrResult.txt","w+")
nodeStr=open("./data/nodes.txt").read()
for l in nodeStr.splitlines():
vertices.append(int(l))
edgeStr=open("./data/edges.txt").read()
for l in edgeStr.splitlines():
edges.append((int(l.split(",")[0]),int(l.split(",")[1])))
result=getResult(vertices,edges)
for k,v in result.items():
f.write(str(k)+"\t"+str(v)+"\n")
f.close()
计算结果为:
node数据形式为:
edges数据形式为: