.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/05_probabilistic/plot_19_bayesian.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_05_probabilistic_plot_19_bayesian.py: Bayesian sampling of model structures ===================================== How certain is a discovered law? :class:`~eqdisco.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 :math:`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, :math:`v=V_{\max}S/(K_m+S)`. .. GENERATED FROM PYTHON SOURCE LINES 13-24 .. code-block:: Python 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) .. GENERATED FROM PYTHON SOURCE LINES 25-27 Sampling -------- .. GENERATED FROM PYTHON SOURCE LINES 27-47 .. code-block:: Python 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() .. image-sg:: /auto_examples/05_probabilistic/images/sphx_glr_plot_19_bayesian_001.png :alt: plot 19 bayesian :srcset: /auto_examples/05_probabilistic/images/sphx_glr_plot_19_bayesian_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 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] .. GENERATED FROM PYTHON SOURCE LINES 48-50 Parameter study: the prior penalty per operation ------------------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 50-61 .. code-block:: Python 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() .. image-sg:: /auto_examples/05_probabilistic/images/sphx_glr_plot_19_bayesian_002.png :alt: plot 19 bayesian :srcset: /auto_examples/05_probabilistic/images/sphx_glr_plot_19_bayesian_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 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} .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 3.962 seconds) .. _sphx_glr_download_auto_examples_05_probabilistic_plot_19_bayesian.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/eqdisco/main?urlpath=lab/tree/notebooks/auto_examples/05_probabilistic/plot_19_bayesian.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_19_bayesian.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_19_bayesian.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_19_bayesian.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_