.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/09_analysis/plot_32_simplification.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_09_analysis_plot_32_simplification.py: Simplification of evolved models ================================ Evolved expressions carry introns and redundant parameters. The simplification pipeline (:func:`eqdisco.simplify.simplify`) folds constant subtrees, rewrites identities, merges parameters of addition and multiplication chains (a rule-based form of the parameter reduction of de França and Kronberger, 2023), optionally calls SymPy, refits and rounds the coefficients. The function is unchanged except for the final rounding, which is checked against a tolerance on the error. .. GENERATED FROM PYTHON SOURCE LINES 12-23 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq from eqdisco.optimize import jacobian_rank from eqdisco.simplify import apply_rules, simplify prob = eq.datasets.get_problem("keijzer-12", noise=0.01) sr = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div"), max_size=80, random_state=0).fit(prob.X_train, prob.y_train) .. GENERATED FROM PYTHON SOURCE LINES 24-26 One model before and after -------------------------- .. GENERATED FROM PYTHON SOURCE LINES 26-50 .. code-block:: Python raw = max(sr.pareto_front_, key=lambda e: e.complexity) clean = simplify(raw, prob.X_train, prob.y_train, sympy=True, refit=True, round_digits=True) print("before:", raw.complexity, "nodes,", raw.n_params, "parameters (rank", jacobian_rank(raw.expr, prob.X_train), ")") print(" ", raw) print("after: ", clean.complexity, "nodes,", clean.n_params, "parameters") print(" ", clean) fig, axs = plt.subplots(1, 2, figsize=(10, 3.4)) pop = sr.population_[:120] before = np.array([e.complexity for e in pop]) after = np.array([apply_rules(e).complexity for e in pop]) axs[0].scatter(before, after, s=12, color="#285780", alpha=0.6) axs[0].plot([0, before.max()], [0, before.max()], color="#6B7785", ls="--", lw=1) axs[0].set_xlabel("size before (nodes)") axs[0].set_ylabel("size after rules (nodes)") axs[0].set_title(f"population: mean reduction {100 * (1 - after.sum() / before.sum()):.0f} %", fontsize=9) p_before = np.array([e.n_params for e in pop]) p_rank = np.array([jacobian_rank(e.expr, prob.X_train) for e in pop]) axs[1].scatter(p_before + np.random.default_rng(0).uniform(-0.2, 0.2, len(pop)), p_rank, s=12, color="#D55E00", alpha=0.6) axs[1].plot([0, p_before.max()], [0, p_before.max()], color="#6B7785", ls="--", lw=1) axs[1].set_xlabel("parameters in the expression") print(f"population: mean size before {before.mean():.1f}, after {after.mean():.1f}; parameters {p_before.sum()}, identifiable {p_rank.sum()}") axs[1].set_ylabel("rank of the Jacobian (identifiable)") fig.tight_layout() .. image-sg:: /auto_examples/09_analysis/images/sphx_glr_plot_32_simplification_001.png :alt: population: mean reduction 56 % :srcset: /auto_examples/09_analysis/images/sphx_glr_plot_32_simplification_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none before: 45 nodes, 3 parameters (rank 3 ) 1.735 - 0.9978 * (x0 * x0 + x1 - (x0 + x1 - x0 + x0 * x0 - (x0 * x0 - x0)) / (x0 - x0) * (x0 * x0 * x0 - (0.9974 * x0 * x0 - x0)) * x0) after: 16 nodes, 4 parameters 1 * x0^4 - 0.99 * x0^3 - 0.89 * x1 + 1.7 population: mean size before 46.5, after 20.6; parameters 307, identifiable 254 .. GENERATED FROM PYTHON SOURCE LINES 51-53 Parameter study: rounding tolerance ----------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 53-68 .. code-block:: Python from eqdisco.simplify import round_coefficients # noqa: E402 unrounded = simplify(raw, prob.X_train, prob.y_train, sympy=True, refit=True) tols = [0.0, 0.001, 0.01, 0.1] digits = [] for t in tols: r = round_coefficients(unrounded, prob.X_train, prob.y_train, tolerance=t) digits.append(np.mean([len(f"{abs(v):g}".replace(".", "").lstrip("0")) for v in r.theta])) print("tolerance", tols, "mean significant digits", np.round(digits, 2).tolist()) fig, ax = plt.subplots(figsize=(4.5, 3)) ax.plot(tols, digits, "o-", color="#285780") ax.set_xscale("symlog", linthresh=1e-3) ax.set_xlabel("allowed relative increase of the MSE") ax.set_ylabel("mean significant digits") plt.show() .. image-sg:: /auto_examples/09_analysis/images/sphx_glr_plot_32_simplification_002.png :alt: plot 32 simplification :srcset: /auto_examples/09_analysis/images/sphx_glr_plot_32_simplification_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none tolerance [0.0, 0.001, 0.01, 0.1] mean significant digits [6.0, 2.75, 1.75, 1.0] .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.227 seconds) .. _sphx_glr_download_auto_examples_09_analysis_plot_32_simplification.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/09_analysis/plot_32_simplification.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_32_simplification.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_32_simplification.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_32_simplification.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_