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: object

The EvoDAG search engine, also exported as RGP and RootGP.

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 fit call model to obtain the fitted model. The class with the scikit-learn-like interface that wraps a single model is EvoDAG.model.EvoDAG (a different class with the same name), and the ensemble is EvoDAG.EvoDAGE.

Most users create the engine with init, which reads the default parameters from EvoDAG/conf/default_parameters.json (or default_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 “Key name (value)”. In particular the classification file is the configuration rnd-rnd of the selection experiments, the best ranked with the scikit-learn interface (selection "random", negative_selection false and fitness_function "macro-F1"; the keys first_selection "random" and heuristic_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 popsize offspring. None or numpy.inf (the default) means no limit. Key generations of 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. Key early_stopping_rounds (4000).

  • function_set (list, optional) – Classes of EvoDAG.node that may be used to create offspring (default: all of them). init builds 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 generations must be finite. Key tr_fraction.

  • population_class (class or str, optional) – SteadyState (default) or Generational, or its name. Key population_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). Key time_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 y in fit.

  • all_inputs (bool, optional) – Create initial individuals until every input has been used instead of until the population has popsize individuals (default false). Key all_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. Key fitness_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 when selection is 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_selection is true, which has precedence. Ignored when selection is given.

  • selection (str, optional) – How the arguments (parents) of an offspring are chosen (default None). None keeps the behaviour driven by orthogonal_selection and orthogonal_dot_selection. Otherwise it is one of "fitness" (tournament on fitness), "random", "agreement", "cosine", "pearson", "angle" (Angle-Driven Selection) and "novelty" (Novelty Search, classification and SteadyState only), the schemes of the selection paper. It takes precedence over the two orthogonal_* booleans, which are then ignored. With a heuristic (the last five), the functions it does not apply to get their arguments at random. Key selection ("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. Key first_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. Key heuristic_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, Centroid and MultipleVariables used to create the initial individuals that combine inputs (default None). Key input_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_proba interface of scikit-learn used to calibrate probabilities (default None).

  • **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 clone can create an equivalent engine.

Return type:

dict

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:

EvoDAG

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.

None in 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

random_leaf()[source]

Returns a random variable with the associated weight

unique_individual(v)[source]

Test whether v has not been explored during the evolution

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 func by agreement with the first one.

The first argument is chosen with the population tournament; each other one is the individual, among tournament_size drawn 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, or None if there are fewer than func.min_nargs.

get_args_orthogonal_dot(func)[source]

Select the arguments of func by the smallest dot product with the first one.

Same procedure as get_args_orthogonal but the measure is the dot product of the masked outputs. Returns the list of positions of the arguments, the first argument first, or None if there are too few.

get_unique_args(func)[source]

Select up to func.nargs different arguments by tournament.

Returns the list of positions in the population, or None when fewer than func.min_nargs different ones were found.

get_args(func)[source]

Select the arguments of function func according to the selection parameters.

It uses the agreement or the dot product heuristic when they are on and func supports them, the tournament with distinct arguments for functions that require them, and the plain tournament otherwise. When selection is not None it returns _get_args_selection(func) and the rest does not apply. Returns a list of positions in the population or None.

random_offspring()[source]

Returns an offspring with the associated weight(s)

create_population()[source]

Create the initial population

stopping_criteria_tl()[source]

Whether time_limit seconds have passed since fit started.

stopping_criteria()[source]

Test whether the stopping criteria has been achieved.

nclasses(v)[source]

Number of classes of v, also sets the labes

replace(a)[source]

Replace an individual in the population with individual a

shuffle_tr2ts()[source]

Test set made by shuffling each input of the training set independently.

It is what fit uses as test set when test_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 model to obtain the fitted model.

Return type:

EvoDAG

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 n depends 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:

EvoDAG.model.Model

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 None the output on the test set given to fit is returned.

Returns:

In classification a list with one array per class.

Return type:

list or numpy.ndarray

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 as predict(v, X).

Parameters:
  • v (EvoDAG.node.Variable or array_like, optional) – Individual whose model is used; if X is 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:

numpy.ndarray

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 by EvoDAG-params, uses its first element. By default EvoDAG/conf/default_parameters.json in classification and default_parameters_r.json in regression.

  • seed (int, optional) – Overrides the seed of the parameters.

  • classifier (bool, optional) – Selects the default parameters when params_fname is 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:

EvoDAG

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
RGP

alias of EvoDAG

RootGP

alias of EvoDAG

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: object

Builds the nodes that combine input variables with the naive Bayes style functions (NaiveBayes, NaiveBayesMN, MultipleVariables, Centroid).

__init__(base, vars, functions=None)[source]
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.

functions()[source]

Select the functions to use, dropping those not safe for sparse data when the density is low.

function()[source]

Return the selected functions in a random order.

input()[source]

Create a feasible node from the next unused variables with one of the functions; None if there is none.

class BasePopulation[source]

Bases: object

Population 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.

get_density(v)[source]

Return the density of the individual v.

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

model(v=None)[source]

Returns the model of node v

trace(n)[source]

Restore the position in the history of individual v’s nodes

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

variable_input(used_inputs)[source]

Create a terminal node from the next unused input in used_inputs; None if there is none.

create_population()[source]

Create the initial population

add(v)[source]

Add an individual to the population

replace(v)[source]

Replace an individual selected by negative tournament selection with individual v

class SteadyState[source]

Bases: BasePopulation

Steady-state population: an individual replaces another one as soon as it is created.

create_population()[source]

Create the initial population and keep only the best individuals if it exceeds the population size.

class Generational[source]

Bases: BasePopulation

Generational GP using a steady-state as base

__init__(*args, **kwargs)[source]
replace(v)[source]

Add the individual v to the next generation, which replaces the population once it is full.

class HGenerational[source]

Bases: Generational

Generational 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.

extra_inputs()[source]

Add individuals built with functions over the initial ones and keep the best up to the population size.

create_population()[source]

Create the initial population from the input variables, then extend it with extra_inputs.

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 comp repeats best and 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.