QDpy
Loading...
Searching...
No Matches
_residual.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Retain expressions that place large residuals in different data groups."""
7
8from dataclasses import dataclass
9from functools import lru_cache
10
11import numpy as np
12from sklearn.cluster import KMeans
13from threadpoolctl import threadpool_limits
14
15from qdpy.algorithms.modern import _bounds, _cma_strategy
16from qdpy.containers import Grid
17from qdpy.phenotype import Features, Fitness, Individual
18
19from ._expression import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
20from ._fit import _integer
21from ._search import _Grammar, _positions
22
23__all__ = ["residual_symbolic_regression", "ResidualSymbolicElite", "ResidualSymbolicStats",
24 "ResidualSymbolicResult"]
25
26
27
28@dataclass(frozen=True, slots=True)
30 """The fitted model predicts using its weighted expression tree."""
31
32 expression: Expression
33 model: FittedExpression
34 loss: float
35 outlier_cluster: int
36
37
38
39@dataclass(frozen=True, slots=True)
41 """Coefficient evaluations include each initial setting and all CMA-ES trials."""
42
43 proposals: int
44 coefficient_evaluations: int
45 invalid_evaluations: int
46 archive_updates: int
47
48
49
50@dataclass(frozen=True, slots=True)
52 """Each retained row records the group's original integer label."""
53
54 elites: tuple[ResidualSymbolicElite, ...]
55 archive: Grid
56 groups: tuple[int, ...]
57 stats: ResidualSymbolicStats
58
59 @property
60 def best(self):
61 """Return the lowest-loss elite, or None for an empty archive."""
62 return self.elites[0] if self.elites else None
63
64
65def _weighted(tree):
66 value = Expression(tree.op, tuple(_weighted(child) for child in tree.children), tree.value)
67 return Expression("mul", (Expression.parameter(), value))
68
69
70@lru_cache(maxsize=256)
71def _parameterized(tree):
72 weighted = _weighted(tree)
73 return weighted, _compile(weighted)[0]
74
75
76def _fold_constants(expression):
77 if not expression.children:
78 return expression
79 children = tuple(_fold_constants(child) for child in expression.children)
80 tree = Expression(expression.op, 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)
86 return tree
87
88
89def _clusters(x, y, groups, count, rng):
90 if groups is None:
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)
101 else:
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)
107
108
110 """Read breeding structures from the archive in its normal order."""
111
112 def __init__(self, grid):
113 self.grid = grid
114
115 def __len__(self):
116 return len(self.grid)
117
118 def parent(self, rng):
119 return self.grid[rng.integers(len(self.grid))][0]
120
121
123 def __init__(self, grid, x, y, labels, counts, group_ids, loss, layout):
124 self.grid, self.x, self.y = grid, x, y
125 self.labels, self.counts, self.group_ids = labels, counts, group_ids
126 self.loss, self.layout = loss, layout
127 self.calls = self.invalid = 0
128
129 def evaluate(self, raw, expression, program, coefficients):
130 self.calls += 1
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():
135 self.invalid += 1
136 return np.inf
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))
143 model = FittedExpression(expression, coefficients, rmse)
144 elite = ResidualSymbolicElite(raw, model, loss, self.labels[group])
145 descriptor = (group if self.layout == "residual" else 0, raw.node_count, raw.non_algebraic_count)
146 self.grid.add(Individual([elite], fitness=Fitness((loss,), weights=(-1.,)), features=Features(descriptor)))
147 return loss
148
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)
153 if limit == 1:
154 return
155 try:
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
160 while remaining:
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)
166
167
168
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.
194
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.
202
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.
208 """
209 x = _matrix(X)
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)
233 for tree in seeds:
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)
241 pool = _ResidualPool(grid)
242 completed = 0
243 for slot in range(proposals):
244 limit = min(trials, total - search.calls)
245 if limit <= 0:
246 break
247 tree = seeds[slot] if slot < len(seeds) else grammar.propose(pool)
248 search.fit(_fold_constants(tree), limit, bounds, fit_sigma, population, coefficients)
249 completed += 1
250 elites = tuple(sorted((row[0] for row in grid), key=lambda row: row.loss))
251 return ResidualSymbolicResult(elites, grid, labels,
252 ResidualSymbolicStats(completed, search.calls, search.invalid, grid.nb_added))
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
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.
Definition _residual.py:29
Return measured models, cluster labels, and the native archive.
Definition _residual.py:51
Count generated structures, actual coefficient trials, and archive updates.
Definition _residual.py:40
evaluate(self, raw, expression, program, coefficients)
Definition _residual.py:129