.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/08_knowledge/plot_30_shape_constraints.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_08_knowledge_plot_30_shape_constraints.py: Shape constraints for safe extrapolation ======================================== Data rarely cover the whole operating range, and a model that fits well inside the data may turn the wrong way outside. Shape-constrained symbolic regression (Kronberger et al., 2022) adds what experts know about the shape -- here that a heat-transfer coefficient increases and is concave in the flow rate -- as constraints checked over the extrapolation domain. eqdisco checks constraints by sampling inside the search and verifies the final model by interval arithmetic. .. GENERATED FROM PYTHON SOURCE LINES 12-26 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq from eqdisco.knowledge import ShapeConstraint, check_constraints rng = np.random.default_rng(3) F = rng.uniform(0.5, 3, 15) # fifteen measurements in a narrow range of flow rates h = 120 * F**0.6 * (1 + 0.05 * rng.normal(size=15)) # a Dittus-Boelter-like power law X = F.reshape(-1, 1) domain = ([0.1], [8.0]) # where the model will be used cons = [ShapeConstraint("increasing", "F", domain=domain), ShapeConstraint("concave", "F", domain=domain)] .. GENERATED FROM PYTHON SOURCE LINES 27-29 Unconstrained and constrained searches -------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 29-46 .. code-block:: Python kw = dict(population_size=300, generations=30, functions=("add", "sub", "mul", "div", "square", "sqrt"), feature_names=["F"]) free = eq.SymbolicRegressor(random_state=1, **kw).fit(X, h) safe = eq.SymbolicRegressor(constraints=cons, constraint_weight=500.0, random_state=1, **kw).fit(X, h) for name, m in (("free", free), ("constrained", safe)): print(f"{name:12s} {m.equation_} violations on [0.1, 8]:", check_constraints(m.equation_, cons, method="sampling")) fig, ax = plt.subplots(figsize=(6, 3.5)) f = np.linspace(0.1, 8, 400).reshape(-1, 1) ax.axvspan(0.5, 3, color="#E3E7EB", label="range of the data") ax.scatter(F, h, s=12, color="#6B7785") ax.plot(f, 120 * f[:, 0] ** 0.6, color="#6B7785", ls=":", label="true law") ax.plot(f, free.predict(f), color="#D55E00", lw=1.6, label="unconstrained") ax.plot(f, safe.predict(f), color="#285780", lw=1.6, label="increasing and concave") ax.set_ylim(0, 500) ax.set_xlabel("flow rate F") ax.set_ylabel("heat-transfer coefficient h") ax.legend(frameon=False, fontsize=8) .. image-sg:: /auto_examples/08_knowledge/images/sphx_glr_plot_30_shape_constraints_001.png :alt: plot 30 shape constraints :srcset: /auto_examples/08_knowledge/images/sphx_glr_plot_30_shape_constraints_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none free 118.2 + 25.88 * (F - (sqrt(sqrt(F - 1.793)) + F / (sqrt(F) * F) - F)) violations on [0.1, 8]: {'F increasing': 0.001953125, 'F concave': 0.875} constrained 24.62 + 235.9 * F / (((F + F) / ((F / F)^2 + F^2 + F))^2 + sqrt(sqrt((F + F) / (sqrt(F / F) + F^2 * F) / F^2)) + F) violations on [0.1, 8]: {'F increasing': 0.0, 'F concave': 0.00390625} .. GENERATED FROM PYTHON SOURCE LINES 47-49 Parameter study: how often does extrapolation fail? --------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 49-59 .. code-block:: Python fails = {False: 0, True: 0} for s in range(6): for use in (False, True): m = eq.SymbolicRegressor(constraints=cons if use else None, constraint_weight=500.0, random_state=s, **kw).fit(X, h) fails[use] += max(check_constraints(m.equation_, cons, method="sampling").values()) > 0.05 print("runs (of 6) violating a constraint by more than 5 %:", {"free": int(fails[False]), "constrained": int(fails[True])}) fig, ax = plt.subplots(figsize=(3.8, 3)) ax.bar(["unconstrained", "constrained"], [fails[False], fails[True]], color=["#D55E00", "#285780"]) ax.set_ylabel("runs violating the shape on >5 % (of 6)") plt.show() .. image-sg:: /auto_examples/08_knowledge/images/sphx_glr_plot_30_shape_constraints_002.png :alt: plot 30 shape constraints :srcset: /auto_examples/08_knowledge/images/sphx_glr_plot_30_shape_constraints_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none runs (of 6) violating a constraint by more than 5 %: {'free': 3, 'constrained': 0} .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 34.371 seconds) .. _sphx_glr_download_auto_examples_08_knowledge_plot_30_shape_constraints.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/08_knowledge/plot_30_shape_constraints.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_30_shape_constraints.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_30_shape_constraints.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_30_shape_constraints.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_