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).
- 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 fittedModel, orNonewhen there is no time left or the evolution fails. A model already stored intmpdiris 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_probaof 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:
objectA 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, assingle_model.modelafterEvoDAG.model.EvoDAG.fit, or as the elements ofEnsemble.models; it is not normally created directly. Usepredictanddecision_functionwith new inputs.- Parameters:
trace (list of int) – Positions in
histof 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_probaused bypredict_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 (
Nonein 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:
- predict_proba(X, **kwargs)[source]¶
Probabilities of each class, calibrated on the validation split.
It needs the
probability_calibrationparameter at training time; without it this raisesAttributeError. UseEvoDAGEfor the fraction of votes of an ensemble.- Parameters:
X (array_like) – Inputs, one row per example.
- 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:
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:
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
- class Ensemble[source]¶
Bases:
objectFitted 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.fitreturns and is not normally created directly:Ensemble.initcreates an unfitted one thatfittrains.- Parameters:
models (list of Model or None) – Fitted models;
Nonefor an ensemble to be trained withfit.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;
fitremoves 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)
- training_size(args)[source]¶
Subsample the training set of each member when
max_training_sizeis given.argsis the list of tuples thatfitmaps; 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_jobsis 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:
- 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:
- predict_proba(X)[source]¶
Probability of each class.
Without calibration it is the fraction of the models that predict the class; with
probability_calibrationit 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:
- 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_jobsis used.
- Returns:
One row per example and one column per class (classification).
- Return type:
- 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:
- predict_cl(X, cpu_cores=1)[source]¶
Classes of
Xby majority vote of the models;predictuses it in classification.
- class EvoDAGE[source]¶
Bases:
objectEnsemble of EvoDAG models with a scikit-learn-like interface.
It is exported by the top-level package:
from EvoDAG import EvoDAGE.n_estimatorsruns are trained with consecutive seeds; each one learns from its own random split of the training data. The default parameters are those ofEvoDAG/conf/default_parameters.json(ordefault_parameters_r.jsonwhenclassifier=False); in classification they are the configurationrnd-rndof 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 thatfitreturns anEnsemble, not theEvoDAGEinstance.- Parameters:
time_limit (float, optional) – Seconds for the whole ensemble (default
None, no limit). It replaces thetime_limitof 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)
- 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(argumentsX,y,test_set).- Returns:
The fitted ensemble (not this
EvoDAGEinstance), which has thepredictfamily of methods andmodels.- Return type:
- decision_function(*args, **kwargs)[source]¶
Median of the outputs of the models; see
Ensemble.decision_function
- class EvoDAG[source]¶
Bases:
EvoDAGEA single model with the scikit-learn-like
fit/predictinterface.It is not the class exported as
EvoDAG.EvoDAG(that one,EvoDAG.base.EvoDAG, is the search engine, also available asRGPandRootGP); this one is reached asEvoDAG.model.EvoDAG. It inheritspredict,decision_functionand the other methods ofEvoDAGE, which afterfitwork on the fittedModel; in classificationdecision_functionreturns a list with one array per class.- Parameters:
**kwargs – Parameters of the engine (see
EvoDAG.EvoDAGandEvoDAG.EvoDAG.init), includingparams_fname,seedandclassifier.
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'
- 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
modelis now the fittedModel.- Return type:
- property model¶
The engine before
fitand the fittedModelafter it