Selection¶
This module defines the mating selection during the execution of a genetic algorithm. At the beginning of the mating, process parents need to be selected to be mated using the crossover operation.
Random Selection (‘random’)¶
Here, we randomly pick solutions from the current population to be used for recombination. The implementation uses a permutation to avoid repetitive individuals. For instance, let us consider the case where only two parents are desired to be selected: The permutation (5,2,3,4,1,0), will lead to the parent selection of (5,2), (3,4), (1,0), where no parent can participate twice for mating.
[1]:
from pymoo.factory import get_selection
selection = get_selection('random')
Tournament Selection (‘tournament’)¶
It has been shown that tournament pressure is helpful for faster convergence. This implementation provides the functionality to define a tournament selection very generic. Below we show a binary tournament selection (two individuals are participating in each competition).
Having defined the number of participants, the winner needs to be written to an output array. Here, we use the fitness values (if constraints should be considered, CV should be added as well) to achieve that.
[2]:
from pymoo.factory import get_selection
# simple binary tournament for a single-objective algorithm
def binary_tournament(pop, P, algorithm, **kwargs):
# The P input defines the tournaments and competitors
n_tournaments, n_competitors = P.shape
if n_competitors != 2:
raise Exception("Only pressure=2 allowed for binary tournament!")
# the result this function returns
import numpy as np
S = np.full(n_tournaments, -1, dtype=np.int)
# now do all the tournaments
for i in range(n_tournaments):
a, b = P[i]
# if the first individiual is better, choose it
if pop[a].F < pop[a].F:
S[i] = a
# otherwise take the other individual
else:
S[i] = b
return S
selection = get_selection('tournament', {'pressure' : 2, 'func_comp' : binary_tournament})
# Now for test purposes let us use the selection inplace
from pymoo.optimize import minimize
from pymoo.factory import get_algorithm
from pymoo.factory import get_problem
res = minimize(
get_problem("rastrigin"),
get_algorithm("ga",
pop_size=100,
eliminate_duplicates=True),
termination=('n_gen', 50),
verbose=False)
print(res.X)
[0.00012937 0.00049943]
API¶
-
pymoo.factory.
get_selection
(name, kwargs) A convenience method to get a selection object just by providing a string.
- Parameters
- name{ ‘random’, ‘tournament’ }
Name of the selection.
- kwargsdict
Dictionary that should be used to call the method mapped to the selection factory function.
- Returns
- class
Selection
An selection object based on the string. None if the selection was not found.
- class
-
pymoo.core.selection.
Selection
() → None