Python案例如何用Networkx做同配性分析

wen python案例 1

本文目录导读:

Python案例如何用Networkx做同配性分析

  1. 基础同配性分析
  2. 高级同配性分析
  3. 实际应用案例
  4. 可视化同配性
  5. 统计显著性检验

我来详细介绍如何使用NetworkX进行同配性分析(Assortativity Analysis)。

基础同配性分析

节点度同配性

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
# 创建示例图
G = nx.karate_club_graph()  # 使用空手道俱乐部图
# 计算度同配性系数
assortativity_degree = nx.degree_assortativity_coefficient(G)
print(f"度同配性系数: {assortativity_degree:.4f}")
# 解释:
# 正值:高度节点倾向于连接高度节点(同配)
# 负值:高度节点倾向于连接低度节点(异配)
# 接近0:无明显模式

多重属性同配性

# 计算其他属性的同配性
# 1. 数值属性同配性
G = nx.karate_club_graph()
# 添加数值属性
for node in G.nodes():
    G.nodes[node]['age'] = np.random.randint(20, 60)
assortativity_age = nx.numeric_assortativity_coefficient(G, 'age')
print(f"年龄同配性: {assortativity_age:.4f}")
# 2. 类别属性同配性
# 添加类别属性
for node in G.nodes():
    G.nodes[node]['club'] = 'Officer' if node < 20 else 'Mr. Hi'
assortativity_club = nx.attribute_assortativity_coefficient(G, 'club')
print(f"俱乐部同配性: {assortativity_club:.4f}")

高级同配性分析

混合矩阵分析

import pandas as pd
def analyze_assortativity_matrix(G, attribute):
    """分析同配性混合矩阵"""
    # 获取混合矩阵
    M = nx.attribute_mixing_matrix(G, attribute)
    # 创建可读的DataFrame
    nodes_attr = nx.get_node_attributes(G, attribute)
    unique_attrs = sorted(set(nodes_attr.values()))
    df = pd.DataFrame(M, index=unique_attrs, columns=unique_attrs)
    print("混合矩阵:")
    print(df)
    return df
# 使用示例
G = nx.karate_club_graph()
# 添加社区标签作为属性
communities = nx.community.greedy_modularity_communities(G)
for i, comm in enumerate(communities):
    for node in comm:
        G.nodes[node]['community'] = f'Community_{i}'
matrix_df = analyze_assortativity_matrix(G, 'community')

度-度相关性分析

def analyze_degree_correlation(G):
    """分析度-度相关性"""
    # 计算每个节点对的度
    degrees = dict(G.degree())
    # 收集边两端的度
    degree_pairs = []
    for u, v in G.edges():
        degree_pairs.append((degrees[u], degrees[v]))
    # 转换为numpy数组
    degree_pairs = np.array(degree_pairs)
    # 计算平均邻居度
    avg_neighbor_degree = nx.average_neighbor_degree(G)
    return degree_pairs, avg_neighbor_degree
# 使用示例
degree_pairs, avg_neighbor_degree = analyze_degree_correlation(G)
# 可视化度-度相关性
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.scatter(degree_pairs[:, 0], degree_pairs[:, 1], alpha=0.5)
plt.xlabel('节点度')
plt.ylabel('邻居节点度')'度-度相关性散点图')
plt.plot([0, max(degree_pairs.flatten())], 
         [0, max(degree_pairs.flatten())], 'r--', alpha=0.5)
plt.subplot(1, 2, 2)
degrees_list = sorted(avg_neighbor_degree.keys())
knn_values = [avg_neighbor_degree[k] for k in degrees_list]
plt.plot(degrees_list, knn_values, 'o-')
plt.xlabel('节点度 k')
plt.ylabel('平均邻居度 <knn>')'平均邻居度 vs 节点度')
plt.tight_layout()
plt.show()

实际应用案例

社交网络分析

def social_network_assortativity_analysis(G):
    """社交网络同配性综合分析"""
    results = {}
    # 1. 度同配性
    results['degree_assortativity'] = nx.degree_assortativity_coefficient(G)
    # 2. 如果有节点属性,分析属性同配性
    node_attributes = {}
    # 假设有性别属性
    if 'gender' in nx.get_node_attributes(G, 'gender'):
        results['gender_assortativity'] = nx.attribute_assortativity_coefficient(G, 'gender')
    # 假设有年龄属性
    if 'age' in nx.get_node_attributes(G, 'age'):
        results['age_assortativity'] = nx.numeric_assortativity_coefficient(G, 'age')
    # 3. 计算局部同配性
    results['local_assortativity'] = local_assortativity_analysis(G)
    return results
