culebra.trainer.ea.NSGA class¶
- class NSGA(fitness_func: FitnessFunction, solution_cls: type[Individual], species: Species, crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]] | None = None, mutation_func: Callable[[Individual, float], tuple[Individual]] | None = None, selection_func: Callable[[list[Individual], int, Any], list[Individual]] | None = None, crossover_prob: float | None = None, mutation_prob: float | None = None, gene_ind_mutation_prob: float | None = None, pop_size: int | None = None, nsga3_reference_points_p: int | None = None, nsga3_reference_points_scaling: float | None = None, custom_termination_func: Callable[[NSGA], bool] | None = None, max_num_iters: int | None = None, checkpoint_activation: bool | None = None, checkpoint_freq: int | None = None, checkpoint_basename: str | None = None, verbosity: bool | None = None, random_seed: int | None = None)¶
Bases:
EACreate a new trainer.
- Parameters:
fitness_func (FitnessFunction) – The training fitness function
solution_cls (type[Individual]) – The individual class
species (Species) – The species for all the individuals
crossover_func (Callable) – The crossover function. If omitted,
_default_crossover_funcis used. Defaults toNonemutation_func (Callable) – The mutation function. If omitted,
_default_mutation_funcis used. Defaults toNoneselection_func (Callable) – The selection function. If omitted,
_default_selection_funcis used. Defaults toNonecrossover_prob (float) – The crossover probability. If omitted,
_default_crossover_probis used. Defaults toNonemutation_prob (float) – The mutation probability. If omitted,
_default_mutation_probis used. Defaults toNonegene_ind_mutation_prob (float) – The gene independent mutation probability. If omitted,
_default_gene_ind_mutation_probis used. Defaults toNonepop_size (int) – The population size. If omitted,
_default_pop_sizeis used. Defaults toNonensga3_reference_points_p (int) – Number of divisions along each objective to obtain the reference points of NSGA-III. If omitted,
_default_nsga3_reference_points_pwill be used. Defaults toNonensga3_reference_points_scaling (float) – Scaling factor for the reference points of NSGA-III. Defaults to
Nonecustom_termination_func (Callable) – Custom termination criterion. If omitted,
_default_termination_func()is used. Defaults toNonemax_num_iters (int) – Maximum number of iterations. If omitted,
_default_max_num_iterswill be used. Defaults toNonecheckpoint_activation (bool) – Checkpoining activation. If omitted,
_default_checkpoint_activationwill be used. Defaults toNonecheckpoint_freq (int) – The checkpoint frequency. If omitted,
_default_checkpoint_freqwill be used. Defaults toNonecheckpoint_basename (str) – The checkpoint base file path. If omitted,
_default_checkpoint_basenamewill be used. Defaults toNoneverbosity (bool) – The verbosity. If omitted,
_default_verbositywill be used. Defaults toNone
- Raises:
TypeError – If any argument is not of the appropriate type
ValueError – If any argument has an incorrect value
Class methods¶
- classmethod NSGA.load(filename: str) Base¶
Load a serialized object from a file.
- Parameters:
filename (str) – The file name.
- Returns:
The loaded object
- Raises:
TypeError – If filename is not a valid file name
ValueError – If the filename extension is not
SERIALIZED_FILE_EXTENSION
Properties¶
- property NSGA.checkpoint_basename: str¶
Checkpoint base file path.
- Return type:
- Setter:
Modify the checkpoint base file path
- Parameters:
value (str) – New value for the checkpoint base file path. If set to
None,_default_checkpoint_basenameis chosen- Raises:
TypeError – If value is not a valid file name
- property NSGA.checkpoint_filename: str¶
Checkpoint file path.
- Returns:
The file path to store checkpoints
- Return type:
- property NSGA.checkpoint_freq: int¶
Checkpoint frequency.
- Return type:
- Setter:
Modify the checkpoint frequency
- Parameters:
value (int) – New value for the checkpoint frequency. If set to
None,_default_checkpoint_freqis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is not a positive number
- property NSGA.container: DistributedTrainer | None¶
Container of this trainer.
The trainer container is only used by distributed trainers. For the rest of trainers defaults to
None.- Return type:
- Setter:
Set a new value for container of this trainer
- Parameters:
value (DistributedTrainer) – New value for the container or
None- Raises:
TypeError – If value is not a valid trainer
- property NSGA.cooperative_fitness_estimation_func: Callable[Sequence[Sequence[float]], Sequence[float]]¶
Cooperative fitness estimation function.
Funtion to estimate the cooperative fitness of a solution from several fitness trials with different cooperators. Only used by cooperative trainers.
- property NSGA.cooperators: list[list[Solution | None]] | None¶
Cooperators of the other species.
Only used by cooperative trainers. If the trainer does not use cooperators,
Noneis returned.
- property NSGA.crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]]¶
Crossover function.
- Return type:
- Setter:
Set the crossover function
- Parameters:
value (Callable) – The new crossover function. If set to :data`None`,
_default_crossover_funcis chosen- Raises:
- property NSGA.crossover_prob: float¶
Crossover probability.
- Return type:
- Setter:
Set the crossover probability
- Parameters:
value (float) – The new crossover probability. Must be in (0, 1). If set to :data`None`,
_default_crossover_probis chosen- Raises:
TypeError – If value is not a real number
ValueError – If value is not in (0, 1)
- property NSGA.custom_termination_func: Callable[[CentralizedTrainer], bool] | None¶
Custom termination criterion.
Although the trainer will always stop when the
max_num_itersare reached, a custom termination criterion can be set to detect convergente and stop the trainer earlier. This custom termination criterion must be a function which receives the trainer as its unique argument and returns a boolean value,Trueif the training should terminate orFalseotherwise.If more than one arguments are needed to define the termination condition,
functools.partial()can be used:from functools import partial def my_crit(trainer, max_iters): if trainer.current_iter < max_iters: return False return True trainer.custom_termination_func = partial(my_crit, max_iters=10)
- property NSGA.fitness_func: FitnessFunction¶
Training fitness function.
- Return type:
- Setter:
Set a new fitness function
- Parameters:
value (FitnessFunction) – The new training fitness function
- Raises:
TypeError – If value is not a valid fitness function
- property NSGA.gene_ind_mutation_prob: float¶
Gene independent mutation probability.
- Return type:
- Setter:
Set the gene independent mutation probability
- Parameters:
value (float) – The new gene independent mutation probability. Must be in (0, 1). If set to :data`None`,
_default_gene_ind_mutation_probis chosen- Raises:
TypeError – If value is not a real number
ValueError – If value is not in (0, 1)
- property NSGA.index: int¶
Trainer index.
The trainer index is only used within distributed trainers.
- Return type:
- Setter:
Set a new value for trainer index.
- Parameters:
value (int) – New value for the trainer index. If set to
None,_default_indexis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is a negative number
- property NSGA.iteration_obj_stats: dict(str, Callable)¶
Stats applied to each objective every iteration.
- Return type:
- property NSGA.max_num_iters: int¶
Maximum number of iterations.
- Return type:
- Setter:
Set a new value for the maximum number of iterations
- Parameters:
value (int) – The new maximum number of iterations. If set to
None,_default_max_num_itersis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value is not a positive number
- property NSGA.mutation_func: Callable[[Individual, float], tuple[Individual]]¶
Mutation function.
- Return type:
- Setter:
Set the mutation function
- Parameters:
value (Callable) – The new mutation function. If set to :data`None`,
_default_mutation_funcis chosen- Raises:
- property NSGA.mutation_prob: float¶
Mutation probability.
- Return type:
- Setter:
Set the mutation probability
- Parameters:
value (float) – The new mutation probability. Must be in (0, 1). If set to :data`None`,
_default_mutation_probis chosen- Raises:
TypeError – If value is not a real number
ValueError – If value is not in (0, 1)
- property NSGA.nsga3_reference_points_p: int¶
NSGA-III’s p parameter.
The p parameter indicates the number of divisions to be made along each objective to obtain the reference points of NSGA-III.
- Return type:
- Setter:
Set a new value for the p parameter for NSGA-III
- Parameters:
value (int) – The new number of divisions. If omitted,
_default_nsga3_reference_points_pis chosen- Raises:
TypeError – If value is not an integer
ValueError – If value < 1
- property NSGA.nsga3_reference_points_scaling: float | None¶
Scaling factor for the reference points of NSGA-III.
- property NSGA.pop: list[Individual] | None¶
Population.
- Returns:
The population or
Noneif it has not been generated yet- Return type:
- property NSGA.pop_size: int¶
Population size.
- Returns:
The population size
- Return type:
- Setter:
Set the population size
- Parameters:
value (int) – The new population size. Must be greater then zero. If set to :data`None`,
_default_pop_sizeis chosen- Raises:
ValueError – If value is not greater than zero
- property NSGA.receive_representatives_func: Callable[[CentralizedTrainer], None]¶
Representatives reception function.
Distributed trainers should set this property to their subtrainers in order to implement an adequate representatives exchange mechanism.
- property NSGA.send_representatives_func: Callable[[CentralizedTrainer], None]¶
Representatives sending function.
Distributed trainers should set this property to their subtrainers in order to implement an adequate representatives exchange mechanism.
- property NSGA.selection_func: Callable[[list[Individual], int, Any], list[Individual]]¶
Selection function.
- Return type:
- Setter:
Set the selection function
- Parameters:
value (Callable) – The new selection function. If set to :data`None`,
_default_selection_funcis chosen- Raises:
- property NSGA.state_proxy: DictProxy | None¶
Proxy for the state of this trainer.
The proxy is used to copy the state of the trainer only when training is executed within a
multiprocess.Process. Defaults toNone
Private properties¶
- property NSGA._default_checkpoint_activation: bool¶
Default checkpointing activation.
- Returns:
- Return type:
- property NSGA._default_checkpoint_basename: str¶
Default checkpointing base file name.
- Returns:
- Return type:
- property NSGA._default_cooperative_fitness_estimation_func: Callable[Sequence[Sequence[float]], Sequence[float]]¶
Default cooperative fitness estimation function.
Return the average of all fitness trials.
- property NSGA._default_crossover_func: Callable[[Individual, Individual], tuple[Individual, Individual]]¶
Default crossover function.
- Returns:
The
crossover()method ofsolution_cls- Return type:
- property NSGA._default_gene_ind_mutation_prob: float¶
Default gene independent mutation probability.
- Returns:
- Return type:
- property NSGA._default_max_num_iters: int¶
Default maximum number of iterations.
- Returns:
- Return type:
- property NSGA._default_mutation_func: Callable[[Individual, float], tuple[Individual]]¶
Default mutation function.
- Returns:
The
mutate()method ofsolution_cls- Return type:
- property NSGA._default_nsga3_reference_points_p: int¶
Default NSGA-III’s p parameter.
- Returns:
- Return type:
- property NSGA._default_pop_size: int¶
Default population size.
- Returns:
DEFAULT_POP_SIZEfor NSGA-II or the number of reference points for NSGA-III- Return type:
- property NSGA._default_receive_representatives_func: Callable[[CentralizedTrainer], None]¶
Default implementation for the representatives reception function.
It does nothing.
- property NSGA._default_selection_func: Callable[[list[Individual], int, Any], list[Individual]]¶
Default selection function.
- Returns:
- Return type:
- property NSGA._default_send_representatives_func: Callable[[CentralizedTrainer], None]¶
Default implementation for the representatives sending function.
It does nothing.
Methods¶
- NSGA.best_cooperators() list[list[Solution | None]] | None¶
Return a list of cooperators from each species.
Only used for cooperative trainers.
- NSGA.best_solutions() tuple[HallOfFame]¶
Get the best solutions found for each species.
- Returns:
One Hall of Fame for each species
- Return type:
- NSGA.dump(filename: str) None¶
Serialize this object and save it to a file.
- Parameters:
filename (str) – The file name.
- Raises:
TypeError – If filename is not a valid file name
ValueError – If the filename extension is not
SERIALIZED_FILE_EXTENSION
- NSGA.evaluate(sol: Solution, fitness_func: FitnessFunction | None = None, index: int | None = None, cooperators: Sequence[Sequence[Solution | None]] | None = None) int¶
Evaluate one solution.
Its fitness will be modified according with the fitness function results.
- Parameters:
sol (Solution) – The solution
fitness_func (FitnessFunction) – The fitness function. If omitted, the training function is used
index (int) – Index where sol should be inserted in the cooperators sequence to form a complete solution for the problem
cooperators (Sequence[Sequence[Solution]]) – Sequence of cooperators of other species or
None(if no cooperators are needed to evaluate sol)
- Returns:
The number of evaluations performed
- Return type:
- NSGA.integrate_representatives(representatives: list[Individual]) None¶
Integrate representative solutions.
This method is intended to be called within distributed trainers to make the implementation of migrations easier.
- Parameters:
representatives (list[Individual]) – A list of solutions
- NSGA.reset() None¶
Reset the trainer.
Delete the state of the trainer (with
_reset_state()) and also all the internal data structures needed to perform the training (with_reset_internals()).This method should be invoqued each time a hyper parameter is modified.
- NSGA.select_representatives() list[Individual]¶
Select representative solutions.
This method is intended to be called within distributed trainers to make the implementation of migrations easier.
- Returns:
A list of solutions
- Return type:
- NSGA.test(best_found: Sequence[HallOfFame], fitness_func: FitnessFunction, cooperators: Sequence[Sequence[Solution]] | None = None) None¶
Apply the test fitness function to the solutions found.
Update the solutions in best_found with their test fitness.
- Parameters:
best_found (Sequence[HallOfFame]) – The best solutions found for each species. One
HallOfFamefor each speciesfitness_func (FitnessFunction) – Fitness function used to evaluate the final solutions
cooperators (Sequence[ Sequence[Solution]]) – Sequence of cooperators of other species or
None(if no cooperators are needed)
- Raises:
TypeError – If any parameter has a wrong type
ValueError – If any parameter has an invalid value.
- NSGA.train()¶
Perform the training process.
Private methods¶
- NSGA._default_termination_func() bool¶
Default termination criterion.
- Returns:
Trueifmax_num_itersiterations have been run- Return type:
- NSGA._do_iteration() None¶
Implement an iteration of the training process.
In this case, a generation of NSGA is implemented.
- NSGA._do_training() None¶
Apply the training algorithm.
Execute the trainer until the termination condition is met. Each iteration is composed by the following steps:
- NSGA._evaluate_several(inds: Sequence[Individual]) None¶
Evaluate the individuals that have an invalid fitness.
- Parameters:
inds (Sequence[Individual]) – A sequence of individuals
- NSGA._finish_iteration() None¶
Finish an iteration.
Finish the iteration metrics (number of evaluations, execution time) after each iteration is run.
- NSGA._finish_training() None¶
Finish the training process.
This method is called after the training has finished. It can be overridden to perform any treatment of the solutions found.
- NSGA._generate_cooperators() Sequence[Sequence[Solution | None]] | None¶
Generate cooperators from other species.
- NSGA._generate_pop() None¶
Generate the initial population.
The population is filled with random generated individuals.
- NSGA._get_iteration_metrics() dict¶
Collect the iteration metrics.
- Returns:
The metrics
- Return type:
- NSGA._get_state() dict[str, Any]¶
Return the state of this trainer.
Overridden to add the current population to the trainer’s state.
- Return type:
- NSGA._init_internals() None¶
Set up the trainer internal data structures to start training.
Overridden to support the NSGA-III reference points.
- NSGA._init_state() None¶
Init the trainer state.
If there is any checkpoint file, the state is initialized from it with the
_load_state()method. Otherwise a new initial state is generated with the_new_state()method.
- NSGA._init_training() None¶
Init the training process.
Initialize the state of the trainer and all the internal data structures needed to perform the training.
- NSGA._load_state() None¶
Load the state of the last checkpoint.
- Raises:
Exception – If the checkpoint file can’t be loaded
- NSGA._new_state() None¶
Generate a new trainer state.
Overridden to fill the population with evaluated random individuals.
- NSGA._reset_internals() None¶
Reset the internal structures of the trainer.
Overridden to reset the NSGA-III reference points.
- NSGA._save_state() None¶
Save the state at a new checkpoint.
- Raises:
Exception – If the checkpoint file can’t be written
- NSGA._set_state(state: dict[str, Any]) None¶
Set the state of this trainer.
Overridden to add the current population to the trainer’s state.
- Parameters:
state (dict) – The last loaded state
- NSGA._start_iteration() None¶
Start an iteration.
Prepare the iteration metrics (number of evaluations, execution time) before each iteration is run.
- NSGA._termination_criterion() bool¶
Control the training termination.
- Returns:
Trueif either the default termination criterion or a custom termination criterion is met. The default termination criterion is implemented by the_default_termination_func()method. Another custom termination criterion can be set withcustom_termination_funcmethod- Return type:

