closeness centrality:某个节点到达其他节点的难易程度,也就是到其他所有结点距离的平均值的倒数。
公式:
例题及实现 :
from igraph import Graph as IGraph f = open('/Users/tangweize/Desktop/net.data') edges = [] for line in f.readlines(): u, v = [i for i in line.strip().split(',')] edges.append((u, v)) print(edges) ''''[('1', '2'), ('1', '3'), ('2', '3'), ('3', '7'), ('4', '5'), ('4', '6'), ('5', '6'), ('6', '7'), ('7', '8'), ('8', '9'), ('9', '10'), ('9', '11'), ('10', '11'), ('8', '12'), ('12', '13'), ('12', '14'), ('13', '14')]''' f.close() g = IGraph.TupleList(edges, directed=False, vertex_name_attr='name') path = g.get_shortest_paths("7") names = g.vs['name'] cc = 0; for p in path: cc += len(p) + 1 print("closeness centrality = ", (len(path)-1)/float(cc))
或者直接调用igraph里面的closeness
from igraph import Graph as IGraph f = open('/Users/tangweize/Desktop/net.data') edges = [] for line in f.readlines(): u, v = [i for i in line.strip().split(',')] edges.append((u, v)) print(edges) ''''[('1', '2'), ('1', '3'), ('2', '3'), ('3', '7'), ('4', '5'), ('4', '6'), ('5', '6'), ('6', '7'), ('7', '8'), ('8', '9'), ('9', '10'), ('9', '11'), ('10', '11'), ('8', '12'), ('12', '13'), ('12', '14'), ('13', '14')]''' f.close() g = IGraph.TupleList(edges, directed=False, vertex_name_attr='name') ccvs = [] for p in zip(g.vs, g.closeness()): ccvs.append({"name" :p[0]["name"], "cc":p[1]}) sorted(ccvs, lambda k:k["cc"], reversed = True)[:10]