MEDfl.LearningManager packageο
Submodulesο
MEDfl.LearningManager.client moduleο
- class MEDfl.LearningManager.client.FlowerClient(cid: str, local_model: Model, trainloader: DataLoader, valloader: DataLoader, diff_priv: bool = True)[source]ο
Bases:
NumPyClientFlowerClient class for creating MEDfl clients.
- cidο
Client ID.
- Type:
str
- trainloaderο
DataLoader for training data.
- Type:
DataLoader
- valloaderο
DataLoader for validation data.
- Type:
DataLoader
- diff_privο
Flag indicating whether to use differential privacy.
- Type:
bool
- __init__(cid: str, local_model: Model, trainloader: DataLoader, valloader: DataLoader, diff_priv: bool = True)[source]ο
Initializes the FlowerClient instance.
- Parameters:
cid (str) β Client ID.
local_model (Model) β Local model of the federated learning network.
trainloader (DataLoader) β DataLoader for training data.
valloader (DataLoader) β DataLoader for validation data.
diff_priv (bool) β Flag indicating whether to use differential privacy.
- evaluate(parameters, config)[source]ο
Evaluates the local model on the validation data and returns the loss and accuracy.
- Parameters:
parameters β Parameters received from the server.
config β Configuration information.
- Returns:
Loss, number of validation examples, and accuracy information.
- Return type:
Tuple
- fit(parameters, config)[source]ο
Fits the local model to the received parameters using federated learning.
- Parameters:
parameters β Parameters received from the server.
config β Configuration information.
- Returns:
Parameters of the local model, number of training examples, and privacy information.
- Return type:
Tuple
MEDfl.LearningManager.dynamicModal moduleο
- class MEDfl.LearningManager.dynamicModal.DynamicModel[source]ο
Bases:
objectDynamicModel class for creating various types of neural network models.
- static create_binary_classifier(input_dim, hidden_dims, output_dim, activation='relu', dropout_rate=0.0, batch_norm=False, use_gpu=False)[source]ο
Creates a binary classifier neural network model with customizable architecture.
- Parameters:
input_dim (int) β Dimension of the input data.
hidden_dims (List[int]) β List of dimensions for hidden layers.
output_dim (int) β Dimension of the output (number of classes).
activation (str, optional) β Activation function for hidden layers. Default is βreluβ.
dropout_rate (float, optional) β Dropout rate for regularization. Default is 0.0 (no dropout).
batch_norm (bool, optional) β Whether to apply batch normalization. Default is False.
use_gpu (bool, optional) β Whether to use GPU acceleration. Default is False.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- static create_convolutional_neural_network(input_channels, output_channels, kernel_size, use_gpu=False)[source]ο
Creates a convolutional neural network (CNN) model.
- Parameters:
input_channels (int) β Number of input channels.
output_channels (int) β Number of output channels.
kernel_size (int) β Size of the convolutional kernel.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- static create_linear_regressor(input_dim, output_dim, use_gpu=False)[source]ο
Creates a linear regressor neural network model.
- Parameters:
input_dim (int) β Dimension of the input data.
output_dim (int) β Dimension of the output.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- static create_logistic_regressor(input_dim, use_gpu=False)[source]ο
Creates a logistic regressor neural network model.
- Parameters:
input_dim (int) β Dimension of the input data.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- static create_lstm_network(input_size, hidden_size, use_gpu=False)[source]ο
Creates a Long Short-Term Memory (LSTM) network model.
- Parameters:
input_size (int) β Size of the input layer.
hidden_size (int) β Size of the hidden layer.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- create_model(model_type: str, params_dict={}) Module[source]ο
Create a specific type of model dynamically based on the given parameters.
- Parameters:
model_type (str) β Type of the model to create (βBinary Classifierβ, βMulticlass Classifierβ, βLinear Regressorβ, βLogistic Regressorβ, βSVMβ, βNeural Network Classifierβ, βConvolutional Neural Networkβ, βRecurrent Neural Networkβ, βLSTM Networkβ, βAutoencoderβ).
params_dict (dict) β Dictionary containing parameters for model creation.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
- static create_multiclass_classifier(input_dim, hidden_dims, output_dim, activation='relu', dropout_rate=0.0, batch_norm=False, use_gpu=False)[source]ο
Creates a multiclass classifier neural network model with customizable architecture.
- Parameters:
input_dim (int) β Dimension of the input data.
hidden_dims (List[int]) β List of dimensions for hidden layers.
output_dim (int) β Dimension of the output (number of classes).
activation (str, optional) β Activation function for hidden layers. Default is βreluβ.
dropout_rate (float, optional) β Dropout rate for regularization. Default is 0.0 (no dropout).
batch_norm (bool, optional) β Whether to apply batch normalization. Default is False.
use_gpu (bool, optional) β Whether to use GPU acceleration. Default is False.
- Returns:
Created PyTorch model.
- Return type:
torch.nn.Module
MEDfl.LearningManager.federated_dataset moduleο
- class MEDfl.LearningManager.federated_dataset.FederatedDataset(name: str, train_nodes: list, test_nodes: list, trainloaders: list, valloaders: list, testloaders: list)[source]ο
Bases:
object- __init__(name: str, train_nodes: list, test_nodes: list, trainloaders: list, valloaders: list, testloaders: list)[source]ο
Represents a Federated Dataset.
- Parameters:
name β Name of the Federated Dataset.
train_nodes β List of train nodes.
test_nodes β List of test nodes.
trainloaders β List of train data loaders.
valloaders β List of validation data loaders.
testloaders β List of test data loaders.
MEDfl.LearningManager.flpipeline moduleο
- class MEDfl.LearningManager.flpipeline.FLpipeline(name: str, description: str, server: FlowerServer)[source]ο
Bases:
objectFLpipeline class for managing Federated Learning pipelines.
- nameο
The name of the FLpipeline.
- Type:
str
- descriptionο
A description of the FLpipeline.
- Type:
str
- serverο
The FlowerServer object associated with the FLpipeline.
- Type:
- __init__(self, name
str, description: str, server: FlowerServer) -> None: Initialize FLpipeline with the specified name, description, and server.
- auto_test(test_frac=1) List[dict][source]ο
Automatically test the FLpipeline on all nodes with the specified test_frac.
- Parameters:
test_frac (float, optional) β The fraction of the test data to use. Default is 1.
- Returns:
A list of dictionaries containing the node names and the classification reports.
- Return type:
List[dict]
- create(result: str) None[source]ο
Create a new FLpipeline entry in the database with the given result.
- Parameters:
result (str) β The result string to store in the database.
- delete() None[source]ο
Delete the FLpipeline entry from the database based on its name.
Note: This is a placeholder method and needs to be implemented based on your specific database setup.
- test_by_node(node_name: str, test_frac=1) dict[source]ο
Test the FLpipeline by node with the specified test_frac.
- Parameters:
node_name (str) β The name of the node to test.
test_frac (float, optional) β The fraction of the test data to use. Default is 1.
- Returns:
A dictionary containing the node name and the classification report.
- Return type:
dict
MEDfl.LearningManager.model moduleο
- class MEDfl.LearningManager.model.Model(model: Module, optimizer: Optimizer, criterion: Callable)[source]ο
Bases:
objectModel class for training and testing PyTorch neural networks.
- modelο
PyTorch neural network.
- Type:
torch.nn.Module
- optimizerο
PyTorch optimizer.
- Type:
torch.optim.Optimizer
- criterionο
Loss function.
- Type:
Callable
- __init__(model: Module, optimizer: Optimizer, criterion: Callable) None[source]ο
Initialize Model class with the specified model, optimizer, and criterion.
- Parameters:
model (torch.nn.Module) β PyTorch neural network.
optimizer (torch.optim.Optimizer) β PyTorch optimizer.
criterion (Callable) β Loss function.
- evaluate(val_loader, device=device(type='cpu')) Tuple[float, float][source]ο
Evaluate the model on the given validation data.
- Parameters:
val_loader β The data loader for validation data.
device β The device on which to perform the evaluation. Default is βcpuβ.
- Returns:
The evaluation loss and accuracy.
- Return type:
Tuple[float, float]
- get_parameters() List[ndarray][source]ο
Get the parameters of the model as a list of NumPy arrays.
- Returns:
The parameters of the model as a list of NumPy arrays.
- Return type:
List[np.ndarray]
- static load_model(model_path: str)[source]ο
Loads a PyTorch model from a file.
- Parameters:
model_path (str) β Path to the model file to be loaded.
- Returns:
Loaded PyTorch model.
- Return type:
torch.nn.Module
- static save_model(model, model_name: str)[source]ο
Saves a PyTorch model to a file.
- Parameters:
model (torch.nn.Module) β PyTorch model to be saved.
model_name (str) β Name of the model file.
- Raises:
Exception β If there is an issue during the saving process.
- Returns:
None
- set_parameters(parameters: List[ndarray]) None[source]ο
Set the parameters of the model from a list of NumPy arrays.
- Parameters:
parameters (List[np.ndarray]) β The parameters to be set.
- train(train_loader, epoch, device, privacy_engine, diff_priv=False) float[source]ο
Train the model on the given train_loader for one epoch.
- Parameters:
train_loader β The data loader for training data.
epoch (int) β The current epoch number.
device β The device on which to perform the training.
privacy_engine β The privacy engine used for differential privacy (if enabled).
diff_priv (bool, optional) β Whether differential privacy is used. Default is False.
- Returns:
The value of epsilon used in differential privacy.
- Return type:
float
MEDfl.LearningManager.plot moduleο
- class MEDfl.LearningManager.plot.AccuracyLossPlotter(results_dict)[source]ο
Bases:
objectA utility class for plotting accuracy and loss metrics based on experiment results.
- Parameters:
results_dict (dict) β Dictionary containing experiment results organized by parameters and metrics.
- results_dictο
Dictionary containing experiment results organized by parameters and metrics.
- Type:
dict
- parametersο
List of unique parameters in the experiment results.
- Type:
list
- metricsο
List of unique metrics in the experiment results.
- Type:
list
- iterationsο
Range of iterations (rounds or epochs) in the experiment.
- Type:
range
- __init__(results_dict)[source]ο
Initialize the AccuracyLossPlotter with experiment results.
- Parameters:
results_dict (dict) β Dictionary containing experiment results organized by parameters and metrics.
- static plot_classification_report(pipeline_name: str)[source]ο
Plot a comparison of classification report metrics between nodes.
- Parameters:
pipeline_name (str) β Name of the pipeline.
- Returns:
None
- MEDfl.LearningManager.plot.results_dict = {('LR: 0.001, Optimizer: Adam', 'accuracy'): [0.85, 0.89, 0.92, 0.94, Ellipsis], ('LR: 0.001, Optimizer: Adam', 'loss'): [0.2, 0.15, 0.1, 0.08, Ellipsis], ('LR: 0.01, Optimizer: SGD', 'accuracy'): [0.88, 0.91, 0.93, 0.95, Ellipsis], ('LR: 0.01, Optimizer: SGD', 'loss'): [0.18, 0.13, 0.09, 0.07, Ellipsis], ('LR: 0.1, Optimizer: Adam', 'accuracy'): [0.82, 0.87, 0.91, 0.93, Ellipsis], ('LR: 0.1, Optimizer: Adam', 'loss'): [0.25, 0.2, 0.15, 0.12, Ellipsis]}ο
- server should have:
- #len = num of rounds
self.accuracies self.losses
- Client should have
# len = num of epochs self.accuracies self.losses self.epsilons self.deltas
#common things : LR,SGD, Aggregation
MEDfl.LearningManager.server moduleο
- class MEDfl.LearningManager.server.FlowerServer(global_model: Model, strategy: Strategy, num_rounds: int, num_clients: int, fed_dataset: FederatedDataset, diff_privacy: bool = False, client_resources: Optional[Dict[str, float]] = {'num_cpus': 1, 'num_gpus': 0.0})[source]ο
Bases:
objectA class representing the central server for Federated Learning using Flower.
- strategyο
The strategy used for federated learning, specifying communication and aggregation methods.
- Type:
- num_roundsο
The number of federated learning rounds to perform.
- Type:
int
- num_clientsο
The number of clients participating in the federated learning process.
- Type:
int
- fed_datasetο
The federated dataset used for training and evaluation.
- Type:
- diff_privο
Whether differential privacy is used during the federated learning process.
- Type:
bool
- accuraciesο
A list to store the accuracy of the global model during each round.
- Type:
List[float]
- lossesο
A list to store the loss of the global model during each round.
- Type:
List[float]
- flower_clientsο
A list to store the FlowerClient objects representing individual clients.
- Type:
List[FlowerClient]
- __init__(global_model: Model, strategy: Strategy, num_rounds: int, num_clients: int, fed_dataset: FederatedDataset, diff_privacy: bool = False, client_resources: Optional[Dict[str, float]] = {'num_cpus': 1, 'num_gpus': 0.0}) None[source]ο
Initialize a FlowerServer object with the specified parameters.
- Parameters:
global_model (Model) β The global model that will be federated among clients.
strategy (Strategy) β The strategy used for federated learning, specifying communication and aggregation methods.
num_rounds (int) β The number of federated learning rounds to perform.
num_clients (int) β The number of clients participating in the federated learning process.
fed_dataset (FederatedDataset) β The federated dataset used for training and evaluation.
diff_privacy (bool, optional) β Whether differential privacy is used during the federated learning process. Default is False.
- client_fn(cid) FlowerClient[source]ο
Return a FlowerClient object for a specific client ID.
- Parameters:
cid β The client ID.
- Returns:
A FlowerClient object representing the individual client.
- Return type:
- evaluate(server_round: int, parameters: list[numpy.ndarray[Any, numpy.dtype[Any]]], config: Dict[str, Union[bool, bytes, float, int, str]]) Optional[Tuple[float, Dict[str, Union[bool, bytes, float, int, str]]]][source]ο
Evaluate the global model on the validation dataset and update the accuracies and losses.
- Parameters:
server_round (int) β The current round of the federated learning process.
parameters (fl.common.NDArrays) β The global model parameters.
config (Dict[str, fl.common.Scalar]) β Configuration dictionary.
- Returns:
The evaluation loss and accuracy.
- Return type:
Optional[Tuple[float, Dict[str, fl.common.Scalar]]]
MEDfl.LearningManager.strategy moduleο
- class MEDfl.LearningManager.strategy.Strategy(name: str = 'FedAvg', fraction_fit: float = 1.0, fraction_evaluate: float = 1.0, min_fit_clients: int = 2, min_evaluate_clients: int = 2, min_available_clients: int = 2, initial_parameters=[], evaluation_methode='centralized')[source]ο
Bases:
objectA class representing a strategy for Federated Learning.
- nameο
The name of the strategy. Default is βFedAvgβ.
- Type:
str
- fraction_fitο
Fraction of clients to use for training during each round. Default is 1.0.
- Type:
float
- fraction_evaluateο
Fraction of clients to use for evaluation during each round. Default is 1.0.
- Type:
float
- min_fit_clientsο
Minimum number of clients to use for training during each round. Default is 2.
- Type:
int
- min_evaluate_clientsο
Minimum number of clients to use for evaluation during each round. Default is 2.
- Type:
int
- min_available_clientsο
Minimum number of available clients required to start a round. Default is 2.
- Type:
int
- initial_parametersο
The initial parameters of the server model
- Type:
Optional[]
Methods:
- __init__(name: str = 'FedAvg', fraction_fit: float = 1.0, fraction_evaluate: float = 1.0, min_fit_clients: int = 2, min_evaluate_clients: int = 2, min_available_clients: int = 2, initial_parameters=[], evaluation_methode='centralized') None[source]ο
Initialize a Strategy object with the specified parameters.
- Parameters:
name (str) β The name of the strategy. Default is βFedAvgβ.
fraction_fit (float) β Fraction of clients to use for training during each round. Default is 1.0.
fraction_evaluate (float) β Fraction of clients to use for evaluation during each round. Default is 1.0.
min_fit_clients (int) β Minimum number of clients to use for training during each round. Default is 2.
min_evaluate_clients (int) β Minimum number of clients to use for evaluation during each round. Default is 2.
min_available_clients (int) β Minimum number of available clients required to start a round. Default is 2.
initial_parameters (Optional[]) β The initial parametres of the server model
evaluation_methode ("centralized" | "distributed") β
MEDfl.LearningManager.utils moduleο
- MEDfl.LearningManager.utils.custom_classification_report(y_true, y_pred_prob)[source]ο
Compute custom classification report metrics including accuracy, sensitivity, specificity, precision, NPV, F1-score, false positive rate, and true positive rate.
- Parameters:
y_true (array-like) β True labels.
y_pred (array-like) β Predicted labels.
- Returns:
A dictionary containing custom classification report metrics.
- Return type:
dict
- MEDfl.LearningManager.utils.empty_db()[source]ο
Empty the database by deleting records from multiple tables and resetting auto-increment counters.
- Returns:
None
- MEDfl.LearningManager.utils.get_node_confusion_matrix(pipeline_id, node_name)[source]ο
Get the confusion matrix for a specific node in a pipeline based on test results.
- Parameters:
pipeline_id (int) β ID of the pipeline.
node_name (str) β Name of the node.
- Returns:
A dictionary representing the confusion matrix for the specified node.
- Return type:
dict
- MEDfl.LearningManager.utils.get_pipeline_confusion_matrix(pipeline_id)[source]ο
Get the global confusion matrix for a pipeline based on test results.
- Parameters:
pipeline_id (int) β ID of the pipeline.
- Returns:
A dictionary representing the global confusion matrix.
- Return type:
dict
- MEDfl.LearningManager.utils.get_pipeline_from_name(name)[source]ο
Get the pipeline ID from its name in the database.
- Parameters:
name (str) β Name of the pipeline.
- Returns:
ID of the pipeline.
- Return type:
int
- MEDfl.LearningManager.utils.get_pipeline_result(pipeline_id)[source]ο
Get the test results for a pipeline.
- Parameters:
pipeline_id (int) β ID of the pipeline.
- Returns:
DataFrame containing test results for the specified pipeline.
- Return type:
pandas.DataFrame
- MEDfl.LearningManager.utils.load_db_config()[source]ο
Read a dictionary from an environment variable.
- MEDfl.LearningManager.utils.test(model, test_loader, device=device(type='cpu'))[source]ο
Evaluate a model using a test loader and return a custom classification report.
- Parameters:
model (torch.nn.Module) β PyTorch model to evaluate.
test_loader (torch.utils.data.DataLoader) β DataLoader for the test dataset.
device (torch.device, optional) β Device for model evaluation. Default is βcpuβ.
- Returns:
A dictionary containing custom classification report metrics.
- Return type:
dict