networkX-03-连通度、全局网络效率、局部网络效率、聚类系数计算

本文详细介绍了如何在Python中使用NetworkX库计算网络的连通度(包括无向图和有向图的连通性),全局和局部效率,以及聚类系数。通过实例展示了如何检查图的连通状态,计算效率,并提供了源码分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


教程仓库地址:github networkx_tutorial
本文从指标公式出发,计算网络的连通度、全局效率、局部效率、聚类系数,有需要的同学可在仓库下载ipynb文件进行练习.

1.连通度

  • 文字部分来自GPT-4

import networkx as nx
import matplotlib. pyplot as plt
# 创建一个无向图
G = nx.Graph()
# 添加边
G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])
# # 绘制图形
nx.draw(G,node_size=500,with_labels=True)


png

1.1 检查图是否连通

# 检查图是否连通
is_connected = nx.is_connected(G)
print(f"The graph is connected: {is_connected}")
The graph is connected: True

1.2 检查有向图是否为强连通

# 创建一个有向图
DG = nx.DiGraph()
DG.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)])
nx.draw(DG,node_size=500,with_labels=True)


png

# 检查图是否强连通
is_strongly_connected = nx.is_strongly_connected(DG)
print(f"The directed graph is strongly connected: {is_strongly_connected}")
The directed graph is strongly connected: True

1.3 点连通度、边连通度:

# 计算点连通度
node_connectivity = nx.node_connectivity(G)
print("节点连通度:", node_connectivity)
# 计算边连通度
edge_connectivity = nx.edge_connectivity(G)
print("边连通度:", edge_connectivity)
节点连通度: 2
边连通度: 2

2.网络效率

2.1全局效率

# 创建一个简单的无向图
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4)])

# 绘制图形
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=500, font_size=16, font_weight='bold')
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, font_size=12, font_color='red')
plt.show()


png

#计算指定节点对之间的效率:节点之间最短路径的倒数
nx.efficiency(G,2,4)  # 2,4 之间的最短路径长度为2,则两节点之间的效率为1/2
0.5
# 全局网络效率官方函数
nx.global_efficiency(G)
0.8333333333333334
# 源码
def global_effi(G):
    n = len(G)
    denom =  n * (n - 1)
    if denom != 0:
        lengths = nx.all_pairs_dijkstra_path_length(G)
        g_eff = 0
        for source, targets in lengths:
            for target, distance in targets.items():
                if distance > 0:
                    g_eff += 1 / distance
        g_eff /= denom
        # g_eff = sum(1 / d for s, tgts in lengths
        #                   for t, d in tgts.items() if d > 0) / denom
    else:
        g_eff = 0
    # path lengths in parallel.
    return g_eff

global_effi(G=G)
0.8333333333333334

2.2 局部效率

2.2.1 查找子图

# 定义要查找的节点子集
node_subset = [1, 2, 3]
# 查找诱导子图
induced_subgraph = G.subgraph(node_subset)
nx.draw(induced_subgraph,with_labels = True)


png

# 查找生成子图
spanning_subgraph = G.subgraph(G.nodes())
nx.draw(spanning_subgraph,with_labels = True)


png

2.2.3 局部效率源码分析

nx.local_efficiency(G) 
0.5833333333333334
# 源码
sum = 0  # 初始化 ,所有节点和其构成的子图 ,对应的全局效率的值
len(G)  # G的节点数

for v in G:  # 遍历每个节点
    print('---{}节点的子图是----'.format(v))
    # 找到每个节点的和其邻居构成的子图
    # fig,ax = plt.subplots()
    # nx.draw(G.subgraph(G[v]),with_labels = True,ax=ax)
    g_effi = nx.global_efficiency(G.subgraph(G[v]))
    print('邻居节点{}全局效率为:{}'.format(v,g_effi))
    sum = sum+ g_effi
    
print("local_efficiency",sum/len(G))  #0.9166666666666667
     
---1节点的子图是----
邻居节点1全局效率为:1.0
---2节点的子图是----
邻居节点2全局效率为:1.0
---3节点的子图是----
邻居节点3全局效率为:0.3333333333333333
---4节点的子图是----
邻居节点4全局效率为:0
local_efficiency 0.5833333333333334

3.聚类系数(Clustering Coefficient)


3.1 聚类系统源码分析

# 官方函数
for node in G.nodes():
    c = nx.clustering(G = G,nodes=node)
    print(f"节点 {node} 的聚类系数为 {c}")
