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.
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 quantities whose units span independent dimensions can be written as a relation between dimensionless products of them. The exponents of these products form a basis of the null space of the 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 (), decreasing, convex (), 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: or , or 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 and tests:
- additive separability
-
of a group of variables from the rest : the mixed differences vanish for random pairs of samples;
- multiplicative separability
-
the same test on ;
- translational symmetry
-
of a pair : changes little when both are shifted by the same amount;
- scaling symmetry
-
of a pair: 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 “ depends on ”. The tests are only as good as the surrogate, so they need enough data to fit it well.
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 variables in dimensions to 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, with distances in metres and a dimensionless refractive index , 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 to the distance . With units, three of the five are consistent, and the first of them, , 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 , length and gravitational acceleration : the single group is , and the law reduces to the statement that is constant.
Shape constraints and extrapolation. Fifteen measurements of a heat-transfer coefficient follow a power law with 5% noise in a narrow range of flow rates, ; the model will be used between 0.1 and 8. One search is unconstrained, the other requires to be increasing and concave in on :
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 . 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.
Open in ColabExample plot_30_shape_constraints.py in the gallery
Symmetries. The center of mass of two bodies, (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 and 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 depends on the masses only through , 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 is 1.4%, 0.7%, 0.5% and 0.6%.
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.