Model families: how many different models do the data support? (new in eqdisco)#

The models of a Pareto front, of an ensemble or of repeated runs often compute nearly the same function in different forms. Grouping them by their predictions (model_families()) shows how many genuinely different explanations remain. With noisy data from Nguyen-5, \(\sin(x^2)\cos x-1\), on a narrow range, several families fit equally well inside the data but differ outside – a warning against over-interpreting one of them.

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import model_families

rng = np.random.default_rng(0)
x = rng.uniform(-1, 1, 60)
y = np.sin(x**2) * np.cos(x) - 1 + 0.02 * rng.normal(size=60)
X = x.reshape(-1, 1)

Models of ten runs#

models = []
for s in range(10):
    sr = eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "sin", "cos", "exp"), random_state=s).fit(X, y)
    models += [e for e in sr.pareto_front_ if e.metrics["r2"] > 0.9]
labels, table, Z = model_families(models, X, y, threshold=0.05)
print(len(models), "models,", len(table), "families")
print(table.head(6).to_string())
eq.viz.plot_families(models, X, y, threshold=0.05)
fig, ax = plt.subplots(figsize=(6, 3.4))
xs = np.linspace(-2, 2, 300).reshape(-1, 1)
ax.axvspan(-1, 1, color="#E3E7EB", label="range of the data")
ax.scatter(x, y, s=8, color="#6B7785")
for k, r in table.head(4).iterrows():
    e = models[int(r["rep_index"])]
    ax.plot(xs, e.predict(xs), color=eq.viz.OKABE_ITO[k], lw=1.5, label=f"family {k}: {str(e)[:30]}")
ax.set_ylim(-3, 1)
ax.set_xlabel("x")
ax.legend(frameon=False, fontsize=7)
  • dendrogram of candidate models, map of models (MDS)
  • plot 36 model families
82 models, 3 families
   family  size                       representative  complexity  best_mse  rep_index
0       0    60  -1.318 + 0.7974 * sin(exp(cos(x0)))           8  0.000313          2
1       1    12        0.4893 - 1.455 * cos(sin(x0))           7  0.000533          1
2       2    10             0.1314 - 1.078 * cos(x0)           6  0.001455          0

<matplotlib.legend.Legend object at 0x72b441875670>

Parameter study: the distance threshold#

ths = [0.01, 0.02, 0.05, 0.1, 0.2]
print("threshold", ths, "families", [len(model_families(models, X, y, threshold=t)[1]) for t in ths])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(ths, [len(model_families(models, X, y, threshold=t)[1]) for t in ths], "o-", color="#285780")
ax.set_xscale("log")
ax.set_xlabel("distance threshold")
ax.set_ylabel("number of families")
plt.show()
plot 36 model families
threshold [0.01, 0.02, 0.05, 0.1, 0.2] families [19, 11, 3, 2, 1]

Total running time of the script: (0 minutes 4.178 seconds)

Gallery generated by Sphinx-Gallery