6"""Retain expressions that place large residuals in different data groups."""
8from dataclasses
import dataclass
9from functools
import lru_cache
12from sklearn.cluster
import KMeans
13from threadpoolctl
import threadpool_limits
19from ._expression
import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
20from ._fit
import _integer
21from ._search
import _Grammar, _positions
23__all__ = [
"residual_symbolic_regression",
"ResidualSymbolicElite",
"ResidualSymbolicStats",
24 "ResidualSymbolicResult"]
28@dataclass(frozen=True, slots=True)
30 """The fitted model predicts using its weighted expression tree."""
32 expression: Expression
33 model: FittedExpression
39@dataclass(frozen=True, slots=True)
41 """Coefficient evaluations include each initial setting and all CMA-ES trials."""
44 coefficient_evaluations: int
45 invalid_evaluations: int
50@dataclass(frozen=True, slots=True)
52 """Each retained row records the group's original integer label."""
54 elites: tuple[ResidualSymbolicElite, ...]
56 groups: tuple[int, ...]
57 stats: ResidualSymbolicStats
61 """Return the lowest-loss elite, or None for an empty archive."""
66 value =
Expression(tree.op, tuple(_weighted(child)
for child
in tree.children), tree.value)
67 return Expression(
"mul", (Expression.parameter(), value))
70@lru_cache(maxsize=256)
71def _parameterized(tree):
72 weighted = _weighted(tree)
73 return weighted, _compile(weighted)[0]
76def _fold_constants(expression):
77 if not expression.children:
79 children = tuple(_fold_constants(child)
for child
in expression.children)
81 if all(child.op ==
"constant" for child
in children):
82 program, _, _, _ = _compile(tree)
83 value = float(_evaluate(program, np.empty((1, 0)), ())[0])
84 if np.isfinite(value):
85 return Expression.constant(value)
89def _clusters(x, y, groups, count, rng):
91 count = _integer(count,
"clusters", 1)
92 points = np.column_stack((x, y))
93 points /= np.maximum(np.max(np.abs(points), axis=0), np.finfo(float).tiny)
94 bounds = points.min(axis=0)
95 width = points.max(axis=0) - bounds
96 points = (points - bounds) / np.where(width > 0., width, 1.)
97 if count > len(np.unique(points, axis=0)):
98 raise ValueError(
"clusters cannot exceed the number of distinct training rows.")
99 with threadpool_limits(limits=1):
100 groups = KMeans(count, n_init=5, random_state=int(rng.integers(2**31))).fit_predict(points)
102 groups = np.asarray(groups)
103 if groups.shape != (len(x),)
or not np.issubdtype(groups.dtype, np.integer):
104 raise ValueError(
"Supply one integer group label per training observation.")
105 labels, indices = np.unique(groups, return_inverse=
True)
106 return tuple(map(int, labels)), indices, np.bincount(indices)
110 """Read breeding structures from the archive in its normal order."""
112 def __init__(self, grid):
116 return len(self.
grid)
118 def parent(self, rng):
119 return self.
grid[rng.integers(len(self.
grid))][0]
123 def __init__(self, grid, x, y, labels, counts, group_ids, loss, layout):
124 self.
grid, self.
x, self.
y = grid, x, y
127 self.
calls = self.invalid = 0
129 def evaluate(self, raw, expression, program, coefficients):
131 predicted = _evaluate(program, self.
x, coefficients)
132 with np.errstate(over=
"ignore", invalid=
"ignore"):
133 absolute = np.abs(predicted - self.
y)
134 if not np.isfinite(absolute).all():
137 scale = float(absolute.max())
or 1.
138 unit = absolute / scale
139 rmse = _rmse(predicted, self.
y)
140 loss = (scale * float(np.mean(unit))
if self.
loss ==
"mae" else
141 scale * float(np.median(unit))
if self.
loss ==
"medae" else rmse)
142 group = int(np.argmax(np.bincount(self.
group_ids, weights=unit) / self.
counts))
145 descriptor = (group
if self.
layout ==
"residual" else 0, raw.node_count, raw.non_algebraic_count)
149 def fit(self, tree, limit, bounds, sigma, population, rng):
150 expression, program = _parameterized(tree)
151 initial = np.full(tree.node_count, np.clip(1., *bounds))
152 self.
evaluate(tree, expression, program, initial)
156 strategy = _cma_strategy(initial, sigma, population, int(rng.integers(2**31)), bounds)
157 except ImportError
as error:
158 raise ImportError(
"CMA-ES coefficient trials require qdpy[cma].")
from error
159 remaining = limit - 1
161 batch = strategy.ask(number=min(remaining, population))
162 scores = [self.
evaluate(tree, expression, program, coefficients)
for coefficients
in batch]
163 if len(batch) == population:
164 strategy.tell(batch, scores)
165 remaining -= len(batch)
188def residual_symbolic_regression(X, y, *, groups=None, clusters=4, loss="medae", layout="residual",
189 budget=128, fit_evaluations=25, max_fit_evaluations=None,
190 max_depth=4, max_nodes=12, operators=(
"add",
"sub",
"mul",
"div",
"log",
"exp"),
191 literals=(1.,), coefficient_bounds=(-12., 12.), fit_sigma=.6,
192 cma_population=6, initial_expressions=(), seed=0):
193 """Run DRSR on labeled training data with an optional structural control.
195 The archive indexes the group with highest mean absolute error,
196 raw tree size, and raw non-algebraic operator count. With
197 ``layout="structural"``, the same search drops the group axis from
198 competition. Choose ``mae``, ``medae`` (median absolute error) or
199 ``rmse`` as the optimization loss. The model's RMSE is recorded
200 independently. If supplied, the rows' integer group labels take
201 precedence over the default k-means clustering of scaled X and y.
203 Each raw tree gains one multiplicative weight per node. Constant
204 folding reuses the native expression evaluator. Bounded CMA-ES
205 trials require the existing ``cma`` extra. Undefined predictions
206 consume a trial. Every finite trial can enter the archive, including
207 lower-ranked coefficients that represent a different residual niche.
210 target = _target(y, len(x))
211 proposals = _integer(budget,
"budget", 0)
212 width = _integer(max_nodes,
"max_nodes", 1)
213 depth = _integer(max_depth,
"max_depth", 0)
214 trials = _integer(fit_evaluations,
"fit_evaluations", 1)
215 total = proposals * trials
if max_fit_evaluations
is None else _integer(
216 max_fit_evaluations,
"max_fit_evaluations", 0)
217 population = _integer(cma_population,
"cma_population", 3)
218 bounds = _bounds(coefficient_bounds)
219 if not np.isfinite(bounds[1] - bounds[0])
or not 0. < fit_sigma < np.inf:
220 raise ValueError(
"Use a finite coefficient span and positive finite fit_sigma.")
221 if loss
not in (
"mae",
"medae",
"rmse")
or layout
not in (
"residual",
"structural"):
222 raise ValueError(
"Use mae, medae, or rmse and the residual or structural layout.")
223 variation, coefficients, clustering = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
224 labels, group_ids, counts = _clusters(x, target, groups, clusters, clustering)
225 groups_in_grid = len(labels)
if layout ==
"residual" else 1
226 grid =
Grid(shape=(groups_in_grid, width, width + 1),
227 features_domain=((-0.5, groups_in_grid - .5), (.5, width + .5), (-.5, width + .5)),
228 fitness_domain=((0., np.inf),), fitness_weights=(-1.,))
229 grammar =
_Grammar(x.shape[1], operators, literals, depth, width, 0, variation)
230 if not grammar.leaves:
231 raise ValueError(
"Supply at least one variable or literal.")
232 seeds = tuple(initial_expressions)
234 if not isinstance(tree, Expression):
235 raise TypeError(
"initial_expressions must contain Expression trees.")
236 _, _, parameters, variables = _compile(tree)
237 if (parameters
or variables > x.shape[1]
or tree.node_count > width
238 or any(len(path) > depth
for path, _
in _positions(tree))):
239 raise ValueError(
"Each seed must match the variables and tree limits and have no parameter leaves.")
240 search =
_ResidualSearch(grid, x, target, labels, counts, group_ids, loss, layout)
243 for slot
in range(proposals):
244 limit = min(trials, total - search.calls)
247 tree = seeds[slot]
if slot < len(seeds)
else grammar.propose(pool)
248 search.fit(_fold_constants(tree), limit, bounds, fit_sigma, population, coefficients)
250 elites = tuple(sorted((row[0]
for row
in grid), key=
lambda row: row.loss))
:param obj: Slice indicating on which objectives the domination is tested.
A safe expression tree whose parameter leaves each hold one free scalar.
A fitted expression with independently usable NumPy inference.
A raw expression structure and one measured choice of node coefficients.
Return measured models, cluster labels, and the native archive.
Count generated structures, actual coefficient trials, and archive updates.
evaluate(self, raw, expression, program, coefficients)