Bayesian sampling of model structures#

How certain is a discovered law? BayesianSymbolicRegressor samples expressions by Metropolis moves with parallel tempering. The energy is half the Bayesian information criterion plus a prior that charges every operation, so that \(e^{-E}\) approximates the posterior probability of a structure – the idea of the Bayesian machine scientist (Guimerà et al., 2020). The posterior is estimated over the visited structures from their energies. The data: twenty noisy rates of an enzyme reaction obeying Michaelis–Menten kinetics, \(v=V_{\max}S/(K_m+S)\).

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq

rng = np.random.default_rng(6)
S = np.sort(rng.uniform(0.05, 5, 20))
v = 2.0 * S / (0.6 + S) * (1 + 0.03 * rng.normal(size=20))
X = S.reshape(-1, 1)

Sampling#

bms = eq.BayesianSymbolicRegressor(functions=("add", "sub", "mul", "div", "exp", "log"), n_steps=2500, temperatures=(1.0, 1.6, 2.6, 4.2), feature_names=["S"], random_state=0)
bms.fit(X, v)
print(bms.posterior_.head(6)[["equation", "posterior", "share", "energy", "size"]])
print("MAP model:", bms.equation_, "| acceptance:", np.round(bms.acceptance_, 2))
fig, axs = plt.subplots(1, 3, figsize=(13, 3.4), gridspec_kw={"width_ratios": [1, 1.4, 1]})
axs[0].plot(bms.trace_["energy"], color="#285780", lw=0.7)
axs[0].set_xlabel("step")
axs[0].set_ylabel("energy of the T = 1 chain")
eq.viz.plot_posterior(bms.posterior_, top=8, ax=axs[1])
s = np.linspace(0, 5, 200).reshape(-1, 1)
axs[2].scatter(S, v, color="#6B7785", s=15, label="data")
for k in range(3):
    e = bms.posterior_.iloc[k]
    f = bms._eq(e["expression"])
    axs[2].plot(s, f.predict(s), color=eq.viz.OKABE_ITO[k], lw=1.4, label=f"{e['posterior']:.2f}: {e['equation'][:22]}")
axs[2].set_xlabel("substrate S")
axs[2].set_ylabel("rate v")
axs[2].legend(frameon=False, fontsize=6.5)
fig.tight_layout()
plot 19 bayesian
                            equation  posterior   share     energy  size
0             (S + S) / (0.6088 + S)   0.288288  0.0325 -28.880849     7
1               S / S / (0.7345 + S)   0.257048  0.0770 -28.766153     7
2       (S + S) / (S + exp(-0.4963))   0.106055  0.0115 -27.880849     8
3         S / S / (S + exp(-0.3088))   0.094797  0.0235 -27.768626     8
4  (S + S) / (S + exp(log(-0.6088)))   0.039016  0.0155 -26.880849     9
5    S / S / (S + exp(log(-0.7343)))   0.034877  0.0005 -26.768709     9
MAP model: -0.002261 + 1.003 * (S + S) / (0.6088 + S) | acceptance: [0.31 0.33 0.33 0.35]

Parameter study: the prior penalty per operation#

pens = [0.0, 1.0, 3.0]
fig, ax = plt.subplots(figsize=(4.5, 3))
for k, p in enumerate(pens):
    b = eq.BayesianSymbolicRegressor(functions=("add", "sub", "mul", "div", "exp", "log"), n_steps=1200, prior_penalty=p, random_state=0).fit(X, v)
    by_size = b.posterior_.groupby("size")["posterior"].sum()
    print(f"penalty {p}: posterior mass by size", {int(k): round(float(v), 3) for k, v in by_size.items() if v > 0.01})
    ax.plot(by_size.index, by_size.to_numpy(), "o-", color=eq.viz.OKABE_ITO[k], ms=3, label=f"penalty {p}")
ax.set_xlabel("size of the structures")
ax.set_ylabel("posterior probability")
ax.legend(frameon=False, fontsize=8)
plt.show()
plot 19 bayesian
penalty 0.0: posterior mass by size {2: 0.01, 4: 0.081, 5: 0.026, 6: 0.236, 7: 0.01, 8: 0.145, 9: 0.035, 10: 0.249, 11: 0.154, 12: 0.031, 13: 0.01}
penalty 1.0: posterior mass by size {2: 0.029, 4: 0.046, 6: 0.085, 7: 0.033, 8: 0.578, 9: 0.206, 13: 0.014}
penalty 3.0: posterior mass by size {2: 0.816, 4: 0.181}

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

Gallery generated by Sphinx-Gallery