# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Diversified residual symbolic regression with robust coefficient search.
# @see https://doi.org/10.1145/3795095.3805087
"""Retain expressions that place large residuals in different data groups."""
from dataclasses import dataclass
from functools import lru_cache
import numpy as np
from sklearn.cluster import KMeans
from threadpoolctl import threadpool_limits
from qdpy.algorithms.modern import _bounds, _cma_strategy
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from ._expression import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
from ._fit import _integer
from ._search import _Grammar, _positions
__all__ = ["residual_symbolic_regression", "ResidualSymbolicElite", "ResidualSymbolicStats",
"ResidualSymbolicResult"]
## @brief A raw expression structure and one measured choice of node coefficients.
[docs]
@dataclass(frozen=True, slots=True)
class ResidualSymbolicElite:
"""The fitted model predicts using its weighted expression tree."""
expression: Expression
model: FittedExpression
loss: float
outlier_cluster: int
## @brief Count generated structures, actual coefficient trials, and archive updates.
[docs]
@dataclass(frozen=True, slots=True)
class ResidualSymbolicStats:
"""Coefficient evaluations include each initial setting and all CMA-ES trials."""
proposals: int
coefficient_evaluations: int
invalid_evaluations: int
archive_updates: int
## @brief Return measured models, cluster labels, and the native archive.
[docs]
@dataclass(frozen=True, slots=True)
class ResidualSymbolicResult:
"""Each retained row records the group's original integer label."""
elites: tuple[ResidualSymbolicElite, ...]
archive: Grid
groups: tuple[int, ...]
stats: ResidualSymbolicStats
@property
def best(self):
"""Return the lowest-loss elite, or None for an empty archive."""
return self.elites[0] if self.elites else None
def _weighted(tree):
value = Expression(tree.op, tuple(_weighted(child) for child in tree.children), tree.value)
return Expression("mul", (Expression.parameter(), value))
@lru_cache(maxsize=256)
def _parameterized(tree):
weighted = _weighted(tree)
return weighted, _compile(weighted)[0]
def _fold_constants(expression):
if not expression.children:
return expression
children = tuple(_fold_constants(child) for child in expression.children)
tree = Expression(expression.op, children)
if all(child.op == "constant" for child in children):
program, _, _, _ = _compile(tree)
value = float(_evaluate(program, np.empty((1, 0)), ())[0])
if np.isfinite(value):
return Expression.constant(value)
return tree
def _clusters(x, y, groups, count, rng):
if groups is None:
count = _integer(count, "clusters", 1)
points = np.column_stack((x, y))
points /= np.maximum(np.max(np.abs(points), axis=0), np.finfo(float).tiny)
bounds = points.min(axis=0)
width = points.max(axis=0) - bounds
points = (points - bounds) / np.where(width > 0., width, 1.)
if count > len(np.unique(points, axis=0)):
raise ValueError("clusters cannot exceed the number of distinct training rows.")
with threadpool_limits(limits=1):
groups = KMeans(count, n_init=5, random_state=int(rng.integers(2**31))).fit_predict(points)
else:
groups = np.asarray(groups)
if groups.shape != (len(x),) or not np.issubdtype(groups.dtype, np.integer):
raise ValueError("Supply one integer group label per training observation.")
labels, indices = np.unique(groups, return_inverse=True)
return tuple(map(int, labels)), indices, np.bincount(indices)
class _ResidualPool:
"""Read breeding structures from the archive in its normal order."""
def __init__(self, grid):
self.grid = grid
def __len__(self):
return len(self.grid)
def parent(self, rng):
return self.grid[rng.integers(len(self.grid))][0]
class _ResidualSearch:
def __init__(self, grid, x, y, labels, counts, group_ids, loss, layout):
self.grid, self.x, self.y = grid, x, y
self.labels, self.counts, self.group_ids = labels, counts, group_ids
self.loss, self.layout = loss, layout
self.calls = self.invalid = 0
def evaluate(self, raw, expression, program, coefficients):
self.calls += 1
predicted = _evaluate(program, self.x, coefficients)
with np.errstate(over="ignore", invalid="ignore"):
absolute = np.abs(predicted - self.y)
if not np.isfinite(absolute).all():
self.invalid += 1
return np.inf
scale = float(absolute.max()) or 1.
unit = absolute / scale
rmse = _rmse(predicted, self.y)
loss = (scale * float(np.mean(unit)) if self.loss == "mae" else
scale * float(np.median(unit)) if self.loss == "medae" else rmse)
group = int(np.argmax(np.bincount(self.group_ids, weights=unit) / self.counts))
model = FittedExpression(expression, coefficients, rmse)
elite = ResidualSymbolicElite(raw, model, loss, self.labels[group])
descriptor = (group if self.layout == "residual" else 0, raw.node_count, raw.non_algebraic_count)
self.grid.add(Individual([elite], fitness=Fitness((loss,), weights=(-1.,)), features=Features(descriptor)))
return loss
def fit(self, tree, limit, bounds, sigma, population, rng):
expression, program = _parameterized(tree)
initial = np.full(tree.node_count, np.clip(1., *bounds))
self.evaluate(tree, expression, program, initial)
if limit == 1:
return
try:
strategy = _cma_strategy(initial, sigma, population, int(rng.integers(2**31)), bounds)
except ImportError as error:
raise ImportError("CMA-ES coefficient trials require qdpy[cma].") from error
remaining = limit - 1
while remaining:
batch = strategy.ask(number=min(remaining, population))
scores = [self.evaluate(tree, expression, program, coefficients) for coefficients in batch]
if len(batch) == population:
strategy.tell(batch, scores)
remaining -= len(batch)
## @brief Evolve expression structures and retain robust fits in distinct residual niches.
# @param X Finite (samples, variables) training data.
# @param y One finite regression target per training row.
# @param groups Optional integer label per row, or None to cluster the scaled training data.
# @param clusters K-means cluster count when group labels are absent.
# @param loss Use median absolute error (medae), mean absolute error (mae), or root mean squared error (rmse).
# @param layout Use residual niches or a structural-only control.
# @param budget Hard cap on expression proposals, including repeats.
# @param fit_evaluations Maximum coefficient trials per proposal, including the initial setting.
# @param max_fit_evaluations Optional additional hard cap on coefficient trials over the whole run.
# @param max_depth Maximum depth in edges of the raw expression tree.
# @param max_nodes Maximum number of raw tree nodes.
# @param operators Operation names available to the tree grammar.
# @param literals Numeric constants available to the tree grammar.
# @param coefficient_bounds Common finite interval for node weights.
# @param fit_sigma Initial CMA-ES standard deviation.
# @param cma_population Coefficient trials per complete CMA-ES generation.
# @param initial_expressions Raw seed trees evaluated before genetic variation.
# @param seed Seed for genetic variation, clustering, and coefficient search.
# @return Measured residual niches and the cost of finding them.
[docs]
def residual_symbolic_regression(X, y, *, groups=None, clusters=4, loss="medae", layout="residual",
budget=128, fit_evaluations=25, max_fit_evaluations=None,
max_depth=4, max_nodes=12, operators=("add", "sub", "mul", "div", "log", "exp"),
literals=(1.,), coefficient_bounds=(-12., 12.), fit_sigma=.6,
cma_population=6, initial_expressions=(), seed=0):
"""Run DRSR on labeled training data with an optional structural control.
The archive indexes the group with highest mean absolute error,
raw tree size, and raw non-algebraic operator count. With
``layout="structural"``, the same search drops the group axis from
competition. Choose ``mae``, ``medae`` (median absolute error) or
``rmse`` as the optimization loss. The model's RMSE is recorded
independently. If supplied, the rows' integer group labels take
precedence over the default k-means clustering of scaled X and y.
Each raw tree gains one multiplicative weight per node. Constant
folding reuses the native expression evaluator. Bounded CMA-ES
trials require the existing ``cma`` extra. Undefined predictions
consume a trial. Every finite trial can enter the archive, including
lower-ranked coefficients that represent a different residual niche.
"""
x = _matrix(X)
target = _target(y, len(x))
proposals = _integer(budget, "budget", 0)
width = _integer(max_nodes, "max_nodes", 1)
depth = _integer(max_depth, "max_depth", 0)
trials = _integer(fit_evaluations, "fit_evaluations", 1)
total = proposals * trials if max_fit_evaluations is None else _integer(
max_fit_evaluations, "max_fit_evaluations", 0)
population = _integer(cma_population, "cma_population", 3)
bounds = _bounds(coefficient_bounds)
if not np.isfinite(bounds[1] - bounds[0]) or not 0. < fit_sigma < np.inf:
raise ValueError("Use a finite coefficient span and positive finite fit_sigma.")
if loss not in ("mae", "medae", "rmse") or layout not in ("residual", "structural"):
raise ValueError("Use mae, medae, or rmse and the residual or structural layout.")
variation, coefficients, clustering = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
labels, group_ids, counts = _clusters(x, target, groups, clusters, clustering)
groups_in_grid = len(labels) if layout == "residual" else 1
grid = Grid(shape=(groups_in_grid, width, width + 1),
features_domain=((-0.5, groups_in_grid - .5), (.5, width + .5), (-.5, width + .5)),
fitness_domain=((0., np.inf),), fitness_weights=(-1.,))
grammar = _Grammar(x.shape[1], operators, literals, depth, width, 0, variation)
if not grammar.leaves:
raise ValueError("Supply at least one variable or literal.")
seeds = tuple(initial_expressions)
for tree in seeds:
if not isinstance(tree, Expression):
raise TypeError("initial_expressions must contain Expression trees.")
_, _, parameters, variables = _compile(tree)
if (parameters or variables > x.shape[1] or tree.node_count > width
or any(len(path) > depth for path, _ in _positions(tree))):
raise ValueError("Each seed must match the variables and tree limits and have no parameter leaves.")
search = _ResidualSearch(grid, x, target, labels, counts, group_ids, loss, layout)
pool = _ResidualPool(grid)
completed = 0
for slot in range(proposals):
limit = min(trials, total - search.calls)
if limit <= 0:
break
tree = seeds[slot] if slot < len(seeds) else grammar.propose(pool)
search.fit(_fold_constants(tree), limit, bounds, fit_sigma, population, coefficients)
completed += 1
elites = tuple(sorted((row[0] for row in grid), key=lambda row: row.loss))
return ResidualSymbolicResult(elites, grid, labels,
ResidualSymbolicStats(completed, search.calls, search.invalid, grid.nb_added))