Note
Go to the end to download the full example code or to run this example in your browser via Binder.
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.
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)]
Unconstrained and constrained searches#
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)

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}
<matplotlib.legend.Legend object at 0x72b45155a8a0>
Parameter study: how often does extrapolation fail?#
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()

runs (of 6) violating a constraint by more than 5 %: {'free': 3, 'constrained': 0}
Total running time of the script: (0 minutes 34.371 seconds)