.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/02_gp/plot_06_bloat_control.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_06_bloat_control.py: Bloat and its control ===================== Programs in genetic programming tend to grow without improving: *bloat*. Larger programs are slower to evaluate, harder to read and generalize worse. This example follows the mean program size on Nguyen-6, :math:`\sin x+\sin(x+x^2)`, under four policies: no control besides the size limit, parsimony pressure (a penalty per node added to the loss), double tournament (Luke and Panait, 2002), and NSGA-II with size as a second objective. .. GENERATED FROM PYTHON SOURCE LINES 12-27 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq prob = eq.datasets.get_problem("nguyen-6") base = dict(population_size=250, generations=30, functions=("add", "sub", "mul", "sin", "cos"), max_size=80, max_depth=14) policies = { "size limit only": dict(), "parsimony 0.001": dict(parsimony=1e-3), "double tournament": dict(selection="double_tournament"), "NSGA-II (error, size)": dict(selection="nsga2"), } .. GENERATED FROM PYTHON SOURCE LINES 28-30 Mean size and accuracy ---------------------- .. GENERATED FROM PYTHON SOURCE LINES 30-50 .. code-block:: Python results = {} for name, kw in policies.items(): results[name] = [eq.SymbolicRegressor(random_state=s, **base, **kw).fit(prob.X_train, prob.y_train) for s in range(4)] for name, rr in results.items(): print(f"{name:22s} final mean size {np.mean([r.history_['mean_size'].iloc[-1] for r in rr]):5.1f} " f"median best MSE {np.median([r.history_['best_loss'].iloc[-1] for r in rr]):.2e} " f"median test 1-R2 {np.median([1 - r.equation_.score(prob.X_test, prob.y_test) for r in rr]):.2e}") fig, axs = plt.subplots(1, 2, figsize=(10, 3.4)) for k, (name, runs) in enumerate(results.items()): S = np.array([r.history_["mean_size"].to_numpy() for r in runs]) axs[0].plot(S.mean(0), color=eq.viz.OKABE_ITO[k], lw=2, label=name) L = np.array([r.history_["best_loss"].to_numpy() for r in runs]) axs[1].semilogy(np.median(L, 0), color=eq.viz.OKABE_ITO[k], lw=2, label=name) axs[0].set_xlabel("generation") axs[0].set_ylabel("mean program size (nodes)") axs[1].set_xlabel("generation") axs[1].set_ylabel("median best MSE") axs[0].legend(frameon=False, fontsize=8) fig.tight_layout() .. image-sg:: /auto_examples/02_gp/images/sphx_glr_plot_06_bloat_control_001.png :alt: plot 06 bloat control :srcset: /auto_examples/02_gp/images/sphx_glr_plot_06_bloat_control_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none size limit only final mean size 53.8 median best MSE 2.35e-05 median test 1-R2 8.53e-05 parsimony 0.001 final mean size 5.8 median best MSE 1.11e-03 median test 1-R2 1.21e-03 double tournament final mean size 16.7 median best MSE 3.10e-04 median test 1-R2 1.53e-03 NSGA-II (error, size) final mean size 15.3 median best MSE 1.10e-04 median test 1-R2 7.71e-05 .. GENERATED FROM PYTHON SOURCE LINES 51-53 Parameter study: the parsimony coefficient ------------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 53-68 .. code-block:: Python coefs = [0, 1e-4, 1e-3, 1e-2] sizes, errs = [], [] for c in coefs: rr = [eq.SymbolicRegressor(random_state=s, parsimony=c, **base).fit(prob.X_train, prob.y_train) for s in range(3)] sizes.append(np.mean([r.history_["mean_size"].iloc[-1] for r in rr])) errs.append(np.median([1 - r.equation_.score(prob.X_test, prob.y_test) for r in rr])) print("parsimony", coefs, "mean size", np.round(sizes, 1).tolist(), "median test 1-R2", [f"{e:.1e}" for e in errs]) fig, ax = plt.subplots(figsize=(4.8, 3.2)) ax.plot(sizes, errs, "o-", color="#285780") for c, s, e in zip(coefs, sizes, errs): ax.annotate(f"{c:g}", (s, e), xytext=(5, 3), textcoords="offset points", fontsize=8) ax.set_xlabel("final mean program size") ax.set_ylabel("median $1-R^2$ (test)") ax.set_yscale("log") plt.show() .. image-sg:: /auto_examples/02_gp/images/sphx_glr_plot_06_bloat_control_002.png :alt: plot 06 bloat control :srcset: /auto_examples/02_gp/images/sphx_glr_plot_06_bloat_control_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none parsimony [0, 0.0001, 0.001, 0.01] mean size [51.8, 13.6, 6.4, 4.1] median test 1-R2 ['1.3e-04', '1.0e-03', '9.6e-04', '2.6e-03'] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 20.630 seconds) .. _sphx_glr_download_auto_examples_02_gp_plot_06_bloat_control.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_06_bloat_control.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_06_bloat_control.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_06_bloat_control.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_06_bloat_control.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_