Using EvoDAG from Python

EvoDAG offers scikit-learn estimators: they have fit, predict and score, they can be cloned, put in a Pipeline and tuned with GridSearchCV, as any other estimator. This page covers those classes. EvoDAG’s own classes (EvoDAGE, the search engine, the model objects) are described in Native API.

The examples on this page use small synthetic data and small populations so that they finish quickly; the library’s own defaults are much larger (see Parameters). The blocks share state: each one builds on the variables of the previous one, so you can paste the whole page into a script.

What the defaults are is explained at the beginning of Parameters. In particular, in classification the arguments and the individual that an offspring replaces are chosen at random and the fitness is macro-F1; params={"selection": "fitness", "negative_selection": True} gives the classical selection by fitness.

Which class do I use?

Class What it is
EnsembleClassifier, EnsembleRegressor an ensemble of independent EvoDAG runs (or of any other estimator); the usual choice
EvoDAGClassifier, EvoDAGRegressor one EvoDAG run, that is, one model
Native API EvoDAG’s own classes, for the command line’s models, a time limit for a whole ensemble and programs that already use them

For example, with a small synthetic problem (the sections below explain each piece):

import numpy as np
from EvoDAG import EnsembleClassifier, EvoDAGClassifier

rng = np.random.RandomState(0)
X = rng.randn(200, 4)
y = (X[:, 0] + X[:, 1] ** 2 > 1).astype(int)

tiny = EvoDAGClassifier(popsize=100, early_stopping_rounds=100)
model = EnsembleClassifier(tiny, n_estimators=5, random_state=0).fit(X, y)
print("accuracy on the training set:", model.score(X, y))

A single run can overfit, so the ensemble is what you normally want: each member is stopped early on its own validation split, and the members vote (classification) or give their median (regression). EnsembleClassifier(EvoDAGClassifier()) is the scikit-learn form of EvoDAG’s ensemble.

Install

The classes need scikit-learn, which is an optional dependency of EvoDAG:

pip install 'EvoDAG[sklearn]'

All four are importable from the top-level package, for example from EvoDAG import EnsembleClassifier, EvoDAGClassifier. Without scikit-learn the import raises an ImportError that says so, and the rest of EvoDAG keeps working.

Data

X is a two-dimensional array with one row per example (anything that scikit-learn accepts, such as a list of lists or a data frame). It must not have missing or infinite values. For classification y holds the class of each example: numbers or strings, and predict gives them back in the same type, in classes_. For regression y holds the real targets.

import numpy as np

rng = np.random.RandomState(0)
X = rng.randn(200, 5)
# three classes, labelled "a", "b" and "c"
y = (X[:, 0] + X[:, 1] ** 2 > 1).astype(int) + (X[:, 2] > 1.0)
y = np.array(["a", "b", "c"])[y]

Classification

EnsembleClassifier trains n_estimators independent runs of the estimator it is given; member i gets random_state + i, and therefore its own random split of the training data into the part used to evolve and the validation part used to stop (see How it works). Its prediction is the class chosen by most members. n_jobs is the number of processes used to train the members and to evaluate them later, and does not change the result.

from EvoDAG import EnsembleClassifier, EvoDAGClassifier

tiny = EvoDAGClassifier(popsize=100, early_stopping_rounds=100)
ensemble = EnsembleClassifier(tiny, n_estimators=5, n_jobs=1,
                              random_state=0).fit(X, y)
hy = ensemble.predict(X)
print("classes:", ensemble.classes_)
print("accuracy:", ensemble.score(X, y))

The estimator has methods of the usual shapes. The columns follow classes_, which are the sorted labels.

Method Returns
predict(X) the class with the largest median decision (with two classes, the second class when the median is positive)
predict_proba(X) one row per example, one column per class: the softmax of the median decision (voting="hard", the default), or the mean of the members’ probabilities (voting="soft")
decision_function(X) the median over the members of the raw outputs: one column per class, or one value per example with two classes
estimators_ the list of fitted members, in order

predict, decision_function and predict_proba agree with one another, as scikit-learn expects. The decision_function is exactly the median that EvoDAG’s own ensemble computes; its own predict takes a majority vote of the members instead, which can differ on a few examples (see Native API).

proba = ensemble.predict_proba(X)
print(proba.shape, proba.sum(axis=1)[:3])
print(ensemble.decision_function(X).shape)
print(len(ensemble.estimators_), "members")

