The model and the ensemble

EvoDAG.model

Everything a user needs to train and predict: EvoDAGE (the ensemble with the fit/predict interface), Ensemble and Model (what a fit returns) and EvoDAG (a single model; not the engine of EvoDAG.base, which has the same name).

tqdm(x, **kwargs)[source]

Stand-in used when tqdm is not installed: return x unchanged.

fit(X_y_evodag)[source]

Fit one member of an ensemble; the argument is a tuple (used with Pool.imap_unordered).

The tuple is (X, y, test_set, parameters, tmpdir, init_time). It returns the fitted Model, or None when there is no time left or the evolution fails. A model already stored in tmpdir is reused.

decision_function(model_X)[source]

Evaluate the decision function of one model; the argument is (k, model, X).

It returns [k, decision_function] so that results can be sorted after a parallel map.

predict_proba(model_X)[source]

Evaluate predict_proba of one model; the argument is (k, model, X).

It returns [k, probabilities] so that results can be sorted after a parallel map.

class Model[source]

Bases: object

A fitted model: the nodes needed to predict, with their coefficients.

It is built from an individual (usually the early stopping individual) keeping only the nodes that individual depends on, in the order in which they are evaluated. A model is obtained with EvoDAG.EvoDAG.model, as single_model.model after EvoDAG.model.EvoDAG.fit, or as the elements of Ensemble.models; it is not normally created directly. Use predict and decision_function with new inputs.

Parameters:
  • trace (list of int) – Positions in hist of the nodes that belong to the model.

  • hist (list) – History of all the individuals created by the evolution.

  • nvar (int, optional) – Number of inputs of the training data.

  • classifier (bool, optional) – Classification (default) or regression.

  • labels (numpy.ndarray, optional) – The class labels, used to translate the predictions.

  • probability_calibration (object, optional) – Fitted object with predict_proba used by predict_proba.

  • nclasses (int, optional) – Number of classes.

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)
>>> model = RGP.init(popsize=50, early_stopping_rounds=50, seed=0).fit(X, y).model()
>>> model.nvar, model.nclasses, model.classifier
(3, 2, True)
>>> model.predict(X).shape
(100,)
__init__(trace, hist, nvar=None, classifier=True, labels=None, probability_calibration=None, nclasses=None)[source]
property nclasses

Number of classes (None in regression)

property nvar

Number of inputs of the training data

property multiple_outputs

Whether the nodes have several outputs (one per class in classification)

property classifier

whether this is classification or regression task

property fitness_vs

Fitness in the validation set; it is minus the error, so zero is perfect

property size

Number of nodes of the model

property height

Height of the last node, the longest path down to an input

inputs(counter=None)[source]

Count how many times each input variable is used by the model.

Parameters:

counter (collections.Counter, optional) – Counter to update; a new one is created by default.

Returns:

Maps the index of an input (a column of X) to the number of nodes that read it.

Return type:

collections.Counter

transform(v)[source]

Replace, in node v, positions in the history by positions in the model.

predict_proba(X, **kwargs)[source]

Probabilities of each class, calibrated on the validation split.

It needs the probability_calibration parameter at training time; without it this raises AttributeError. Use EvoDAGE for the fraction of votes of an ensemble.

Parameters:

X (array_like) – Inputs, one row per example.

decision_function(X, **kwargs)[source]

Decision function i.e. the raw data of the prediction

predict(X, **kwargs)[source]

Predict X: the class with the largest output, or the value in regression.

Parameters:

X (array_like) – Inputs, one row per example.

Returns:

One element 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)
>>> model = RGP.init(popsize=50, early_stopping_rounds=50, seed=0).fit(X, y).model()
>>> hy = model.predict(X)
>>> hy.shape, bool((hy == y).mean() > 0.8)
((100,), True)
graphviz(fpt, terminals=True)[source]

Write the model in the dot language of Graphviz.

Parameters:
  • fpt (str or file-like) – File name, or an object with a write method.

  • terminals (bool, optional) – Include the input variables in the graph (default true).

Examples

>>> import io
>>> import numpy as np
>>> from EvoDAG import RGP
>>> rng = np.random.RandomState(0)
>>> X = rng.randn(100, 3)
>>> y = (X[:, 0] > 0).astype(int)
>>> model = RGP.init(popsize=50, early_stopping_rounds=50, seed=0).fit(X, y).model()
>>> out = io.StringIO()
>>> model.graphviz(out)
>>> out.getvalue().startswith("digraph EvoDAG {")
True
static convert_features(v)[source]

