QDpy
Loading...
Searching...
No Matches
symbolic_regression.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Fit a short, noisy series and plot plausible equations beyond its observed range."""
6
7import argparse
8from dataclasses import asdict
9import json
10from pathlib import Path
11
12import numpy as np
13
14from qdpy.symbolic import symbolic_regression
15
16
17
18def select_equations(models, x_validation, y_validation, probes, *, tolerance=.025, limit=6):
19 """Start with the validation winner and greedily add distinct probe curves."""
20 ranked = sorted(((model.rmse(x_validation, y_validation), model) for model in models),
21 key=lambda pair: (pair[0], pair[1].expression.node_count))
22 if not ranked or not np.isfinite(ranked[0][0]):
23 return ()
24 error, winner = ranked[0]
25 alternatives = [model for score, model in ranked[1:] if score <= error + tolerance]
26 selected = [winner]
27 predictions = np.asarray([model.predict(probes) for model in [winner, *alternatives]])
28 # Compress extreme predictions with the same bounded transformation as the archive.
29 profiles = np.arctan2(predictions, np.max(np.abs(y_validation)) or 1.)
30 nearest = np.linalg.norm(profiles[1:] - profiles[0], axis=1)
31 while len(selected) < limit and nearest.size:
32 index = int(np.argmax(nearest))
33 if nearest[index] < 1e-6:
34 break
35 selected.append(alternatives[index])
36 distances = np.linalg.norm(profiles[1:] - profiles[index + 1], axis=1)
37 nearest = np.minimum(nearest, distances)
38 return tuple(selected)
39
40
41
42def run(mode="semantic", seed=11, budget=1200, plot=None):
43 """Fit noisy observations of a saturating response on the interval [0, 0.6]."""
44 rng = np.random.default_rng(319)
45 training = np.linspace(0., .6, 37)[:, None]
46 validation = np.linspace(.007, .593, 32)[:, None]
47 probes = np.linspace(.72, 3., 6)[:, None]
48
49 def measure(x):
50 value = 1.5 * x[:, 0] / (1. + .75 * x[:, 0])
51 return value + rng.normal(0., .014, len(x))
52
53 y_train, y_val = measure(training), measure(validation)
54 result = symbolic_regression(training, y_train, mode=mode, probes=probes, seed=seed,
55 operators=("add", "sub", "mul", "div", "square", "exp", "log"),
56 budget=budget, cells=40, fit_evaluations=64)
57 selected = select_equations(result.models, validation, y_val, probes)
58
59 if plot is not None:
60 import matplotlib.pyplot as plt
61
62 curve = np.linspace(0., probes[-1, 0], 401)[:, None]
63 fig, (fit, forecast) = plt.subplots(ncols=2, figsize=(9, 4))
64 for i, model in enumerate(selected, 1):
65 fit.plot(training[:, 0], model.predict(training))
66 forecast.plot(curve[:, 0], model.predict(curve), label=f"Equation {i}")
67 fit.scatter(training[:, 0], y_train, c=".15", s=9, zorder=10, label="Training data")
68 fit.set(title="Observed range", xlabel="Input", ylabel="Response")
69 forecast.axvspan(training.min(), training.max(), color=".93")
70 forecast.set(title="Extrapolation", xlabel="Input", ylabel="Predicted response")
71 forecast.set_yscale("symlog", linthresh=.1, linscale=1.5)
72 forecast.legend(loc="best", fontsize="small")
73 fig.tight_layout()
74 fig.savefig(plot, dpi=150)
75 plt.close(fig)
76
77 return dict(mode=mode, seed=seed, retained=len(result.models), stats=asdict(result.stats),
78 equations=[dict(formula=model.formula, validation_rmse=model.rmse(validation, y_val),
79 predictions=model.predict(probes).tolist()) for model in selected],
80 probe_inputs=probes[:, 0].tolist())
81
82
83if __name__ == "__main__":
84 parser = argparse.ArgumentParser(description=__doc__)
85 parser.add_argument("--mode", choices=("structural", "semantic", "gp"), default="semantic")
86 parser.add_argument("--seed", type=int, default=11)
87 parser.add_argument("--budget", type=int, default=1200)
88 parser.add_argument("--plot", type=Path)
89 args = parser.parse_args()
90 print(json.dumps(run(args.mode, args.seed, args.budget, args.plot), indent=2, allow_nan=False))