# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Visualize extrapolation disagreement in a symbolic regression archive. """Fit a short, noisy series and plot plausible equations beyond its observed range.""" import argparse from dataclasses import asdict import json from pathlib import Path import numpy as np from qdpy.symbolic import symbolic_regression ## @brief Choose validation-competitive equations that disagree on unlabeled probes. def select_equations(models, x_validation, y_validation, probes, *, tolerance=.025, limit=6): """Start with the validation winner and greedily add distinct probe curves.""" ranked = sorted(((model.rmse(x_validation, y_validation), model) for model in models), key=lambda pair: (pair[0], pair[1].expression.node_count)) if not ranked or not np.isfinite(ranked[0][0]): return () error, winner = ranked[0] alternatives = [model for score, model in ranked[1:] if score <= error + tolerance] selected = [winner] predictions = np.asarray([model.predict(probes) for model in [winner, *alternatives]]) # Compress extreme predictions with the same bounded transformation as the archive. profiles = np.arctan2(predictions, np.max(np.abs(y_validation)) or 1.) nearest = np.linalg.norm(profiles[1:] - profiles[0], axis=1) while len(selected) < limit and nearest.size: index = int(np.argmax(nearest)) if nearest[index] < 1e-6: break selected.append(alternatives[index]) distances = np.linalg.norm(profiles[1:] - profiles[index + 1], axis=1) nearest = np.minimum(nearest, distances) return tuple(selected) ## @brief Run one seeded search and report equations selected on validation error. def run(mode="semantic", seed=11, budget=1200, plot=None): """Fit noisy observations of a saturating response on the interval [0, 0.6].""" rng = np.random.default_rng(319) training = np.linspace(0., .6, 37)[:, None] validation = np.linspace(.007, .593, 32)[:, None] probes = np.linspace(.72, 3., 6)[:, None] def measure(x): value = 1.5 * x[:, 0] / (1. + .75 * x[:, 0]) return value + rng.normal(0., .014, len(x)) y_train, y_val = measure(training), measure(validation) result = symbolic_regression(training, y_train, mode=mode, probes=probes, seed=seed, operators=("add", "sub", "mul", "div", "square", "exp", "log"), budget=budget, cells=40, fit_evaluations=64) selected = select_equations(result.models, validation, y_val, probes) if plot is not None: import matplotlib.pyplot as plt curve = np.linspace(0., probes[-1, 0], 401)[:, None] fig, (fit, forecast) = plt.subplots(ncols=2, figsize=(9, 4)) for i, model in enumerate(selected, 1): fit.plot(training[:, 0], model.predict(training)) forecast.plot(curve[:, 0], model.predict(curve), label=f"Equation {i}") fit.scatter(training[:, 0], y_train, c=".15", s=9, zorder=10, label="Training data") fit.set(title="Observed range", xlabel="Input", ylabel="Response") forecast.axvspan(training.min(), training.max(), color=".93") forecast.set(title="Extrapolation", xlabel="Input", ylabel="Predicted response") forecast.set_yscale("symlog", linthresh=.1, linscale=1.5) forecast.legend(loc="best", fontsize="small") fig.tight_layout() fig.savefig(plot, dpi=150) plt.close(fig) return dict(mode=mode, seed=seed, retained=len(result.models), stats=asdict(result.stats), equations=[dict(formula=model.formula, validation_rmse=model.rmse(validation, y_val), predictions=model.predict(probes).tolist()) for model in selected], probe_inputs=probes[:, 0].tolist()) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--mode", choices=("structural", "semantic", "gp"), default="semantic") parser.add_argument("--seed", type=int, default=11) parser.add_argument("--budget", type=int, default=1200) parser.add_argument("--plot", type=Path) args = parser.parse_args() print(json.dumps(run(args.mode, args.seed, args.budget, args.plot), indent=2, allow_nan=False))