.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/02_gp/plot_10_library_learning.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_02_gp_plot_10_library_learning.py: Library learning: reusing building blocks (new in eqdisco) ========================================================== Many laws repeat a motif: a sum of exponentials, a ratio of polynomials, a product appearing twice. With ``library_learning=True`` eqdisco periodically mines the frequent subtrees of the best individuals (:func:`~eqdisco.analysis.mine_library`) and inserts them into new offspring, so that a block found once can be reused elsewhere in the tree. The target repeats the block :math:`m=x_0x_1+x_2` three times: :math:`y=m^2+\sin m+m\,x_3`. .. GENERATED FROM PYTHON SOURCE LINES 12-24 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq rng = np.random.default_rng(0) X = rng.uniform(-1.5, 1.5, (250, 4)) m = X[:, 0] * X[:, 1] + X[:, 2] y = m**2 + np.sin(m) + m * X[:, 3] funcs = ("add", "sub", "mul", "sin") .. GENERATED FROM PYTHON SOURCE LINES 25-27 With and without the library ---------------------------- .. GENERATED FROM PYTHON SOURCE LINES 27-49 .. code-block:: Python runs = {} for lib in (False, True): runs[lib] = [eq.SymbolicRegressor(population_size=250, generations=30, functions=funcs, library_learning=lib, library_interval=3, p_library=0.05, random_state=s).fit(X, y) for s in range(6)] learned = eq.analysis.mine_library([r.ind for r in runs[True][0]._final_population[:50]], max_blocks=5) print("library of run 0:", [str(blk) for blk in learned]) for lib in (False, True): print("with library" if lib else "without library", f"median final NMSE {np.median([r.history_['best_loss'].iloc[-1] for r in runs[lib]]) / np.var(y):.2e}") fig, axs = plt.subplots(1, 2, figsize=(10, 3.4)) for lib, color in ((False, "#D55E00"), (True, "#285780")): L = np.array([r.history_["best_loss"] for r in runs[lib]]) / np.var(y) for h in L: axs[0].semilogy(h, color=color, lw=0.6, alpha=0.4) axs[0].semilogy(np.median(L, 0), color=color, lw=2.2, label="with library" if lib else "without library") axs[1].scatter([r.equation_.complexity for r in runs[lib]], [max(1 - r.score(X, y), 1e-12) for r in runs[lib]], color=color, s=30) axs[0].set_xlabel("generation") axs[0].set_ylabel("normalized MSE of the best") axs[0].legend(frameon=False, fontsize=8) axs[1].set_yscale("log") axs[1].set_xlabel("size of the selected model") axs[1].set_ylabel("$1-R^2$") fig.tight_layout() .. image-sg:: /auto_examples/02_gp/images/sphx_glr_plot_10_library_learning_001.png :alt: plot 10 library learning :srcset: /auto_examples/02_gp/images/sphx_glr_plot_10_library_learning_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none library of run 0: ['x0 * x1', 'x3 * x2', 'x1 * x2', 'x2 * x2', 'x3 + x2'] without library median final NMSE 9.70e-02 with library median final NMSE 4.69e-02 .. GENERATED FROM PYTHON SOURCE LINES 50-52 Parameter study: the injection rate ----------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 52-61 .. code-block:: Python rates = [0.0, 0.02, 0.05, 0.1, 0.2] med = [np.median([eq.SymbolicRegressor(population_size=250, generations=30, functions=funcs, library_learning=p > 0, library_interval=3, p_library=p, random_state=s).fit(X, y).history_["best_loss"].iloc[-1] for s in range(3)]) for p in rates] print("injection rate", rates, "median final NMSE", [f"{m / np.var(y):.2e}" for m in med]) fig, ax = plt.subplots(figsize=(4.5, 3)) ax.plot(rates, np.array(med) / np.var(y), "o-", color="#285780") ax.set_xlabel("share of offspring built from the library") ax.set_ylabel("median final normalized MSE") ax.set_yscale("log") plt.show() .. image-sg:: /auto_examples/02_gp/images/sphx_glr_plot_10_library_learning_002.png :alt: plot 10 library learning :srcset: /auto_examples/02_gp/images/sphx_glr_plot_10_library_learning_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none injection rate [0.0, 0.02, 0.05, 0.1, 0.2] median final NMSE ['5.06e-02', '4.58e-02', '4.18e-02', '4.22e-02', '2.98e-02'] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 29.832 seconds) .. _sphx_glr_download_auto_examples_02_gp_plot_10_library_learning.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/02_gp/plot_10_library_learning.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_10_library_learning.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_10_library_learning.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_10_library_learning.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_