12from ._expression
import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
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.")
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.
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.")
52 return problem.solve(expression, seed)
56 def __init__(self, fitter, program, linear, count):
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]
63 self.
stop = fitter.budget - bool(linear)
66 self.
penalty = np.full_like(fitter.y, 1e6)
68 def objective(self, theta):
77 if not np.isfinite(predictions).all():
79 offset, design = predictions[:, 0], predictions[:, 1:]
80 with np.errstate(over=
"ignore", invalid=
"ignore"):
82 if not np.isfinite(target).all():
85 linear, _, _, _ = np.linalg.lstsq(design, target, rcond=
None)
86 except np.linalg.LinAlgError:
88 if not np.isfinite(linear).all():
91 with np.errstate(over=
"ignore", invalid=
"ignore"):
92 predictions = offset + design @ linear
94 rmse = _rmse(predictions, y)
95 if not isfinite(rmse):
103 with np.errstate(over=
"ignore", under=
"ignore"):
104 residuals = (predictions - y) / self.
fitter.scale
105 return np.clip(residuals, -1e5, 1e5)
107 def starts(self, count, seed):
108 lower, upper = self.
fitter.bounds
109 initial = np.full(len(self.
nonlinear), np.clip(1., lower, upper))
113 rng = np.random.default_rng(seed)
116 fractions = (np.arange(count - 1) + rng.random(count - 1)) / (count - 1)
117 yield from (lower + (upper - lower) * fractions[:,
None])
119 yield from rng.uniform(lower, upper, size=(count - 1, len(initial)))
121 def solve(self, expression, seed):
126 count = min(self.
fitter.restarts, total)
127 for i, initial
in enumerate(self.
starts(count, seed)):
137 if best
is not None and self.
affine:
140 rmse = _rmse(values, self.
fitter.y)
141 model =
FittedExpression(expression, best, rmse)
if isfinite(rmse)
else None
154def fit_expression(expression: Expression, X, y, *,
155 nonlinear_bounds=(-20., 20.), max_evaluations: int = 48,
175 fitter =
_Fitter(x, _target(y, len(x)), nonlinear_bounds, max_evaluations, restarts)