The search engine¶
EvoDAG.base holds the engine class that runs one evolution. It creates
the offspring (choosing a function, selecting its arguments, computing the
weights), asks the population to replace an individual with it and decides
when to stop.
EvoDAG.base¶
- class EvoDAG[source]¶
Bases:
objectThe EvoDAG search engine, also exported as
RGPandRootGP.It runs one evolution: it builds an initial population of simple individuals, creates one offspring at a time with the least-squares crossover (PrXO), and stops by early stopping on a validation split. After
fitcallmodelto obtain the fitted model. The class with the scikit-learn-like interface that wraps a single model isEvoDAG.model.EvoDAG(a different class with the same name), and the ensemble isEvoDAG.EvoDAGE.Most users create the engine with
init, which reads the default parameters fromEvoDAG/conf/default_parameters.json(ordefault_parameters_r.json), instead of calling the constructor, whose own defaults differ from that file. The defaults documented below are those of the constructor; where the configuration file has another value it is given as “Keyname(value)”. In particular the classification file is the configurationrnd-rndof the selection experiments, the best ranked with the scikit-learn interface (selection"random",negative_selectionfalse andfitness_function"macro-F1"; the keysfirst_selection"random"andheuristic_functions"tailored"stay in the file but only the heuristics read them), whereas the constructor keeps the selection by fitness (its fitness is"macro-F1"as well).- Parameters:
generations (int or float, optional) – Maximum number of generations; one generation is
popsizeoffspring.Noneornumpy.inf(the default) means no limit. Keygenerationsof the default parameters (null).popsize (int, optional) – Number of individuals in the population (default 10000). Key
popsize(4000). The string"nvar"sets it to the number of inputs plus the number of input functions.seed (int, optional) – Seed of the pseudo-random numbers (default 0). Key
seed.tournament_size (int, optional) – Individuals drawn in each tournament, for the arguments and for the individual that leaves (default 2). Key
tournament_size.early_stopping_rounds (int, optional) – The run stops when this many offspring were created without improving the early stopping individual (the best on the validation split). A negative value, the default, means
popsize. Keyearly_stopping_rounds(4000).function_set (list, optional) – Classes of
EvoDAG.nodethat may be used to create offspring (default: all of them).initbuilds it from the function keys of the parameters (Add,Mul, …).tr_fraction (float, optional) – Proportion of the data used for training when it is split into the training and the validation part (default 0.5). With 1 there is no validation set and
generationsmust be finite. Keytr_fraction.population_class (class or str, optional) –
SteadyState(default) orGenerational, or its name. Keypopulation_class.negative_selection (bool, optional) – If true (default) the individual replaced by an offspring is the worst of a tournament; if false it is chosen at random. Key
negative_selection(false in the classification file, true in the regression one).number_tries_feasible_ind (int, optional) – Attempts to find a valid individual before giving up (default 30).
time_limit (float, optional) – Seconds after which the evolution stops (default
None, no limit). Keytime_limit(3600).unique_individuals (bool, optional) – Reject offspring that repeat a function applied to the same arguments (default true). Key
unique_individuals(false).classifier (bool, optional) – Classification if true (default), regression otherwise. Key
classifier.labels (array_like, optional) – The class labels; by default they are taken from
yinfit.all_inputs (bool, optional) – Create initial individuals until every input has been used instead of until the population has
popsizeindividuals (default false). Keyall_inputs(true).random_generations (int, optional) – Number of generations in which the arguments are drawn at random instead of by tournament on fitness (default 0). Key
random_generations(0).fitness_function (str, optional) – Fitness in classification (default
"macro-F1"); the options are described in the Parameters page of the user guide. Ignored in regression. Keyfitness_function.orthogonal_selection (bool, optional) – Choose the arguments of the sum, Naive Bayes and Centroid by the smallest agreement with the first argument (default false). Not a key of the default parameters files since the classification file sets
selection. Ignored whenselectionis given.orthogonal_dot_selection (bool, optional) – Choose those arguments by the smallest dot product with the first argument (default false). Not in the default parameters. It has no effect while
orthogonal_selectionis true, which has precedence. Ignored whenselectionis given.selection (str, optional) – How the arguments (parents) of an offspring are chosen (default
None).Nonekeeps the behaviour driven byorthogonal_selectionandorthogonal_dot_selection. Otherwise it is one of"fitness"(tournament on fitness),"random","agreement","cosine","pearson","angle"(Angle-Driven Selection) and"novelty"(Novelty Search, classification andSteadyStateonly), the schemes of the selection paper. It takes precedence over the twoorthogonal_*booleans, which are then ignored. With a heuristic (the last five), the functions it does not apply to get their arguments at random. Keyselection("random"in the classification file; the regression file does not have it).first_selection (str, optional) – How the first (reference) individual of
"agreement","cosine","pearson"and"angle"is chosen:"random"(default) or"fitness"(tournament). The reference is the first argument of the function. Keyfirst_selection("random"in the classification file).heuristic_functions (str, optional) –
"tailored"(default): the heuristic is applied only to the functions it was designed for (the sum, the two Naive Bayes and the Nearest Centroid);"all": to every function with more than one argument. Keyheuristic_functions("tailored"in the classification file).min_density (float, optional) – When the average fraction of non-zero values in the population is below it, only density safe functions are used (default 0.8). Key
min_density.multiple_outputs (bool, optional) – Whether the individuals have several outputs (default false); it is always on in classification. Key
multiple_outputs.function_selection (bool, optional) – Choose the function of each offspring by a tournament on the average fitness of the offspring it produced, instead of at random (default true). Key
function_selection.fs_tournament_size (int, optional) – Size of that tournament (default 2). Key
fs_tournament_size.finite (bool, optional) – Replace the non-finite values of the inputs by zero (default true). Key
finite.pr_variable (float, optional) – Probability that an initial individual is a single input variable and not an input function (default 0.33). Key
pr_variable(0.9).share_inputs (bool, optional) – Kept for compatibility; it has no effect (default false). Key
share_inputs.input_functions (list, optional) – Classes (or names) among
NaiveBayes,NaiveBayesMN,CentroidandMultipleVariablesused to create the initial individuals that combine inputs (defaultNone). Keyinput_functions.F1_index (int, optional) – Class used by
fitness_function="F1"; -1 (default) is the smallest class.use_all_vars_input_functions (bool, optional) – Create first one individual per input function over all the variables (default false). Key
use_all_vars_input_functions(true).remove_raw_inputs (bool, optional) – Free the training inputs once the initial population exists (default true).
probability_calibration (class, optional) – A class with the
fit/predict_probainterface of scikit-learn used to calibrate probabilities (defaultNone).**kwargs – Ignored; they are kept in the instance. This is how keys of the parameters that are not arguments (for example
Argmax) are accepted.
Examples
>>> import numpy as np >>> from EvoDAG import RGP >>> rng = np.random.RandomState(0) >>> X = rng.randn(100, 3) >>> y = (X[:, 0] > 0).astype(int) >>> engine = RGP.init(popsize=50, early_stopping_rounds=50, seed=0) >>> model = engine.fit(X, y).model() >>> bool((model.predict(X) == y).mean() > 0.8) True
- __init__(generations=inf, popsize=10000, seed=0, tournament_size=2, early_stopping_rounds=-1, function_set=[<class 'EvoDAG.node.Add'>, <class 'EvoDAG.node.Mul'>, <class 'EvoDAG.node.Div'>, <class 'EvoDAG.node.Fabs'>, <class 'EvoDAG.node.Exp'>, <class 'EvoDAG.node.Sqrt'>, <class 'EvoDAG.node.Sin'>, <class 'EvoDAG.node.Cos'>, <class 'EvoDAG.node.Log1p'>, <class 'EvoDAG.node.Sq'>, <class 'EvoDAG.node.Min'>, <class 'EvoDAG.node.Max'>, <class 'EvoDAG.node.Atan2'>, <class 'EvoDAG.node.Hypot'>, <class 'EvoDAG.node.Acos'>, <class 'EvoDAG.node.Asin'>, <class 'EvoDAG.node.Atan'>, <class 'EvoDAG.node.Tan'>, <class 'EvoDAG.node.Cosh'>, <class 'EvoDAG.node.Sinh'>, <class 'EvoDAG.node.Tanh'>, <class 'EvoDAG.node.Acosh'>, <class 'EvoDAG.node.Asinh'>, <class 'EvoDAG.node.Atanh'>, <class 'EvoDAG.node.Expm1'>, <class 'EvoDAG.node.Log'>, <class 'EvoDAG.node.Log2'>, <class 'EvoDAG.node.Log10'>, <class 'EvoDAG.node.Lgamma'>, <class 'EvoDAG.node.Sign'>, <class 'EvoDAG.node.Ceil'>, <class 'EvoDAG.node.Floor'>, <class 'EvoDAG.node.NaiveBayes'>, <class 'EvoDAG.node.NaiveBayesMN'>, <class 'EvoDAG.node.Centroid'>], tr_fraction=0.5, population_class=<class 'EvoDAG.population.SteadyState'>, negative_selection=True, number_tries_feasible_ind=30, time_limit=None, unique_individuals=True, classifier=True, labels=None, all_inputs=False, random_generations=0, fitness_function='macro-F1', orthogonal_selection=False, orthogonal_dot_selection=False, min_density=0.8, multiple_outputs=False, function_selection=True, fs_tournament_size=2, finite=True, pr_variable=0.33, share_inputs=False, input_functions=None, F1_index=-1, use_all_vars_input_functions=False, remove_raw_inputs=True, probability_calibration=None, selection=None, first_selection='random', heuristic_functions='tailored', **kwargs)[source]¶
- get_params()[source]¶
Parameters used to initialize the class.
- Returns:
The name and the current value of each argument of the constructor, so that
clonecan create an equivalent engine.- Return type:
Examples
>>> from EvoDAG import RGP >>> params = RGP(popsize=20, seed=3).get_params() >>> params["popsize"], params["seed"] (20, 3)
- clone()[source]¶
Clone the class without the population.
- Returns:
A new engine, not fitted, created with
get_params.- Return type:
- property classifier¶
Whether it is a classification problem or not
- property signature¶
Instance file name
- property popsize¶
Population size
- property generations¶
Number of generations
- property X¶
Features or variables used in the training and validation set
- property Xtest¶
Features or variables used in the test set
- property y¶
Dependent variable
- property function_set¶
List containing the functions used to create the individuals
- property nvar¶
Number of features or variables
- property naive_bayes¶
Naive Bayes statistics of the training part, shared by the classifier nodes.
Nonein regression.
- property population¶
Class containing the population and all the individuals generated
- property init_popsize¶
Number of individuals created before the evolution proper starts.
- es_extra_test(v)[source]¶
This function is called from population before setting the early stopping individual and after the comparisons with the validation set fitness
- unfeasible_offspring()[source]¶
Count a rejected offspring (it also counts for early stopping) and return
None.
- get_args_orthogonal(func)[source]¶
Select the arguments of
funcby agreement with the first one.The first argument is chosen with the population tournament; each other one is the individual, among
tournament_sizedrawn at random, whose predicted labels agree least with those of the first argument on the training part. Returns the list of positions in the population of the arguments, the first argument first, orNoneif there are fewer thanfunc.min_nargs.
- get_args_orthogonal_dot(func)[source]¶
Select the arguments of
funcby the smallest dot product with the first one.Same procedure as
get_args_orthogonalbut the measure is the dot product of the masked outputs. Returns the list of positions of the arguments, the first argument first, orNoneif there are too few.
- get_unique_args(func)[source]¶
Select up to
func.nargsdifferent arguments by tournament.Returns the list of positions in the population, or
Nonewhen fewer thanfunc.min_nargsdifferent ones were found.
- get_args(func)[source]¶
Select the arguments of function
funcaccording to the selection parameters.It uses the agreement or the dot product heuristic when they are on and
funcsupports them, the tournament with distinct arguments for functions that require them, and the plain tournament otherwise. Whenselectionis notNoneit returns_get_args_selection(func)and the rest does not apply. Returns a list of positions in the population orNone.
- shuffle_tr2ts()[source]¶
Test set made by shuffling each input of the training set independently.
It is what
fituses as test set whentest_set="shuffle".
- fit(X, y, test_set=None)[source]¶
Run the evolution.
- Parameters:
X (array_like) – Inputs, one row per example. A list with one array per input (column) is also accepted.
y (array_like) – In classification the class of each example (numbers); in regression the real target. With several outputs a list with one array per output.
test_set (array_like or str, optional) – Inputs to be evaluated along the evolution so that predictions of the models are available without evaluating them again;
"shuffle"creates one from the training inputs.
- Returns:
The engine itself. Use
modelto obtain the fitted model.- Return type:
- Raises:
RuntimeError – If no suitable individual can be found, or if there is no validation split and no limit of generations.
Examples
>>> import numpy as np >>> from EvoDAG import RGP >>> rng = np.random.RandomState(0) >>> X = rng.randn(100, 3) >>> y = (X[:, 0] > 0).astype(int) >>> engine = RGP.init(popsize=50, early_stopping_rounds=50, seed=0) >>> engine.fit(X, y) is engine True >>> len(engine.population.hist) > 0 True
- trace(n)[source]¶
Positions in the history of the nodes that individual
ndepends on, sorted.- Parameters:
n (EvoDAG.node.Variable) – An individual of the history.
- model(v=None)[source]¶
Return the model of node
v.- Parameters:
v (EvoDAG.node.Variable, optional) – An individual found in
population.hist. By default the early stopping individual, the best on the validation split.- Returns:
The nodes needed to predict, with their coefficients.
- Return type:
Examples
>>> import numpy as np >>> from EvoDAG import RGP, Model >>> rng = np.random.RandomState(0) >>> X = rng.randn(100, 3) >>> y = (X[:, 0] > 0).astype(int) >>> engine = RGP.init(popsize=50, early_stopping_rounds=50, seed=0) >>> isinstance(engine.fit(X, y).model(), Model) True
- decision_function(v=None, X=None)[source]¶
Decision function, i.e. the raw outputs of the model.
- Parameters:
v (EvoDAG.node.Variable, optional) – Individual whose model is used; the early stopping one by default.
X (array_like, optional) – Inputs to evaluate. If
Nonethe output on the test set given tofitis returned.
- Returns:
In classification a list with one array per class.
- Return type:
Examples
>>> import numpy as np >>> from EvoDAG import RGP >>> rng = np.random.RandomState(0) >>> X = rng.randn(100, 3) >>> y = (X[:, 0] > 0).astype(int) >>> engine = RGP.init(popsize=50, early_stopping_rounds=50, seed=0) >>> df = engine.fit(X, y).decision_function(X=X) >>> len(df), df[0].shape (2, (100,))
- predict(v=None, X=None)[source]¶
Predict
X: the classes in classification, the values in regression.It can be called as
predict(X)or aspredict(v, X).- Parameters:
v (EvoDAG.node.Variable or array_like, optional) – Individual whose model is used; if
Xis not given this is taken as the inputs.X (array_like, optional) – Inputs to predict.
- Returns:
One value per example, in the labels of the training data.
- Return type:
Examples
>>> import numpy as np >>> from EvoDAG import RGP >>> rng = np.random.RandomState(0) >>> X = rng.randn(100, 3) >>> y = (X[:, 0] > 0).astype(int) >>> engine = RGP.init(popsize=50, early_stopping_rounds=50, seed=0) >>> hy = engine.fit(X, y).predict(X) >>> sorted(set(hy.tolist())) == [0, 1] True
- classmethod init(params_fname=None, seed=None, classifier=True, **kwargs)[source]¶
Create an engine from a file of parameters.
- Parameters:
params_fname (str or dict, optional) – JSON file (also gzip compressed when its name ends in
.gz) or dictionary with the parameters. A file that contains a list, as the one written byEvoDAG-params, uses its first element. By defaultEvoDAG/conf/default_parameters.jsonin classification anddefault_parameters_r.jsonin regression.seed (int, optional) – Overrides the seed of the parameters.
classifier (bool, optional) – Selects the default parameters when
params_fnameis not given (default true, classification).**kwargs – Parameters that override those of the file. Keys that are the name of a function (
Add,Mul, …) switch it on or off (boolean) or set its number of arguments (integer, 0 removes it).
- Returns:
An engine that is not fitted.
- Return type:
Examples
>>> from EvoDAG import RGP >>> engine = RGP.init(popsize=20, Mul=0, seed=2) >>> engine.popsize 20 >>> "Mul" in [f.__name__ for f in engine.function_set] False
EvoDAG.population¶
The population stores the individuals, runs the tournaments (selection of the arguments and negative selection of the individual that leaves) and tracks the best individual on the validation split.
- class Inputs[source]¶
Bases:
objectBuilds the nodes that combine input variables with the naive Bayes style functions (NaiveBayes, NaiveBayesMN, MultipleVariables, Centroid).
- use_all_variables()[source]¶
Whether the next node should be built on all the variables of the input.
- all_variables()[source]¶
Create the next function over all the input variables; None if the node is not feasible.
- class BasePopulation[source]¶
Bases:
objectPopulation of an evolutionary run: keeps the individuals, history, best so far and early stopping individual.
- __init__(base=None, tournament_size=2, classifier=True, labels=None, popsize=10000, random_generations=0, es_extra_test=<function BasePopulation.<lambda>>, negative_selection=True)[source]¶
- property popsize¶
Current number of individuals in the population.
- property population¶
List containing the population
- property density¶
Average density of the individuals in the population.
- property previous_estopping¶
Returns whether the last individual set in the population was an early stopping individual
- property hist¶
List containing all the individuals generated
- property estopping¶
Early stopping individual
- property bsf¶
Best so far
- clean(v)[source]¶
Remove the density of the individual v and free its outputs unless it is the early stopping individual.
- random_selection(negative=False)[source]¶
Return the index of an individual selected uniformly at random.
- random()[source]¶
Return the indices of as many different random individuals as the tournament size.
- tournament(negative=False)[source]¶
Tournament selection and when negative is True it performs negative tournament selection
- class SteadyState[source]¶
Bases:
BasePopulationSteady-state population: an individual replaces another one as soon as it is created.
- class Generational[source]¶
Bases:
BasePopulationGenerational GP using a steady-state as base
- class HGenerational[source]¶
Bases:
GenerationalGenerational population whose initial individuals are first built from the input and then from functions.
- input(vars)[source]¶
Create an individual with a function chosen by the function selection, using arguments from vars.
EvoDAG.function_selection¶
The tournament that chooses the function of each offspring according to the average fitness the function has obtained (compiled module).
- class FunctionSelection¶
Chooses the index of the function to use in a new node, by tournament on the average fitness of the functions.
- classmethod __new__(*args, **kwargs)¶
- avg_fitness(x)¶
Average fitness of function
x, i.e. its accumulated fitness divided by the times it was used, 0 if never used.
- comparison(best, comp)¶
Whether
comprepeatsbestand a different feasible function can still be drawn, so that it has to be drawn again.
- random_function()¶
Draw a function index uniformly at random (from the density safe functions when the density is below the minimum), retrying up to five times to avoid the unfeasible ones.
- tournament()¶
Select a function with a tournament, the best average fitness wins and ties go to the function with more arguments.