Residual regression and focused QD search¶
This guide covers five ways to preserve or use diversity during search.
The examples compare each method with a control using the same attempt
budget. Coefficient optimization in residual symbolic regression uses
the optional qdpy[cma] installation. The remaining examples use the
base package.
Find equations for different parts of a dataset¶
Diversified Residual Symbolic Regression (DRSR) retains equations with different residual patterns. For each fitted equation, compute the mean absolute residual within every group and record the group with the largest mean. Along with raw tree size and the number of non-algebraic operators, that group determines the archive cell. The robust loss determines which equation survives within a cell. [Ikeda2026]
import numpy as np
from qdpy.symbolic import Expression, residual_symbolic_regression
x = np.tile(np.linspace(0.2, 1.5, 20), 2)[:, None]
y = np.concatenate((x[:20, 0], -0.8 * x[20:, 0]))
result = residual_symbolic_regression(
x, y, groups=np.repeat((7, 12), 20), loss="medae",
budget=32, fit_evaluations=23, max_fit_evaluations=700,
initial_expressions=(Expression.variable(0),), seed=11,
)
for elite in result.elites[:6]:
print(elite.model.formula, elite.outlier_cluster, elite.loss)
print(result.stats)
Pass integer training group labels, or use the default k-means partition of scaled input and target columns. Each tree gets one multiplicative coefficient per node. QDpy uses its existing tree variation and constant folding, then runs bounded CMA-ES. The initial coefficients and every finite trial can enter the archive. This keeps alternative fits of the same tree available. Undefined predictions consume a trial and are excluded from admission. Candidate models carry the training RMSE separately from the chosen robust loss.
Use layout="structural" for a control with the same coefficient
search and only the two structural axes. Compare resulting models on
fresh labeled data. The bundled demo reports the lowest held-out RMSE
among retained models for each of two known relationships. It uses the
training regime labels to construct the archive.
Trigger extinction in a Voronoi archive¶
Pass extinction_period and extinction_size to
qdpy.algorithms.VoronoiElites. The period is measured in committed
batches. In a scheduled batch, after offering each result, repeatedly
remove the lower-quality member of the closest descriptor pair until
the archive fits the reduced size. Ordinary batches can refill the
archive to its usual capacity. A scheduled batch containing only failures
still shrinks the archive. [Feiden2023]
from qdpy.algorithms import VoronoiElites
from qdpy.containers import VoronoiArchive
archive = VoronoiArchive(20, features_domain=((0., 1.),) * 2,
fitness_domain=((0., 1.),))
search = VoronoiElites(
archive, 120, 2, batch_size=10,
extinction_period=5, extinction_size=6, seed=11,
)
search.optimise(lambda x: ((1. - (x[0] - 0.8) ** 2,), tuple(x)))
print(search.extinctions, search.pruned, len(archive))
Choose the descriptor to reflect meaningful behavioral differences. The wall-maze comparison uses four measured positions along each route. It reports the first evaluator call to reach the goal region and maps survivors onto a common endpoint grid.
Use different descriptors for selection and admission¶
In qdpy.algorithms.MultiDescriptorMAPElites, the ordinary
feature vector places evaluated offspring in an archive cell. Store a
second numeric descriptor in the evaluator’s named scores. Parent
selection uses these vectors for the current elites. A maze example
uses endpoints for archive cells and sampled trajectories for parent
selection. [Gravina2019]
from qdpy.algorithms import MultiDescriptorMAPElites
from qdpy.containers import Grid
archive = Grid(shape=(10,), features_domain=((0., 1.),),
fitness_domain=((0., 1.),), fitness_weights=(1.,))
def evaluate(genome):
u, v = genome
return (1. - (u - .5) ** 2,), (u,), {"waypoints": (v, u * v)}
search = MultiDescriptorMAPElites(
archive, 96, 2, selection_size=2, selection_score="waypoints",
mode="blend", batch_size=8, seed=11,
)
search.optimise(evaluate)
print(archive.filled_bins, search.forecasts)
novelty measures nearest-neighbor distance in the selection space.
surprise measures distance from forecasts obtained by extrapolating
cluster-center movement over two archive snapshots. blend combines the
two distances and pareto uses both as objectives in a rank-and-crowding
tournament. The single-score modes draw parents in proportion to the
scores, with uniform sampling when all scores are zero. Each method
uses the same bounded Iso+LineDD variation and native grid admission.
Supply the named selection vector on each elite when warm-starting.
Let a user direct local search¶
qdpy.algorithms.WindowedMAPElites implements User-Controlled
MAP-Elites (UC-ME). After a short global search, show a small set of
feasible elites near the current descriptor window. A user selection
moves the window. Future batches breed from the elites inside it.
Measured offspring can populate cells anywhere in the archive.
[Sfikas2023]
from qdpy.algorithms import RealVariable, WindowedMAPElites
from qdpy.containers import Grid
grid = Grid(shape=(10, 10), features_domain=((0., 1.),) * 2,
fitness_domain=((0., 1.),), fitness_weights=(1.,))
search = WindowedMAPElites(
grid, 60, [RealVariable(0., 1.)] * 2, window_radius=.2,
constraint_names="size", batch_size=10, seed=11,
)
def evaluate(genome):
u, v = genome
return (1. - .2 * abs(u - v),), (u, v), {"size": u + v - 1.2}
search.optimise(evaluate)
def choose_widest(panel):
return max(range(len(panel)), key=lambda i: panel[i].features.values[0])
search.choose(choose_widest, count=4, sampling="medoids")
search.optimise(evaluate, budget=60)
print(search.window_center)
The chooser returns the zero-based index of one of its alternatives.
Use alternatives() and focus(elite) if a notebook or UI needs
time to collect a choice. focus(None) returns to global search.
Medoids represent clusters of nearby designs. Corner sampling picks
distinct elites nearest to evenly spaced corner indices, up to one
elite per corner. In constrained runs, alternate between the eligible
feasible and lowest-violation elites when both pools have entries.
choose() only shows feasible alternatives.
Diversify ties within a binary Pareto front¶
qdpy.algorithms.GSEMOD samples a Pareto representative and
flips each bit with probability 1 / dimension. A new nondominated
objective vector can enter the population. If a candidate ties the
objectives of a representative, the population’s bit balance decides
whether the replacement is accepted. [Antipov2025]
from qdpy.algorithms import GSEMOD
search = GSEMOD(6, diversity="lexicographic", seed=11)
def evaluate(bits, seed):
ones = sum(bits)
return ones, len(bits) - ones
search.run(evaluate, 500)
print(search.stats.imbalance)
print(search.population)
The evaluator returns finite maximization objectives, or None
to record a failed attempt. Negate objectives you want to minimize.
total minimizes the sum of the per-bit imbalances. lexicographic
first minimizes the largest imbalance, then compares the rest
in descending order. none is ordinary GSEMO with replacement on
ties. Call run() again to spend an additional budget.
Reproduce the CPU comparisons¶
Run the bundled example
from a source checkout. Each command prints one JSON row per method
and seed. The residual case requires qdpy[cma].
python examples/residual_window_qd.py residual --seeds 11 22 33 44 55
python examples/residual_window_qd.py voronoi --seeds 11 22 33 44 55
python examples/residual_window_qd.py descriptors --seeds 11 22 33 44 55
python examples/residual_window_qd.py window --seeds 11 22 33 44 55
python examples/residual_window_qd.py binary --seeds 11 22 33 44 55
Both symbolic layouts recovered both generating relationships in all five runs at 48 tree proposals and 1,104 coefficient trials per run. The residual layout retained eight equations on average, and the structural control retained four. Mean best held-out RMSE for the negative-slope regime was 0.0146 with residual descriptors and 0.0528 with structural descriptors. Both layouts had mean positive-regime RMSE below 0.011.
Both Voronoi variants reached the goal in every run at 704 calls. With extinction, the mean first discovery was at call 171.0, compared with 286.6 for ordinary Voronoi-Elites. Median discovery calls were 169 and 183. Both variants ended with 28 survivors after the final refill, with mean endpoint QD scores of 14.03 and 14.36.
On the endpoint grid after 480 maze evaluations, uniform, novelty, surprise, blend, and Pareto selection had mean QD scores of 57.83, 61.03, 59.67, 62.12, and 60.25. Blend also had the largest mean nearest-neighbor trajectory distance, 0.150 compared with 0.147 for uniform selection.
With six choices and 276 evaluations, the scripted target preference averaged 0.642 across the global archive, 0.764 with corner displays, and 0.767 with medoid displays. The local methods occupied about 39 cells each. The global run averaged 53.4 cells.
All GSEMO variants reached the 35-vector reference Pareto front of
the ten-bit LOTZ-k problem at 1,800 evaluations. Ordinary GSEMO
averaged total imbalance of 174.4. Sum and lexicographic tie-breaking
averaged 146.0 and 146.4. The optimum total imbalance is 146 for this
problem. These comparisons use small, controlled examples.