Discovering Equations from Data with PythonSymbolic regression, genetic programming and the eqdisco toolbox

Chapter 9
Domain knowledge

Data alone rarely determine an equation, especially when they are few, noisy and cover a narrow range of the inputs. Physical knowledge narrows the search. This chapter shows three kinds of knowledge that eqdisco can use: physical units, which forbid adding quantities of different dimensions and reduce the variables to dimensionless groups; shape constraints, which require a model to be monotone, convex or bounded where it will be used, beyond the range of the data; and symmetries and separability, which are detected from the data before the search and suggest the form of the law.

9.1 Problem and idea

A heat-transfer coefficient measured at fifteen flow rates between 0.5 and 3 can be fitted by many equations; most of them do something absurd at a flow rate of 8, where the model will be used. A formula for the focal length of a lens that adds a distance to a refractive index may fit the data, but it is wrong. An equation for the center of mass of two bodies that does not depend on the ratio of their masses alone contradicts a symmetry of the problem. In each case the analyst knows something that the data do not show, and a search that ignores it wastes effort on equations that will be rejected anyway.

eqdisco lets knowledge enter in three ways (fig. 9.1). Units are attached to the variables and the target; inconsistent candidates are penalized during the search, and the Buckingham Π theorem reduces the inputs to dimensionless groups before it. Shape constraints state monotonicity, convexity or bounds on a domain that may extend beyond the data; candidates that violate them are penalized. Symmetry tests probe a smooth surrogate of the data for separability and invariances and suggest a simpler problem to search.

Figure 9.1

Figure 9.1. Three ways of bringing domain knowledge into the search. Units and shape constraints become penalties of the loss, symmetries detected on a surrogate model reduce the problem before the search.

9.2 Theory

9.2.1 Physical units

Every SI unit is a vector of exponents of the seven base dimensions; a unit string such as "kg*m/s^2" is parsed into such a vector. Units propagate through an expression bottom-up: multiplication and division add and subtract the vectors, integer powers scale them, the square root halves them. Addition and subtraction require equal units; transcendental functions (exponential, logarithm, trigonometric functions) require a dimensionless argument and return a dimensionless value. Keijzer and Babovic [89] proposed to make genetic programming dimensionally aware in this way. eqdisco counts the violations of an expression (incompatible sums, dimensional arguments of transcendental functions, an output unit that differs from the unit of the target) and adds a penalty proportional to their number, scaled by the variance of the target and constraint_weight. Fitted constants may carry any unit, as the gravitational constant or the Boltzmann constant do, so a constant never causes a violation by itself.

The Buckingham Π theorem [90] states that a physically meaningful relation between n quantities whose units span r independent dimensions can be written as a relation between n −r dimensionless products of them. The exponents of these products form a basis of the null space of the r ×n dimension matrix; eqdisco computes a basis with small integer or half-integer exponents. Replacing the variables by the Π groups before the search reduces the number of inputs and guarantees dimensional consistency; it is the first step of AI Feynman [7].

9.2.2 Shape constraints

A shape constraint states that the model, or one of its derivatives, has a sign on a domain: increasing in a variable (∂f∕∂xj ≥0), decreasing, convex (∂2f∕∂xj2 ≥0), concave, or bounded between two values. Kronberger et al. [91] showed that such constraints improve the extrapolation of symbolic regression models considerably, because they rule out the oscillations and turns that fit the data but not the physics. The derivatives are obtained symbolically by SymPy and converted back into expressions. Their sign is checked in two ways: by sampling the domain on a grid or at random points, which is fast but can miss a short violation, or by interval arithmetic (section 2.2.4), which bounds the derivative over the whole domain and is conservative but never misses one. The violation is the share of sampled points (or the extent of the interval) on the wrong side, and it is added to the loss with the weight constraint_weight. The domain can, and usually should, extend beyond the range of the data, since that is where the constraint has an effect.

9.2.3 Separability and symmetries

Many physical laws are separable or invariant: f(x1,x2,x3) = g(x1) + h(x2,x3) or g(x1)h(x2,x3), or f depends on two variables only through their difference or their ratio. Udrescu and Tegmark [7] detect these properties by fitting a neural network to the data and probing it, and use them to split a problem into smaller ones. eqdisco fits a smooth multilayer perceptron surrogate f^ and tests:

additive separability

of a group of variables A from the rest B: the mixed differences f^(xA,xB) + f^(x′A,x′B) −f^(xA,x′B) −f^(x′A,xB) vanish for random pairs of samples;

multiplicative separability

the same test on ln ⁡ |f^|;

translational symmetry

of a pair (xi,xj): f^ changes little when both are shifted by the same amount;

scaling symmetry

of a pair: f^ changes little when both are multiplied by the same factor.

The changes are compared with a reference, the change caused by shifting one variable alone. A pairwise additive interaction matrix summarizes which variables interact, and suggest_structure turns the passed tests into suggestions such as “f depends on m1∕m2”. The tests are only as good as the surrogate, so they need enough data to fit it well.

Algorithm

In a nutshell: Domain knowledge

  • Units propagate through expressions; inconsistent sums, dimensional arguments of transcendental functions and wrong output units are penalized; constants may carry any unit.
  • The Buckingham Π theorem reduces n variables in r dimensions to n −r dimensionless groups.
  • Shape constraints (monotonicity, convexity, bounds) on a domain beyond the data are checked by sampling or by interval arithmetic and penalized (algorithm 9.1).
  • Separability and translational or scaling symmetries are tested on a neural surrogate and suggest a simpler problem.

9.3 Using it in eqdisco

SymbolicRegressor(..., units=None, constraints=None, constraint_weight=10.0)

units