Convert inputs (rows are examples) into the list of Variable nodes used to evaluate a model.

static convert_features_test_set(vars, v)[source]

Store the test inputs v as the test set of the Variable nodes vars.

class Ensemble[source]

Bases: object

Fitted ensemble: the models obtained with different seeds and how they are combined.

Classification predicts the class that most models choose and the decision function is the median of the models’ outputs; in regression the prediction is that median. It is what EvoDAGE.fit returns and is not normally created directly: Ensemble.init creates an unfitted one that fit trains.

Parameters:
  • models (list of Model or None) – Fitted models; None for an ensemble to be trained with fit.

  • n_jobs (int, optional) – Processes used to train and to evaluate the models (default 1).

  • evodags (list of dict, optional) – Parameters of each member, used by fit.

  • tmpdir (str, optional) – Directory where finished members are stored; fit removes it at the end.

Examples

>>> import numpy as np
>>> from EvoDAG import EvoDAGE
>>> rng = np.random.RandomState(0)
>>> X = rng.randn(100, 3)
>>> y = (X[:, 0] > 0).astype(int)
>>> ensemble = EvoDAGE(n_estimators=3, popsize=50, early_stopping_rounds=50,
...                    seed=0).fit(X, y)
>>> type(ensemble).__name__, len(ensemble.models)
('Ensemble', 3)
__init__(models, n_jobs=1, evodags=None, tmpdir=None)[source]
training_size(args)[source]

Subsample the training set of each member when max_training_size is given.

args is the list of tuples that fit maps; the same list is returned when the parameter is not set.

fit(X, y, test_set=None)[source]

Train the members, in parallel when n_jobs is greater than one.

Parameters:
  • X (array_like) – Inputs, one row per example.

  • y (array_like) – Classes (numbers) or real targets.

  • test_set (array_like, optional) – Inputs evaluated along the evolution of each member.

Returns:

The ensemble itself; members that could not be trained in the time limit are left out.

Return type:

Ensemble

property nclasses

Number of classes

property probability_calibration

Whether the models have a probability calibration

property models

List containing the models that compose the ensemble

property multiple_outputs

Whether the models have several outputs

property classifier

Whether this is classification or regression

property fitness_vs

Median Fitness in the validation set

property size

Median number of nodes of the models

property height

Median height of the models

inputs(counter=None)[source]

Count how many times each input variable is used by all the models.

See Model.inputs; the counts of the models are added.

raw_decision_function(X)[source]

Outputs of every model side by side.

Returns:

One row per example and, for each model in turn, one column per class (a classifier) or per output.

Return type:

numpy.ndarray

predict_proba(X)[source]

Probability of each class.

Without calibration it is the fraction of the models that predict the class; with probability_calibration it is the average of the calibrated probabilities.

Returns:

One row per example, one column per class, in the order of the sorted labels.

Return type:

numpy.ndarray

decision_function(X, cpu_cores=1)[source]

Median, over the models, of their outputs.

Parameters:
  • X (array_like) – Inputs, one row per example.

  • cpu_cores (int, optional) – Processes used to evaluate the models; the larger of this and n_jobs is used.

Returns:

One row per example and one column per class (classification).

Return type:

numpy.ndarray

predict(X, cpu_cores=1)[source]

Predict X: the class chosen by most models, or the median in regression.

Parameters:
  • X (array_like) – Inputs, one row per example.

  • cpu_cores (int, optional) – Processes used to evaluate the models.

Returns:

One element per example, in the labels of the training data.

Return type:

numpy.ndarray

predict_cl(X, cpu_cores=1)[source]

Classes of X by majority vote of the models; predict uses it in classification.

graphviz(directory, **kwargs)[source]

Directory to store the graphviz models

classmethod init(n_estimators=30, n_jobs=1, tmpdir=None, **kwargs)[source]

Create an ensemble that is ready to be trained with fit.

Parameters:
  • n_estimators (int, optional) – Number of members (default 30). Member i uses seed seed + i.

  • n_jobs (int, optional) – Processes used to train and to evaluate the members.

  • tmpdir (str, optional) – Directory where finished members are stored.

  • **kwargs – Parameters of every member (see EvoDAG.EvoDAG).

Returns:

An ensemble without models.

Return type:

