Symbolic regression with MAP-Elites

For robust fits that make different observations stand out as outliers, see Find equations for different parts of a dataset.

If several equations fit your measurements, an archive lets you keep alternatives and inspect where their predictions diverge. Use qdpy.symbolic with the base installation. Pass a two-dimensional input matrix with one column per variable and a one-dimensional target vector.

For parent selection on individual training errors, see Regression with lexicase or epsilon-lexicase. For selection on both error and output rarity, see Novelty-lexicase selection. These searches share a structural reporting grid.

For linked variation of expression trees, see Mix linked slots in expression trees.

Fit a dataset

The following search fits a one-variable polynomial. A separate interleaved grid supplies validation labels for model selection. The six probes lie outside the observed domain and carry no labels.

import numpy as np
from qdpy.symbolic import symbolic_regression

X = np.linspace(0., 1., 24)[:, None]
y = 1. + X[:, 0] ** 2
validation = (X[:-1] + X[1:]) / 2.
y_validation = 1. + validation[:, 0] ** 2
probes = np.linspace(1.1, 2., 6)[:, None]

result = symbolic_regression(
    X, y, mode="semantic", probes=probes, cells=16,
    operators=("add", "sub", "mul", "square"), budget=400, seed=11,
)
winner = min(result.models, key=lambda model: model.rmse(validation, y_validation))
print(winner.formula, winner.coefficients, winner.predict(probes))
print(result.stats)

Use result.best to inspect the training winner or result.models to select a model using separate validation data. Both QD modes return the native Grid or CVTGrid in result.archive. Each elite holds one fitted model as individual[0]. Its fitness is training RMSE, with smaller values preferred. The search returns an empty model collection and a None training winner if no finite fit passes the domain checks.

Choose an archive

Mode

What it retains

structural

One winner for each combination of node count, free coefficient count, and count of sine, cosine, exponential, and logarithm nodes.

semantic

One winner per CVT cell. Each descriptor coordinate is the prediction at one probe, scaled by the maximum absolute training target and compressed into the interval [-1, 1] with arctangent.

gp

Up to population_size models ranked by training RMSE, with no grid. Use it as a control for archive-based search.

All three modes share the same grammar, variation and fitting. If you supply probes, all three reject a model that is undefined at any probe. Choose a small set of locations that reflect where you would be interested in measuring next. A dense row of nearly identical probes gives that part of the domain more weight in CVT distances.

Valid predictions at the observed and probe locations establish finiteness at those locations. A fitted rational or logarithmic expression can still have singularities or undefined values elsewhere. predict returns NaN at rows where an intermediate calculation is undefined or overflows. It uses the mathematical operations printed in formula, including ordinary division.

Inspect disagreement

The example fits a noisy response on [0, 0.6]. It picks a validation winner and then chooses alternatives with similar errors and different predictions at unlabeled probes. The plot shows the observed domain next to the predicted curves beyond it. The forecast axis uses a symmetric logarithmic scale so that large deviations remain visible.

python examples/symbolic_regression.py --seed 11 --plot extrapolation.png

Read the equations printed next to their validation errors. For a scientific comparison, collect or reserve test labels separately and evaluate the equations chosen on validation. Extrapolation labels belong in the final assessment.

Fit an existing structure

If the structure is known, call fit_expression directly. Each appearance of a parameter leaf represents a different coefficient. Here the amplitude can be solved analytically at each trial frequency.

import numpy as np
from qdpy.symbolic import Expression, fit_expression

x = Expression.variable(0)
p = Expression.parameter()
wave = Expression("sin", (Expression("mul", (p, x)),))
equation = Expression("mul", (Expression("mul", (p, x)), wave))
X = np.linspace(0., 1., 21)[:, None]
y = .3 * X[:, 0] * np.sin(2 * np.pi * X[:, 0])
fit = fit_expression(equation, X, y, nonlinear_bounds=(.5, 20.),
                     max_evaluations=120, restarts=6, seed=11)
print(fit.model.formula, fit.evaluations)

The fitter solves affine coefficients by least squares. When the tree also contains nonlinear coefficients, it repeats the affine solve inside a bounded, seeded SciPy search using variable projection. Supply realistic nonlinear bounds where you have them. Search budgets count tree proposals even when a proposal repeats a structure. The separate fit_evaluations count includes finite-difference calls and the final fit check.

The structural descriptors follow the 2019 MAP-Elites study. The 2025 QDSR paper adds dimensional constraints and uses least-squares fitting. The semantic archive here groups fitted equations by predictions and uses a grammar with no physical units. See Symbolic regression benchmark and Symbolic regression API.