联邦图学习:跨机构图数据的隐私保护建模

FreeGuideOnline 最新 2026-06-28

bash pip install fedgraphnn pyg-lib torch-scatter torch-sparse -f https://data.pyg.org/whl/torch-2.0.0.html


### 数据划分:模拟 LOUvain 子图分布
借用 Cora 数据集,采用 Louvain 社区发现算法将原图分割为 3 个不重叠子图,分给三个客户端,并移除所有跨客户端边,模拟现实中的隔离数据。
```python
from fedgraphnn import load_and_partition_graph
client_data = load_and_partition_graph('Cora', num_clients=3, partition='louvain')

定义本地GNN模型

每个客户端使用两层 GraphSAGE 进行本地训练。

import torch.nn as nn
from torch_geometric.nn import SAGEConv

class LocalSAGE(nn.Module):
    def __init__(self, in_dim, hidden_dim, out_dim):
        super().__init__()
        self.conv1 = SAGEConv(in_dim, hidden_dim)
        self.conv2 = SAGEConv(hidden_dim, out_dim)
    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index).relu()
        return self.conv2(x, edge_index)

联邦训练循环(FedAvg)

服务器初始化全局模型,下发到所有客户端。客户端本地训练若干 epoch,上传模型权重,服务器按样本数加权聚合。

def federated_train(global_model, clients, rounds=50):
    for r in range(rounds):
        local_weights = []
        trade_count = []
        for client in clients:
            client.model.load_state_dict(global_model.state_dict())
            n_sample = client.train()
            local_weights.append(client.model.state_dict())
            trade_count.append(n_sample)
        # 加权平均聚合
        total = sum(trade_count)
        avg_weights = {}
        for key in global_model.state_dict().keys():
            avg_weights[key] = sum(clients[i].model.state_dict()[key] * (trade_count[i]/total) for i in range(len(clients)))
        global_model.load_state_dict(avg_weights)
        # 每10轮评估全局模型
        if r % 10 == 0:
            evaluate(global_model)