# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Budgeted coefficient fitting with variable projection.
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from scipy.optimize import least_squares
from ._expression import Expression, FittedExpression, _compile, _evaluate, _matrix, _rmse, _target
## @brief One coefficient fit and its measured training evaluation cost.
[docs]
@dataclass(frozen=True, slots=True)
class CoefficientFit:
"""Report a fitted model or None if no finite fit was found within the budget."""
model: FittedExpression | None
evaluations: int
class _FitLimit(Exception):
"""Stop SciPy before another finite difference call exceeds the allotted budget."""
def _integer(value, name, minimum):
value = index(value)
if value < minimum:
raise ValueError(f"{name} must be at least {minimum}.")
return value
class _Fitter:
def __init__(self, x, y, bounds, budget, restarts):
lower, upper = map(float, bounds)
if not isfinite(upper - lower) or not lower < upper:
raise ValueError("Nonlinear bounds need a finite, positive width.")
self.x = x
self.y = y
self.bounds = lower, upper
self.budget = _integer(budget, "max_evaluations", 2)
self.restarts = _integer(restarts, "restarts", 1)
self.scale = float(np.max(np.abs(y))) or 1.
def fit(self, expression, seed):
program, linear, count, n_variables = _compile(expression)
if self.x.shape[1] < n_variables:
raise ValueError(f"The expression needs at least {n_variables} input columns.")
problem = _FitProblem(self, program, linear, count)
return problem.solve(expression, seed)
class _FitProblem:
def __init__(self, fitter, program, linear, count):
self.fitter = fitter
self.program = program
self.affine = {slot: column for column, slot in enumerate(linear, 1)}
self.nonlinear = [slot for slot in range(count) if slot not in self.affine]
self.coefficients = np.zeros(count)
self.calls = 0
self.stop = fitter.budget - bool(linear)
self.best_rmse = float("inf")
self.best_coefficients = None
self.penalty = np.full_like(fitter.y, 1e6)
def objective(self, theta):
if self.calls >= self.stop:
raise _FitLimit
self.calls += 1
self.coefficients[self.nonlinear] = theta
x, y = self.fitter.x, self.fitter.y
predictions = _evaluate(self.program, x, self.coefficients, self.affine)
if self.affine:
if not np.isfinite(predictions).all():
return self.penalty
offset, design = predictions[:, 0], predictions[:, 1:]
with np.errstate(over="ignore", invalid="ignore"):
target = y - offset
if not np.isfinite(target).all():
return self.penalty
try:
linear, _, _, _ = np.linalg.lstsq(design, target, rcond=None)
except np.linalg.LinAlgError:
return self.penalty
if not np.isfinite(linear).all():
return self.penalty
self.coefficients[list(self.affine)] = linear
with np.errstate(over="ignore", invalid="ignore"):
predictions = offset + design @ linear
rmse = _rmse(predictions, y)
if not isfinite(rmse):
return self.penalty
if rmse < self.best_rmse:
self.best_rmse = rmse
self.best_coefficients = tuple(map(float, self.coefficients))
# Keep exploratory residuals finite even when a trial is far outside
# the scale of the targets. Track the actual error above.
with np.errstate(over="ignore", under="ignore"):
residuals = (predictions - y) / self.fitter.scale
return np.clip(residuals, -1e5, 1e5)
def starts(self, count, seed):
lower, upper = self.fitter.bounds
initial = np.full(len(self.nonlinear), np.clip(1., lower, upper))
yield initial
if count == 1:
return
rng = np.random.default_rng(seed)
if len(self.nonlinear) == 1:
# Stratify one-dimensional restarts, including periodic fits.
fractions = (np.arange(count - 1) + rng.random(count - 1)) / (count - 1)
yield from (lower + (upper - lower) * fractions[:, None])
else:
yield from rng.uniform(lower, upper, size=(count - 1, len(initial)))
def solve(self, expression, seed):
if not self.nonlinear:
self.objective(())
else:
total = self.stop
count = min(self.fitter.restarts, total)
for i, initial in enumerate(self.starts(count, seed)):
# Include every numerical Jacobian call in the budget.
self.stop = self.calls + (total - self.calls) // (count - i)
try:
least_squares(self.objective, initial, bounds=self.fitter.bounds)
except _FitLimit:
pass
best = self.best_coefficients
rmse = self.best_rmse
if best is not None and self.affine:
self.calls += 1
values = _evaluate(self.program, self.fitter.x, best)
rmse = _rmse(values, self.fitter.y)
model = FittedExpression(expression, best, rmse) if isfinite(rmse) else None
return CoefficientFit(model, self.calls)
## @brief Fit free expression coefficients on labeled training data.
# @param expression The tree whose free coefficients are to be fitted.
# @param X Finite sample matrix.
# @param y Finite target vector.
# @param nonlinear_bounds Shared lower and upper bounds for nonlinear coefficients.
# @param max_evaluations Hard cap on expression evaluations in the fit.
# @param restarts Number of starts that share the evaluation cap.
# @param seed Seed for nonlinear restart locations.
# @return A fitted model, when feasible, and the actual evaluation count.
[docs]
def fit_expression(expression: Expression, X, y, *,
nonlinear_bounds=(-20., 20.), max_evaluations: int = 48,
restarts: int = 4, seed: int | None = None) -> CoefficientFit:
"""Fit an expression's free scalars on one finite data matrix.
X has shape (samples, variables) and y has one real target per row.
Solve the structurally affine coefficients together by SVD least
squares. For mixed expressions, repeat that solve inside a bounded
SciPy least-squares search over the remaining coefficients (variable
projection). Bounds apply only to nonlinear coefficients.
The evaluation limit includes finite differences and the final check
in the original expression. Restarts divide that budget between
starting points. The seed controls randomized start locations. A
missing model indicates that the fit found no finite solution on all
training rows within the budget. Nonlinear fitting can terminate at a
local optimum.
"""
if not isinstance(expression, Expression):
raise TypeError("expression must be an Expression.")
x = _matrix(X)
fitter = _Fitter(x, _target(y, len(x)), nonlinear_bounds, max_evaluations, restarts)
return fitter.fit(expression, seed)