节点 1 的聚类系数为 1.0
节点 2 的聚类系数为 1.0
节点 3 的聚类系数为 0.3333333333333333
节点 4 的聚类系数为 0
# 1. 计算节点的k ,ki:
# test_node : 3 
node = 3
# 邻居
neighbors = list(G.neighbors(node))
# 度
k = len(neighbors)
k  # 节点3对应的k为3
3
# 2. ei的计算
neighbors
for i in range(k):
    for j in range(i + 1, k):
        if G.has_edge(neighbors[i], neighbors[j]):
            # print(neighbors[i], neighbors[j])
            triplets += 1
triplets # 节点3对应的ei为3
2

节点的聚类系数

# 计算每个节点的聚类系数
for node in G.nodes():
    # 获取节点的邻居节点
    neighbors = list(G.neighbors(node))
    k = len(neighbors)
    if k < 2:
        # 如果邻居节点数少于 2,聚类系数为 0
        clustering = 0
    else:
        # 计算节点的三元组数量
        triplets = 0
        for i in range(k):
            for j in range(i + 1, k):
                if G.has_edge(neighbors[i], neighbors[j]):
                    triplets += 1
        # 计算聚类系数
        clustering = 2 * triplets / (k * (k - 1))
    print(f"节点 {node} 的聚类系数为 {clustering}")
节点 1 的聚类系数为 1.0
节点 2 的聚类系数为 1.0
节点 3 的聚类系数为 0.3333333333333333
节点 4 的聚类系数为 0

整个网络的聚类系数C

nx.average_clustering(G=G)
0.5833333333333334
### 使用 NetworkX 计算网络效率、自然连通度和最大子图连通度 #### 网络效率 (Network Efficiency) 网络效率衡量的是在一个网络中任意两个节点之间的平均最短路径长度的倒数。对于一个给定的无向图 \( G \),其全局效率定义如下: \[ E(G) = \frac{1}{n(n-1)}\sum_{i \neq j} \frac{1}{d(i,j)} \] 其中 \( n \) 是节点的数量,\( d(i,j) \) 表示节点 i 和 j 间的距离。 为了计算整个网络效率,在 Python 中可以利用 `networkx` 库来实现这一功能[^2]。 ```python import networkx as nx def global_efficiency(G): N = len(G.nodes()) if N < 2: return float('nan') efficiency_sum = sum(1 / shortest_path_length for u, v, shortest_path_length in nx.all_pairs_shortest_path_length(G).items() if u != v) return efficiency_sum / (N * (N - 1)) G = nx.Graph() # Add nodes and edges to graph here... efficiency = global_efficiency(G) print(f"The Global Efficiency of the Graph is {efficiency}") ``` #### 自然连通度 (Natural Connectivity) 自然连通度是一种评估复杂系统的鲁棒性的指标,它反映了当移除某些组件时系统保持连接的能力。可以通过下面的方式计算: \[ \eta(G)=\lim _{\varepsilon \rightarrow 0}\left[\int_{-\infty }^{+\infty }\ln (\lambda )p(\lambda ,\varepsilon )d\lambda +\gamma \right], \] 这里 \( p(\lambda,\epsilon) \) 是特征多项式的密度函数,而 γ ≈ 0.5772156649 是欧拉常数。然而,实际应用中通常采用近似方法来进行估算。在 `networkx` 中并没有直接提供此属性的方法,但是可以通过第三方库如 `numpy.linalg.eigvals()` 来获取谱信息并进一步处理得到结果。 ```python import numpy as np def approximate_natural_connectivity(G): eigenvalues = sorted(np.real(nx.adjacency_spectrum(G)), reverse=True) harmonic_mean_of_eigenvalues = sum([1/value for value in eigenvalues]) / len(eigenvalues) return harmonic_mean_of_eigenvalues natural_conn = approximate_natural_connectivity(G) print(f"Approximate Natural Connectivity: {natural_conn}") ``` #### 最大子图连通度 (Largest Connected Subgraph Metric) 要找到最大的连通分量,可以直接调用 `networkx.connected_components()` 函数,并选取大小最大的那个作为目标对象;如果关注的是强连通分支,则应考虑使用 `strongly_connected_components()` 方法针对有向图的情况[^1]。 ```python largest_cc = max(nx.connected_components(G), key=len) subgraph = G.subgraph(largest_cc).copy() if isinstance(G, nx.DiGraph): # 如果是有向图则寻找最强连通部分 largest_scc = max(nx.strongly_connected_components(G), key=len) subgraph = G.subgraph(largest_scc).copy() density = nx.density(subgraph) print(f"Density within Largest Component/Subgraph: {density}") ``` 上述代码片段展示了如何通过 `networkx` 实现这些重要的拓扑特性分析工具。值得注意的是,具体的实现细节可能会随着版本更新有所变化,请参照官方文档获得最新指导。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值