def local_assortativity_analysis(G):
    """局部同配性分析"""
    local_assort = {}
    degrees = dict(G.degree())
    for node in G.nodes():
        neighbors = list(G.neighbors(node))
        if len(neighbors) > 1:
            neighbor_degrees = [degrees[n] for n in neighbors]
            # 计算局部同配性
            local_assort[node] = np.corrcoef(
                [degrees[node]] * len(neighbor_degrees), 
                neighbor_degrees
            )[0, 1]
        else:
            local_assort[node] = np.nan
    return local_assort

网络演化中的同配性

def temporal_assortativity_analysis(graphs_list):
    """时间序列同配性分析"""
    time_points = len(graphs_list)
    assortativity_over_time = []
    for t, G in enumerate(graphs_list):
        if G.number_of_edges() > 0:
            assort = nx.degree_assortativity_coefficient(G)
            assortativity_over_time.append(assort)
        else:
            assortativity_over_time.append(np.nan)
    return assortativity_over_time
# 模拟时间序列
def create_temporal_graphs():
    """创建随时间变化的图序列"""
    graphs = []
    base_G = nx.karate_club_graph()
    for t in range(5):
        G = base_G.copy()
        # 随机添加一些边来模拟演化
        for _ in range(10):
            u, v = np.random.choice(G.nodes(), 2, replace=False)
            if not G.has_edge(u, v):
                G.add_edge(u, v)
        graphs.append(G)
    return graphs
# 使用示例
temporal_graphs = create_temporal_graphs()
assort_over_time = temporal_assortativity_analysis(temporal_graphs)
plt.figure(figsize=(10, 6))
plt.plot(range(len(assort_over_time)), assort_over_time, 'o-')
plt.xlabel('时间步')
plt.ylabel('度同配性系数')'网络同配性随时间变化')
plt.grid(True)
plt.show()

可视化同配性

def visualize_assortativity(G):
    """可视化网络同配性"""
    fig, axes = plt.subplots(2, 2, figsize=(15, 12))
    # 1. 原始网络
    pos = nx.spring_layout(G, seed=42)
    nx.draw(G, pos, ax=axes[0, 0], node_color='lightblue', 
            node_size=100, with_labels=True)
    axes[0, 0].set_title('原始网络')
    # 2. 按度着色的网络
    degrees = dict(G.degree())
    node_colors = [degrees[n] for n in G.nodes()]
    nx.draw(G, pos, ax=axes[0, 1], node_color=node_colors,
            node_size=100, with_labels=True,
            cmap=plt.cm.RdYlBu)
    axes[0, 1].set_title('节点度分布')
    # 3. 同配性矩阵热图
    from networkx.algorithms.assortativity import mixing_matrix
    mixing_mat = mixing_matrix(G)
    im = axes[1, 0].imshow(mixing_mat, cmap='viridis', aspect='auto')
    axes[1, 0].set_title('度混合矩阵')
    plt.colorbar(im, ax=axes[1, 0])
    # 4. 平均邻居度图
    knn = nx.average_neighbor_degree(G)
    degrees_list = list(knn.keys())
    knn_values = list(knn.values())
    axes[1, 1].scatter(degrees_list, knn_values)
    axes[1, 1].set_xlabel('节点度 k')
    axes[1, 1].set_ylabel('平均邻居度 <knn>')
    axes[1, 1].set_title('knn(k) 曲线')
    axes[1, 1].grid(True)
    plt.tight_layout()
    plt.show()
# 使用示例
G = nx.karate_club_graph()
visualize_assortativity(G)

统计显著性检验

def assortativity_significance_test(G, n_permutations=1000):
    """同配性显著性检验"""
    original_assortativity = nx.degree_assortativity_coefficient(G)
    permutations = []
    for _ in range(n_permutations):
        # 随机重连边(保持度序列不变)
        G_perm = nx.double_edge_swap(G, nswap=len(G.edges())*2)
        if G_perm:
            perm_assort = nx.degree_assortativity_coefficient(G_perm)
            permutations.append(perm_assort)
    # 计算p值
    permutations = np.array(permutations)
    p_value = np.mean(np.abs(permutations) >= np.abs(original_assortativity))
    # 计算z-score
    z_score = (original_assortativity - np.mean(permutations)) / np.std(permutations)
    results = {
        'original': original_assortativity,
        'mean_null': np.mean(permutations),
        'std_null': np.std(permutations),
        'z_score': z_score,
        'p_value': p_value
    }
    return results
# 使用示例
G = nx.karate_club_graph()
significance_results = assortativity_significance_test(G)
print("同配性显著性检验结果:")
for key, value in significance_results.items():
    print(f"{key}: {value:.4f}")

这些代码示例涵盖了NetworkX中同配性分析的主要方面,根据你的具体需求,可以选择使用基础分析、高级分析或可视化方法。

抱歉,评论功能暂时关闭!