a dictionary from variable names (and "__target__") to unit strings such as "m", "kg*m/s^2", "1".

constraints

a list of knowledge.ShapeConstraint(kind, variable, domain, lower, upper) with kind in "increasing", "decreasing", "convex", "concave", "bounded".

Related

knowledge.parse_unit, knowledge.check_units(model, units), knowledge.unit_violations, knowledge.buckingham_pi(units, target), knowledge.dimensionless_features; knowledge.check_constraints(model, constraints, method), knowledge.constraint_violation; knowledge.fit_surrogate, knowledge.separability, knowledge.interaction_matrix, knowledge.symmetry_tests, knowledge.suggest_structure; viz.plot_interaction_matrix.

9.4 Examples

Units. The thin-lens equation of the Feynman collection, f = 1∕(1∕d1 + n∕d2) with distances d1,d2 in metres and a dimensionless refractive index n, is sampled at 60 points with 5% noise. Five searches without and five with units are compared:

res = {} 
for use in (False, True): 
    res[use] = [ 
        eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "square"), units=prob.units if use else None, 
                             feature_names=prob.feature_names, random_state=s).fit(prob.X_train, prob.y_train) 
        for s in range(5) 
    ] 
for use, rr in res.items(): 
    ok = [check_units(r.equation_, prob.units)["consistent"] for r in rr] 
    print("units" if use else "no units", "consistent:", sum(ok), "of", len(ok), "| e.g.", rr[0].equation_)
   

None of the five equations found without units is dimensionally consistent; a typical one adds the index n to the distance d2. With units, three of the five are consistent, and the first of them, 0.00624 + 0.9965d2∕(n + d2∕d1), is the lens equation itself (fig. 9.2). The unit penalty is a soft constraint, so some runs still return inconsistent equations; the parameter study shows that the share of consistent equations in four runs is 0 without the penalty and 0.75, 0.5 and 0.75 with weights 0.1, 1 and 10, so the weight matters less than the presence of the penalty. The second part of the example computes the Buckingham group of a pendulum from the units of its period T, length l and gravitational acceleration g: the single group is Π = Tg1∕2l−1∕2, and the law T = 2πl∕g reduces to the statement that Π is constant.

Figure 9.2

Figure 9.2. Searches with and without units for the thin-lens equation. Left: test error against size of the selected equations; circled equations are dimensionally consistent. Right: periods of pendulums of different lengths against l∕g; the Buckingham group Π = Tg∕l equals 2π for all of them.

Open in ColabExample plot_29_units.py in the gallery

Shape constraints and extrapolation. Fifteen measurements of a heat-transfer coefficient follow a power law h = 120F0.6 with 5% noise in a narrow range of flow rates, 0.5 ≤F ≤3; the model will be used between 0.1 and 8. One search is unconstrained, the other requires h to be increasing and concave in F on [0.1,8]:

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"))
   

Inside the range of the data the two models agree; outside they differ (fig. 9.3). The unconstrained model is concave at only 12.5% of the sampled points of the use domain and grows almost linearly beyond the data. The constrained model is increasing everywhere and concave at all but 0.4% of the points; it saturates beyond the data, below the true power law but with the right qualitative shape. A constraint guarantees the shape, not the values: with fifteen points in a narrow range, no method can know how fast the coefficient grows at F = 8. Repeated over six seeds, three of the unconstrained models but none of the constrained ones violate a constraint at more than 5% of the points.

Figure 9.3

Figure 9.3. Shape constraints and extrapolation. Fifteen measurements (gray points) in the shaded range, the true power law (dotted), and the models found without constraints (vermilion) and with the constraints increasing and concave on [0.1,8] (blue).

Open in ColabExample plot_30_shape_constraints.py in the gallery

Symmetries. The center of mass of two bodies, r = (m1r1 + m2r2)∕(m1 + m2) (Feynman I.18.4), is sampled at 800 points, a surrogate network is fitted, and the symmetry tests are run on all pairs of variables:

f = fit_surrogate(prob.X_train, prob.y_train, random_state=0) 
M = interaction_matrix(f, prob.X_train) 
st = symmetry_tests(f, prob.X_train, names) 
print(st.round(4)) 
for line in suggest_structure(f, prob.X_train, names, tol=0.03): 
    print(line)
   

Scaling m1 and m2 together changes the surrogate by 0.6% on average, less than a third of the change caused by shifting one variable alone (2.1%); every other pair changes it by 7 to 37%. The test suggests that f depends on the masses only through m1∕m2, which is correct and reduces the problem from four variables to three (fig. 9.4). The test depends on the quality of the surrogate: with 100, 200, 400 and 800 samples the error of the scaling test for (m1,m2) is 1.4%, 0.7%, 0.5% and 0.6%.

Figure 9.4

Figure 9.4. Symmetry tests on a neural surrogate of the center of mass. Left: additive interaction of the variable pairs. Right: relative change of the surrogate under joint scaling and joint translation of each pair, compared with the change caused by one variable alone (black marks); only the joint scaling of m1 and m2 falls below the reference.

Open in ColabExample plot_31_symmetry.py in the gallery

9.5 Further reading

Keijzer and Babovic [89] introduced dimensionally aware genetic programming; Buckingham [90] stated the theorem of dimensionless groups. Kronberger et al. [91] develop shape-constrained symbolic regression with interval arithmetic and compare it with sampling; Moore, Kearfott and Cloud [33] explain the interval methods. Udrescu and Tegmark [7] combine dimensional analysis, neural surrogates and symmetry tests in AI Feynman and provide the Feynman equations used as benchmarks throughout this book. Cranmer et al. [92] build inductive biases into neural networks and distill them into symbolic models.