1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
| """ 隐私保护的联邦学习驾驶员监控系统 """
import torch import torch.nn as nn import torch.optim as optim import numpy as np from typing import List, Dict, Optional from dataclasses import dataclass
@dataclass class FederatedConfig: """联邦学习配置""" num_clients: int = 5 local_epochs: int = 3 batch_size: int = 32 learning_rate: float = 1e-4 dp_noise_multiplier: float = 1.0 dp_max_grad_norm: float = 1.0 aggregation_method: str = 'fedavg' client_sampling_ratio: float = 0.8
class FederatedServer: """联邦学习服务器""" def __init__(self, model: nn.Module, config: FederatedConfig): """ Args: model: 全局模型 config: 联邦配置 """ self.global_model = model self.config = config self.global_params = {k: v.clone() for k, v in model.state_dict().items()} self.client_states: Dict[int, Dict] = {} self.history: List[Dict] = [] def initialize_clients(self, num_clients: int): """初始化客户端状态""" for i in range(num_clients): self.client_states[i] = { 'model_params': None, 'num_samples': 0, 'last_update_round': -1 } def aggregate(self, client_updates: List[Dict]) -> Dict: """ 聚合客户端更新 Args: client_updates: 客户端更新列表 [{'params': dict, 'num_samples': int}, ...] Returns: aggregated_params: 聚合后的模型参数 """ if not client_updates: return self.global_params total_samples = sum(u['num_samples'] for u in client_updates) aggregated_params = {} for key in self.global_params.keys(): aggregated_params[key] = torch.zeros_like(self.global_params[key]) for update in client_updates: weight = update['num_samples'] / total_samples aggregated_params[key] += weight * update['params'][key] aggregated_params = self._apply_dp_noise(aggregated_params) return aggregated_params def _apply_dp_noise(self, params: Dict) -> Dict: """应用差分隐私噪声""" noise_multiplier = self.config.dp_noise_multiplier for key in params.keys(): sensitivity = self.config.dp_max_grad_norm noise = torch.randn_like(params[key]) * sensitivity * noise_multiplier params[key] = params[key] + noise return params def distribute_model(self, client_id: int) -> Dict: """分发全局模型给客户端""" return {k: v.clone() for k, v in self.global_params.items()} def update_global_model(self, aggregated_params: Dict, round_num: int): """更新全局模型""" self.global_params = aggregated_params self.global_model.load_state_dict(aggregated_params) self.history.append({ 'round': round_num, 'timestamp': np.datetime64('now') })
class FederatedClient: """联邦学习客户端(车企节点)""" def __init__(self, client_id: int, model: nn.Module, config: FederatedConfig): """ Args: client_id: 客户端ID model: 本地模型 config: 联邦配置 """ self.client_id = client_id self.local_model = model self.config = config self.local_data = None self.num_samples = 0 self.optimizer = optim.Adam(model.parameters(), lr=config.learning_rate) def set_local_data(self, data_loader): """设置本地数据(不离开本地)""" self.local_data = data_loader self.num_samples = len(data_loader.dataset) def receive_global_model(self, global_params: Dict): """接收全局模型""" self.local_model.load_state_dict(global_params) def train_locally(self) -> Dict: """ 本地训练 Returns: update: 模型更新 """ self.local_model.train() criterion = nn.CrossEntropyLoss() for epoch in range(self.config.local_epochs): epoch_loss = 0.0 for batch_idx, (data, target) in enumerate(self.local_data): self.optimizer.zero_grad() output = self.local_model(data) loss = criterion(output, target) loss.backward() self._clip_gradients() self.optimizer.step() epoch_loss += loss.item() update = { 'params': {k: v.clone() for k, v in self.local_model.state_dict().items()}, 'num_samples': self.num_samples, 'client_id': self.client_id } return update def _clip_gradients(self): """梯度裁剪(差分隐私)""" max_norm = self.config.dp_max_grad_norm torch.nn.utils.clip_grad_norm_( self.local_model.parameters(), max_norm=max_norm )
class DMS_FederatedModel(nn.Module): """联邦学习DMS模型""" def __init__(self, num_classes=5): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.classifier = nn.Sequential( nn.Linear(128, 64), nn.ReLU(), nn.Dropout(0.5), nn.Linear(64, num_classes) ) def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x
def simulate_federated_training(): """模拟联邦学习训练过程""" config = FederatedConfig() global_model = DMS_FederatedModel() server = FederatedServer(global_model, config) num_clients = config.num_clients clients = [] for i in range(num_clients): local_model = DMS_FederatedModel() client = FederatedClient(i, local_model, config) clients.append(client) for client in clients: class DummyDataset(torch.utils.data.Dataset): def __len__(self): return 100 def __getitem__(self, idx): return torch.randn(3, 64, 64), torch.randint(0, 5, ()) dummy_loader = torch.utils.data.DataLoader( DummyDataset(), batch_size=config.batch_size, shuffle=True ) client.set_local_data(dummy_loader) num_rounds = 10 print("=" * 70) print("Federated Learning Simulation") print("=" * 70) for round_num in range(num_rounds): num_participants = int(num_clients * config.client_sampling_ratio) participant_ids = np.random.choice(num_clients, num_participants, replace=False) for client_id in participant_ids: global_params = server.distribute_model(client_id) clients[client_id].receive_global_model(global_params) client_updates = [] for client_id in participant_ids: update = clients[client_id].train_locally() client_updates.append(update) aggregated_params = server.aggregate(client_updates) server.update_global_model(aggregated_params, round_num) print(f"Round {round_num + 1}/{num_rounds} | Participants: {len(participant_ids)}") print("\nFederated training completed!") print(f"Total rounds: {num_rounds}") print(f"Differential privacy noise: {config.dp_noise_multiplier}")
if __name__ == "__main__": simulate_federated_training()
|