EvoDAGClassifier alone fits one run, so it is one model. It has the same methods; its predict_proba is the one-hot encoding of predict unless you ask for calibrated probabilities (the engine parameter probability_calibration, given in params).

single = EvoDAGClassifier(popsize=100, early_stopping_rounds=100,
                          random_state=0).fit(X, y)
print("accuracy:", single.score(X, y))

For classification a model has one output per class: the problem is solved one class against the others, and predict picks the class with the largest output. When the last node of a model is a Naive Bayes or a Nearest Centroid node its outputs are squashed into the interval from -1 to 1 before they are returned; for any other kind of node they are the raw values.

Regression

EnsembleRegressor and EvoDAGRegressor work in the same way, and predict returns the real values (the median of the members for the ensemble). The defaults for regression come from a different file, default_parameters_r.json. That file has the ordinary selections (a tournament on fitness for the arguments and a negative tournament for the individual that leaves), not the random selection that is the default of classification.

from EvoDAG import EnsembleRegressor, EvoDAGRegressor

yr = 2 * X[:, 0] + X[:, 1] ** 2 + 0.1 * rng.randn(200)

regressor = EnsembleRegressor(
    EvoDAGRegressor(popsize=100, early_stopping_rounds=100),
    n_estimators=5, random_state=0).fit(X, yr)
hr = regressor.predict(X)
print("correlation:", np.corrcoef(hr, yr)[0, 1])
print("R^2:", regressor.score(X, yr))

A regression with several targets at once is not available through these classes; see Native API.

Parameters

EvoDAGClassifier and EvoDAGRegressor take these arguments; None means the value of the file of default parameters (the one for classification or the one for regression).

Argument Meaning
popsize size of the population
early_stopping_rounds individuals created without improvement before the evolution stops
time_limit seconds allowed for one evolution
random_state the seed (an integer, 0 by default; None is 0, so a fit is always reproducible)
params a dictionary with any other parameter of the engine
params_fname a JSON file (or a dictionary) used instead of the default parameters

The functions that EvoDAG may use to build an individual are parameters, named after the function: in params, a boolean switches the function on or off and an integer sets how many arguments it takes (0 removes it). Everything else is an ordinary key; all of them are listed in Parameters. The arguments take precedence over params, and the keys seed and classifier are not accepted there (use random_state and the class).

tuned = EnsembleClassifier(
    EvoDAGClassifier(popsize=100, early_stopping_rounds=100,
                     params={"Mul": 0, "Sin": False, "Add": 10,
                             "tournament_size": 3}),
    n_estimators=3, random_state=0).fit(X, y)
print(tuned.score(X, y))

The format of the file for params_fname is described in Parameters; params and the arguments override what the file says.

Wrapping other estimators

EnsembleClassifier and EnsembleRegressor are not tied to EvoDAG: they clone any scikit-learn estimator n_estimators times, give each clone random_state + i when it has that parameter (otherwise the clones are identical) and combine the members in the same way: the median of the predictions in regression and, in classification, the median of the decision_function when the estimator has one, or a majority vote when it has none (a decision tree, for example).

from sklearn.tree import DecisionTreeClassifier

trees = EnsembleClassifier(DecisionTreeClassifier(max_depth=3),
                           n_estimators=7, random_state=0).fit(X, y)
print("accuracy:", trees.score(X, y))

This is not scikit-learn’s BaggingClassifier, which combines the members with the mean and draws the seed of each member at random, nor its VotingClassifier, which needs every member listed by hand. Here the members are trained on the whole training set (the diversity comes from the seeds) and the combination is EvoDAG’s, which is what reproduces its ensemble.

Looking inside a fitted model

Each member of the ensemble keeps its model in model_, the object that has the nodes that the fitted individual depends on and their coefficients. It can tell how big it is and which input variables it ended up using.

model = ensemble.estimators_[0].model_
print("nodes:", model.size, "height:", model.height)
print("inputs used (variable: times):", dict(model.inputs()))
print("validation fitness:", model.fitness_vs)

model.fitness_vs is the fitness on the validation part, and it is the negative of the error: zero is perfect and lower values are worse. What a model can do (it can also be drawn with Graphviz) is described in Native API.

Saving and loading

The estimators are plain Python objects: pickle (or joblib) saves and restores them with everything they learned.

import pickle

restored = pickle.loads(pickle.dumps(ensemble))
print((restored.predict(X) == hy).all())