Selected topic
Ml In Federated Systems
Prefer practical output? Use related tools below while reading.
m as the number of hospitals (or organizations)D as the local dataset at each hospitalw as the shared model weightsθ_i as the local model parameters at hospital iu_i as the update sent from hospital i to the central serveru_i = ∇L(θ_i)
∑_i=1^m u_i
w = w + ∑_i=1^m u_iThis is a simplified example, and actual federated learning systems may involve more complex optimization algorithms, such as Federated Averaging (FedAvg) or Local Stochastic Gradient Descent (LSGD).
python
import torch
import torch.nn as nn# Define the shared model architecture
class SharedModel(nn.Module):
def __init__(self):
super(SharedModel, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
# Define the local model architecture
class LocalModel(nn.Module):
def __init__(self):
super(LocalModel, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
# Define the federated learning process
class FederatedLearning:
def __init__(self):
self.shared_model = SharedModel()
self.local_models = [LocalModel() for _ in range(3)] # 3 hospitals
def train_local(self, dataset):
local_model = self.local_models[dataset]
optimizer = torch.optim.SGD(local_model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(10): # Train for 10 epochs
inputs, labels = dataset
outputs = local_model(inputs)
loss = loss_fn(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
def update_global(self):
global_update = torch.zeros_like(self.shared_model.conv1.weight.data)
for i in range(3): # Aggregate updates from all hospitals
local_update = self.local_models[i].conv1.weight.data.clone()
global_update += local_update
self.shared_model.conv1.weight.data = global_update
# Initialize the federated learning process
fl = FederatedLearning()
# Train each hospital locally
for i in range(3):
fl.train_local(i) # i is the dataset index for hospital i
# Update the global model
fl.update_global()