You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现有向网络的全局聚类系数?寻求解决方案

有向网络全局聚类系数的Python实现方案

一、自定义实现(基于NetworkX)

有向网络的全局聚类系数没有统一标准定义,最常用的两种计算逻辑如下:

  • 传递性三元组定义:统计所有满足A→B、B→C且A→C的闭合三元组数量,除以所有可能的有序三元组((A,B,C)中A≠B≠C的组合)总数。
  • 循环三元组定义:统计满足A→B、B→C且C→A的循环闭合三元组数量,除以对应的可能三元组总数。

以下是基于传递性三元组定义的实现代码:

import networkx as nx

def directed_global_clustering(G):
    """计算有向网络的全局聚类系数(传递性三元组定义)"""
    if not nx.is_directed(G):
        raise ValueError("输入必须是有向图")
    
    total_closed = 0
    total_possible = 0
    
    for node in G.nodes():
        out_neighbors = set(G.successors(node))
        out_degree = len(out_neighbors)
        if out_degree < 2:
            continue
        # 统计当前节点出邻居间的所有可能有序对数量
        possible = out_degree * (out_degree - 1)
        total_possible += possible
        # 统计实际存在的传递性闭合三元组数量
        closed = 0
        for neighbor in out_neighbors:
            closed += len(out_neighbors & set(G.successors(neighbor)))
        total_closed += closed
    
    return total_closed / total_possible if total_possible > 0 else 0.0

使用示例:

# 创建有向图示例
G = nx.DiGraph()
G.add_edges_from([(1,2), (2,3), (1,3), (3,4), (4,3)])
print(directed_global_clustering(G))

若需要基于循环三元组定义,只需修改统计逻辑:遍历节点出邻居,检查是否存在邻居指向当前节点的边且邻居间有指向关系,可根据需求调整代码。

二、使用igraph库直接计算

igraph库对有向网络的聚类系数支持更完善,内置多种计算逻辑。

先安装igraph:

pip install python-igraph

调用内置方法计算:

from igraph import Graph

# 创建有向图
g = Graph(directed=True)
g.add_vertices(4)
g.add_edges([(0,1), (1,2), (0,2), (2,3), (3,2)])

# 按有向传递性三元组计算全局聚类系数
global_clust = g.transitivity(mode="directed")
print(global_clust)

igraph的transitivity方法支持多种mode参数:

  • mode="directed":按有向传递性三元组计算
  • mode="undirected":将有向图视为无向图计算
  • mode="total":同时统计所有类型的有向闭合三元组

内容的提问来源于stack exchange,提问作者Elh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:35:16