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

基于邻接矩阵计算Degree Centrality与Clustering Coefficient方法咨询

问题核心错误排查

  1. 二值化逻辑完全反转:你当前的二值化函数中,df.where(brain_mask, 1.0)的逻辑是「满足距离≤阈值的位置保留原始距离值,不满足的位置设为1」,和需求完全相反,这是你平均度远高于论文范围的核心原因。
  2. 度中心性计算缺少括号:你写的matrix_cerebellum['K']/matrix_cerebellum.shape[0]-1运算顺序是(K/n) -1,而非要求的K/(n-1),这是得到负中心度的直接原因。
  3. 未排除自环干扰:邻接矩阵对角线(节点和自身的连接)默认应该为0,否则计算度的时候会多算自环连接。

正确实现代码

步骤1:修正二值化函数

import numpy as np
import pandas as pd

def binarize_matrix(df, mind=False, cosmos=False):
    if mind:
        brain_Llink = 16.0 # microns
        # 距离小于等于阈值设为1,否则为0
        df = (df <= brain_Llink).astype(float)
    if cosmos:
        cosmos_Llink = 1.2 # mpc
        df = (df <= cosmos_Llink).astype(float)
    # 强制对角线为0,排除自环
    np.fill_diagonal(df.values, 0)
    # 可选:确保矩阵无向,不对称的话取对称值
    df = df.where(df == df.T, 1.0)
    return df

重新执行二值化流程后,可以先打印matrix_cerebellum.sum().mean()查看平均度,此时应该符合论文给出的1.9~3.7范围。

步骤2:计算度中心性

# 先删除之前计算的错误列,避免干扰
matrix_cerebellum = matrix_cerebellum.drop(columns=['K', 'centrality'], errors='ignore')
# 计算每个节点的度
K = matrix_cerebellum.sum(axis=1)
# 总节点数
n = matrix_cerebellum.shape[0]
# 正确计算度中心性
matrix_cerebellum['K'] = K
matrix_cerebellum['degree_centrality'] = K / (n - 1)

步骤3:计算聚类系数

有两种实现方式,可按需选择:

手动实现(适合理解原理)
def calculate_clustering_coeff(adj_matrix, K):
    n = adj_matrix.shape[0]
    clustering = np.zeros(n)
    for j in range(n):
        k_j = K.iloc[j]
        # 度小于2的节点没有足够的邻居,聚类系数为0
        if k_j < 2:
            clustering[j] = 0.0
            continue
        # 取j节点的所有邻居节点
        neighbors = adj_matrix.columns[adj_matrix.iloc[j] == 1]
        # 提取邻居之间的子邻接矩阵,求和后除以2(无向矩阵对称,每个连接会被统计两次)
        sub_adj = adj_matrix.loc[neighbors, neighbors]
        y_j = sub_adj.sum().sum() / 2
        # 套用公式
        clustering[j] = 2 * y_j / (k_j * (k_j - 1))
    return clustering

matrix_cerebellum['clustering_coeff'] = calculate_clustering_coeff(matrix_cerebellum, K)
调用networkx库实现(更高效,适合大矩阵)
import networkx as nx

# 把DataFrame邻接矩阵转成无向图
G = nx.from_pandas_adjacency(matrix_cerebellum)
# 直接调用库函数计算两个指标
degree_centrality = nx.degree_centrality(G)
clustering_coeff = nx.clustering(G)

# 把结果存回原DataFrame
matrix_cerebellum['degree_centrality'] = pd.Series(degree_centrality)
matrix_cerebellum['clustering_coeff'] = pd.Series(clustering_coeff)

内容的提问来源于stack exchange,提问作者8-Bit Borges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:15:05