您的位置:首页 > 其它

networkx使用笔记(五)之实战篇--参数测量

2012-10-05 18:44 405 查看

1. 自有测量函数

networkx中提供一些对网络的参数测量基本函数,包括获知网络节点数目(G.number_of_nodes())、网络的边数目(G.number_of_edges())、获取网络节点列表(G.nodes())和获取网络边列表(G.edges())。获取节点的度,G.degree(node_id);如果是有向图,可以是入度或出度,G.in_degree(node_id)。

还有对网络一些基本的测量,包括连通分量数目(nx.number_connect_components(G))、获取连通分量的节点列表(nx.connected_components(G),包含每个连通图的节点列表)、获取连通分量(nx.connected_component_subgraphs(G),返回的是列表,但是元素是图,这些分量按照节点数目从大到小排列,所以第一个就是最大的连通分量)。上述三个都是关于无向图的连通分量。

在有向图中有强连通分量的概念,获取强连通分量数目(nx.number_strongly_connected_components(G))、最大的强连通分量(nx.strongly_connected_component_subgraphs(G)[0])。

此外,还能测量网络直径的nx.diameter(G),注意这里的直径只能对连通的无向图操作。networkx中对有向图限制较多,例如非连通的无向图无法测量直径、有向图无法测量直径(只能先转换为无向图)、无法计算有向图中的聚类系数等。

2. 网络有效直径

网络直径并不能较好刻画网络特征,一般用有效直径衡量,有效直径指的是在该d下,90%以上的节点都是连通的。本人进行粗略的实现。这里假设,传入的无向图G,将所有节点之间的最短距离计算出来,然后从小到大排列并进行遍历,每个最短距离后有其出现的概率,当最短距离的累计概率超过0.9,即超过90%的节点对之间其距离在该范围内,认为是有效直径。但是这个计算结果和一些给出的结果有出入。

def network_effective_diameter(G=nx.Graph()):
H=nx.connected_component_subgraphs(G)[0]
shortest={}
for node in H.nodes():
'''通过函数计算连通节点之间的最短距离'''
length=nx.single_source_shortest_path_length(H, node)
values=length.values()
for value in values:
if shortest.has_key(value):
shortest[value]=shortest[value]+1
elif not shortest.has_key(value):
shortest[value]=1
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test')
cursor=conn.cursor()
cursor.execute('truncate diameter_tmp')
conn.commit()
for item in shortest.items():
cursor.execute('insert into diameter_tmp values (%s,%s)',[item[0],item[1]])
conn.commit()
effective=0
cursor.execute('select * from diameter_tmp order by shortest')
results=cursor.fetchall()
freq=[]
i=0
print int(0.9*G.number_of_nodes()*G.number_of_nodes())
while i<len(results):
effective=results[i][0]
freq.append(results[i][1])
print effective,sum(freq)
if sum(freq)>int(0.9*G.number_of_nodes()*(G.number_of_nodes()-1)):
break
i=i+1
conn.close()
print 'Compute the effective diameter!', effective
return effective
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: