Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Cooperative GP with OLS credit assignment (new in eqdisco)#
In CooperativeOLSRegressor the population is a shared library
of basis functions. Each generation, forward orthogonal least squares selects the
subset that best explains the data; selected individuals earn their ERR, the
others the share of the residual they could explain, so the population keeps
searching for what the model still misses. The selection path gives nested models
of every size, a Pareto front at no extra cost. The target mixes a periodic, a
multiplicative and a rational term.
import matplotlib.pyplot as plt
import numpy as np
import eqdisco as eq
rng = np.random.default_rng(4)
X = rng.uniform(-2, 2, (300, 3))
y = 2 * np.sin(X[:, 0]) + X[:, 1] * X[:, 2] + 1 / (1 + X[:, 2] ** 2) + 0.01 * rng.normal(size=300)
A cooperative run#
coop = eq.CooperativeOLSRegressor(population_size=150, generations=30, max_terms=6, random_state=0).fit(X, y)
print(coop.equation_)
print(coop.history_.tail(3))
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
h = coop.history_
axs[0].semilogy(h["generation"], 1 - h["r2"], color="#285780", lw=2, label="$1-R^2$ of the current model")
ax2 = axs[0].twinx()
ax2.step(h["generation"], h["n_terms"], color="#D55E00", where="post")
ax2.set_ylabel("terms in the model", color="#D55E00")
axs[0].set_xlabel("generation")
axs[0].legend(frameon=False, fontsize=8)
eq.viz.plot_pareto(coop, ax=axs[1], annotate=True, max_labels=4)
fig.tight_layout()

-2.695 + 2 * sin(x0) + 1 * x1 * x2 + 4.35 * sin(cos(sin(sqrt(x2)))) + 0.5849 * sin(sqrt(x2)) + 0.03112 * sin(cos(log(x2))) - 0.02022 * cos(x2^2)
generation r2 bic n_terms best_bic library
28 28 0.999712 -1122.677185 6 -1836.698882 75
29 29 0.999712 -1122.677185 6 -1836.698882 88
30 30 0.999712 -1122.677185 6 -1836.698882 85
Parameter study: library size#
sizes = [40, 80, 150, 300]
med = [np.median([1 - eq.CooperativeOLSRegressor(population_size=s, generations=20, random_state=k).fit(X, y).score(X, y) for k in range(3)]) for s in sizes]
print("population", sizes, "median 1-R2", [f"{v:.1e}" for v in med])
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(sizes, med, "o-", color="#285780")
ax.set_yscale("log")
ax.set_xlabel("population (library) size")
ax.set_ylabel("median $1-R^2$")
plt.show()

population [40, 80, 150, 300] median 1-R2 ['2.6e-05', '2.6e-05', '2.5e-05', '2.5e-05']
Total running time of the script: (0 minutes 2.461 seconds)