Ensemble

class EvoDAGE[source]

Bases: object

Ensemble of EvoDAG models with a scikit-learn-like interface.

It is exported by the top-level package: from EvoDAG import EvoDAGE. n_estimators runs are trained with consecutive seeds; each one learns from its own random split of the training data. The default parameters are those of EvoDAG/conf/default_parameters.json (or default_parameters_r.json when classifier=False); in classification they are the configuration rnd-rnd of the selection experiments: the random choice of the parents and of the individual that leaves, and macro-F1 as fitness (selection="random", negative_selection=False, fitness_function="macro-F1"). Note that fit returns an Ensemble, not the EvoDAGE instance.

Parameters:
  • time_limit (float, optional) – Seconds for the whole ensemble (default None, no limit). It replaces the time_limit of the parameters file.

  • n_estimators (int, optional) – Number of members (default 30).

  • n_jobs (int, optional) – Processes used to train and to evaluate the members (default 1).

  • tmpdir (str, optional) – Directory where finished members are stored, so that an interrupted fit can be resumed.

  • seed (int, optional) – Seed of the first member (default 0).

  • params_fname (str, optional) – JSON file with parameters, see EvoDAG.EvoDAG.init.

  • **kwargs – Any parameter of the engine, see EvoDAG.EvoDAG: popsize, early_stopping_rounds, classifier, the function names…

Examples

>>> import numpy as np
>>> from EvoDAG import EvoDAGE
>>> rng = np.random.RandomState(0)
>>> X = rng.randn(100, 3)
>>> y = (X[:, 0] > 0).astype(int)
>>> ensemble = EvoDAGE(n_estimators=3, popsize=50, early_stopping_rounds=50,
...                    seed=0).fit(X, y)
>>> hy = ensemble.predict(X)
>>> hy.shape, bool((hy == y).mean() > 0.8)
((100,), True)
>>> ensemble.predict_proba(X).shape
(100, 2)
>>> ensemble.decision_function(X).shape
(100, 2)
>>> ensemble.raw_decision_function(X).shape
(100, 6)
__init__(time_limit=None, **kwargs)[source]
property time_limit

no limit); it can be set

Type:

Seconds for the whole ensemble (None

fit(*args, **kwargs)[source]

Train the members; see Ensemble.fit (arguments X, y, test_set).

Returns:

The fitted ensemble (not this EvoDAGE instance), which has the predict family of methods and models.

Return type:

Ensemble

predict(*args, **kwargs)[source]

Predict the inputs; see Ensemble.predict

decision_function(*args, **kwargs)[source]

Median of the outputs of the models; see Ensemble.decision_function

raw_decision_function(*args, **kwargs)[source]

Outputs of every model side by side; see Ensemble.raw_decision_function

predict_proba(*args, **kwargs)[source]

Probability of each class; see Ensemble.predict_proba

class EvoDAG[source]

Bases: EvoDAGE

A single model with the scikit-learn-like fit/predict interface.

It is not the class exported as EvoDAG.EvoDAG (that one, EvoDAG.base.EvoDAG, is the search engine, also available as RGP and RootGP); this one is reached as EvoDAG.model.EvoDAG. It inherits predict, decision_function and the other methods of EvoDAGE, which after fit work on the fitted Model; in classification decision_function returns a list with one array per class.

Parameters:

**kwargs – Parameters of the engine (see EvoDAG.EvoDAG and EvoDAG.EvoDAG.init), including params_fname, seed and classifier.

Examples

>>> import numpy as np
>>> from EvoDAG.model import EvoDAG as SingleEvoDAG
>>> rng = np.random.RandomState(0)
>>> X = rng.randn(100, 3)
>>> y = (X[:, 0] > 0).astype(int)
>>> single = SingleEvoDAG(popsize=50, early_stopping_rounds=50, seed=0).fit(X, y)
>>> single.predict(X).shape
(100,)
>>> type(single.model).__name__
'Model'
__init__(**kwargs)[source]
fit(*args, **kwargs)[source]

Run the evolution and keep the model of the early stopping individual.

Parameters:
  • X (array_like) – Inputs, one row per example.

  • y (array_like) – Classes (numbers) or real targets.

  • test_set (array_like, optional) – Inputs evaluated along the evolution.

Returns:

This instance, whose model is now the fitted Model.

Return type:

EvoDAG

property model

The engine before fit and the fitted Model after it