QDpy
Loading...
Searching...
No Matches
_fit.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5from dataclasses import dataclass
6from math import isfinite
7from operator import index
8
9import numpy as np
10from scipy.optimize import least_squares
11
12from ._expression import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
13
14
15
16@dataclass(frozen=True, slots=True)
18 """Report a fitted model or None if no finite fit was found within the budget."""
19
20 model: FittedExpression | None
21 evaluations: int
22
23
24class _FitLimit(Exception):
25 """Stop SciPy before another finite difference call exceeds the allotted budget."""
26
27
28def _integer(value, name, minimum):
29 value = index(value)
30 if value < minimum:
31 raise ValueError(f"{name} must be at least {minimum}.")
32 return value
33
34
35class _Fitter:
36 def __init__(self, x, y, bounds, budget, restarts):
37 lower, upper = map(float, bounds)
38 if not isfinite(upper - lower) or not lower < upper:
39 raise ValueError("Nonlinear bounds need a finite, positive width.")
40 self.x = x
41 self.y = y
42 self.bounds = lower, upper
43 self.budget = _integer(budget, "max_evaluations", 2)
44 self.restarts = _integer(restarts, "restarts", 1)
45 self.scale = float(np.max(np.abs(y))) or 1.
46
47 def fit(self, expression, seed):
48 program, linear, count, n_variables = _compile(expression)
49 if self.x.shape[1] < n_variables:
50 raise ValueError(f"The expression needs at least {n_variables} input columns.")
51 problem = _FitProblem(self, program, linear, count)
52 return problem.solve(expression, seed)
53
54
56 def __init__(self, fitter, program, linear, count):
57 self.fitter = fitter
58 self.program = program
59 self.affine = {slot: column for column, slot in enumerate(linear, 1)}
60 self.nonlinear = [slot for slot in range(count) if slot not in self.affine]
61 self.coefficients = np.zeros(count)
62 self.calls = 0
63 self.stop = fitter.budget - bool(linear)
64 self.best_rmse = float("inf")
65 self.best_coefficients = None
66 self.penalty = np.full_like(fitter.y, 1e6)
67
68 def objective(self, theta):
69 if self.calls >= self.stop:
70 raise _FitLimit
71 self.calls += 1
72 self.coefficients[self.nonlinear] = theta
73 x, y = self.fitter.x, self.fitter.y
74 predictions = _evaluate(self.program, x, self.coefficients, self.affine)
75
76 if self.affine:
77 if not np.isfinite(predictions).all():
78 return self.penalty
79 offset, design = predictions[:, 0], predictions[:, 1:]
80 with np.errstate(over="ignore", invalid="ignore"):
81 target = y - offset
82 if not np.isfinite(target).all():
83 return self.penalty
84 try:
85 linear, _, _, _ = np.linalg.lstsq(design, target, rcond=None)
86 except np.linalg.LinAlgError:
87 return self.penalty
88 if not np.isfinite(linear).all():
89 return self.penalty
90 self.coefficients[list(self.affine)] = linear
91 with np.errstate(over="ignore", invalid="ignore"):
92 predictions = offset + design @ linear
93
94 rmse = _rmse(predictions, y)
95 if not isfinite(rmse):
96 return self.penalty
97 if rmse < self.best_rmse:
98 self.best_rmse = rmse
99 self.best_coefficients = tuple(map(float, self.coefficients))
100
101 # Keep exploratory residuals finite even when a trial is far outside
102 # the scale of the targets. Track the actual error above.
103 with np.errstate(over="ignore", under="ignore"):
104 residuals = (predictions - y) / self.fitter.scale
105 return np.clip(residuals, -1e5, 1e5)
106
107 def starts(self, count, seed):
108 lower, upper = self.fitter.bounds
109 initial = np.full(len(self.nonlinear), np.clip(1., lower, upper))
110 yield initial
111 if count == 1:
112 return
113 rng = np.random.default_rng(seed)
114 if len(self.nonlinear) == 1:
115 # Stratify one-dimensional restarts, including periodic fits.
116 fractions = (np.arange(count - 1) + rng.random(count - 1)) / (count - 1)
117 yield from (lower + (upper - lower) * fractions[:, None])
118 else:
119 yield from rng.uniform(lower, upper, size=(count - 1, len(initial)))
120
121 def solve(self, expression, seed):
122 if not self.nonlinear:
123 self.objective(())
124 else:
125 total = self.stop
126 count = min(self.fitter.restarts, total)
127 for i, initial in enumerate(self.starts(count, seed)):
128 # Include every numerical Jacobian call in the budget.
129 self.stop = self.calls + (total - self.calls) // (count - i)
130 try:
131 least_squares(self.objective, initial, bounds=self.fitter.bounds)
132 except _FitLimit:
133 pass
134
135 best = self.best_coefficients
136 rmse = self.best_rmse
137 if best is not None and self.affine:
138 self.calls += 1
139 values = _evaluate(self.program, self.fitter.x, best)
140 rmse = _rmse(values, self.fitter.y)
141 model = FittedExpression(expression, best, rmse) if isfinite(rmse) else None
142 return CoefficientFit(model, self.calls)
143
144
145
154def fit_expression(expression: Expression, X, y, *,
155 nonlinear_bounds=(-20., 20.), max_evaluations: int = 48,
156 restarts: int = 4, seed: int | None = None) -> CoefficientFit:
157 """Fit an expression's free scalars on one finite data matrix.
158
159 X has shape (samples, variables) and y has one real target per row.
160 Solve the structurally affine coefficients together by SVD least
161 squares. For mixed expressions, repeat that solve inside a bounded
162 SciPy least-squares search over the remaining coefficients (variable
163 projection). Bounds apply only to nonlinear coefficients.
164
165 The evaluation limit includes finite differences and the final check
166 in the original expression. Restarts divide that budget between
167 starting points. The seed controls randomized start locations. A
168 missing model indicates that the fit found no finite solution on all
169 training rows within the budget. Nonlinear fitting can terminate at a
170 local optimum.
171 """
172 if not isinstance(expression, Expression):
173 raise TypeError("expression must be an Expression.")
174 x = _matrix(X)
175 fitter = _Fitter(x, _target(y, len(x)), nonlinear_bounds, max_evaluations, restarts)
176 return fitter.fit(expression, seed)
A fitted expression with independently usable NumPy inference.
One coefficient fit and its measured training evaluation cost.
Definition _fit.py:17
starts(self, count, seed)
Definition _fit.py:107