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

Chapter 2
Expressions, search spaces and parameters

Every method of the book manipulates the same object: an expression tree with numerical parameters. This chapter defines the representation, the built-in functions and their protection against undefined values, and the three computations that every search needs on a candidate: its value on the data, its derivatives with respect to the parameters, and guaranteed bounds over a region of the inputs. It then measures the size of the search space, compares ways of measuring the complexity of an equation, and introduces the two ideas that make the numerical constants tractable, linear scaling and gradient-based parameter estimation. The search methods themselves start in chapter 3.

2.1 Problem and idea

An equation such as the rate of an Arrhenius-type reaction,

r = k0ce−E∕T ,
(2.1)

consists of three kinds of symbols: functions (multiplication, the exponential, division, negation), variables (c and T), and numerical constants (k0 and E). Written as a tree, the functions are the inner nodes, and the variables and constants are the leaves (fig. 2.1). Every search method of the book generates, modifies and evaluates such trees, so their representation decides what is cheap and what is expensive. Genetic programming exchanges subtrees between two trees, which requires finding the extent of a subtree quickly; parameter estimation needs the derivatives of the tree with respect to its constants; constraint handling needs bounds of the tree over a box of inputs; simplification and export need a symbolic form.

Figure 2.1

Figure 2.1. The Arrhenius-type rate (2.1) as an expression tree and as the prefix sequence stored by eqdisco. Operators are blue, variables green, constants orange. Every subtree occupies a contiguous block of the sequence, so it can be cut, copied or replaced by slicing.

The idea of eqdisco is to store an expression as a flat prefix sequence of nodes, the order in which a depth-first traversal visits them, and to derive everything else from it. A subtree is a contiguous slice whose end is found by a single pass that counts arities; evaluation runs the sequence backwards with a stack; the constants, read in order, form the parameter vector 𝜃 of the expression. The same sequence is converted to SymPy for simplification, to LaTeX for printing and to source code for deployment.

2.2 Theory

2.2.1 Representation

An expression f is a sequence of nodes (ν0,ν1,…,ν|f|−1) in prefix order. A node is a function of the function set F with arity α ∈{1,2}, a variable xj, or a constant. The size |f| is the number of nodes, the depth depth ⁡ (f) the number of edges on the longest path from the root to a leaf. The subtree rooted at position s ends at the smallest t > s for which the running sum ∑ ⁡ l=st−1(αl −1) reaches −1, where leaves have arity zero. Constants are free parameters by default; a constant can be marked as fixed, which keeps it out of 𝜃 (the exponent 2 of a square, a factor 1∕2 that is part of a known law). The parameters of f are collected in 𝜃 ∈ ℝp in the order of their appearance, and f(x;𝜃) denotes the expression with parameters 𝜃.

2.2.2 Primitives and protection

The functions available to a search are called primitives. Table 2.1 lists the 23 built-in ones; others are added by register_primitive. A search generates many expressions that are undefined somewhere in the data: a division by a difference that vanishes, a logarithm of a negative number, an exponential that overflows. Following Koza [16], eqdisco uses protected operators that return a finite value everywhere: division by a number of magnitude below 10−10 returns 1, the logarithm and the square root act on the absolute value of their argument, and the argument of the exponential is clipped at 100. Protection keeps every candidate comparable, but it also creates artificial plateaus and discontinuities that the search can exploit. The analytic quotient aq(a,b) = a∕1 + b2 of Ni, Drieberg and Rockett [31] is a smooth alternative to division; Keijzer [32] proposed to reject candidates whose interval bounds include a singularity. Every exported model uses the same protected definitions, so a model computes after deployment exactly what it computed during the search.

Table 2.1. The built-in primitives of eqdisco with their weight in the weighted complexity measure and their protection. Leaves have weight 1.

Name

Function

Weight

Protection

add, sub, mul

a + b, a −b, ab

1

–

neg

−a

1

–

div, inv

a∕b, 1∕a

2

1 if |b| ≤10−10

aq

a∕1 + b2

2

smooth everywhere

square, cube

a2, a3

1.5, 2

–

sqrt

|a|

2

absolute value

pow

ab

4

exact for integer b, |a|b otherwise

exp, log

emin ⁡ (a,100), ln ⁡ |a|

3

clipping, absolute value, 0 at 0

sin, cos, tan

trigonometric

3

tan protected near its poles

tanh, atan, logistic, gauss

tanh ⁡ a, arctan ⁡ a, 1∕(1 + e−a), e−a2

3

bounded

abs, max, min

|a|, max ⁡ (a,b), min ⁡ (a,b)

1.5, 2, 2

–

2.2.3 Evaluation and the parameter Jacobian

An expression is evaluated on all N samples at once: the prefix sequence is read backwards, leaves push a column (the variable or the constant broadcast to length N), and a function pops its arguments and pushes its value. The cost is O(N|f|) vector operations. Parameter estimation also needs the Jacobian J ∈ ℝN×p with entries Jik = ∂f(xi;𝜃)∕∂𝜃k. eqdisco computes it in the same backward pass by forward-mode automatic differentiation: every stack entry carries its value v and its gradient ∇ ⁡𝜃v ∈ ℝN×p; a constant 𝜃k pushes the k-th unit vector, a variable a zero gradient, and a function g of arguments a1,…,aα combines them by the chain rule,

∇ ⁡𝜃g(a1,…,aα) = ∑ l=1α ∂g ∂al∇ ⁡𝜃al,
(2.2)

with the partial derivatives of every primitive stored in its definition (including the derivatives of the protected versions). The cost grows to O(Np|f|), which is small because evolved expressions rarely have more than a dozen parameters.

2.2.4 Interval bounds

Interval arithmetic [33] replaces every quantity by an interval [z̲,z¯] that is guaranteed to contain it and propagates the intervals through the functions: [a̲,a¯] + [b̲,b¯] = [a̲ + b̲,a¯ + b¯], the product takes the minimum and maximum of the four end-point products, monotone functions map end points to end points, and periodic or non-monotone functions use their known extrema. Given a box x̲ ≤x ≤x¯, one pass over the tree returns a bound [f̲,f¯] of the expression over the whole box. The bound is exact when every variable occurs once in a monotone expression; when a variable occurs several times, the occurrences are treated as independent and the bound overestimates the range (the dependency problem). Splitting the box into sub-boxes and taking the union of their bounds reduces the overestimation, at a cost that grows with the number of sub-boxes. Interval bounds are used in chapter 9 to check shape constraints, in the simplifier to detect constant subtrees, and in the analysis of extrapolation.

2.2.5 The size of the search space

How many expressions are there? A full binary tree with k inner nodes has k + 1 leaves, and the number of distinct tree shapes is the Catalan number 1 k+1( 2k k) ; every inner node can carry any binary function and every leaf any terminal, so the number of labeled trees grows like 4k |F|k |T|k+1 up to polynomial factors. Many of these trees compute the same function (x0 + x1 and x1 + x0, x0 ⋅c1 ⋅c2 and x0 ⋅c). eqdisco counts the canonical expressions, with the arguments of commutative operators ordered and constant-only subtrees merged into one parameter, by the enumerator of section 5.2.4. Even this reduced space grows exponentially with the size (section 2.4), which is why every method restricts the search: by a maximum size, a small function set, a limit on the number of parameters, a grammar, or a prior distribution over expressions.

2.2.6 Complexity

Symbolic regression trades accuracy for simplicity, so it needs a measure of complexity C(f). The simplest is the size |f|; the depth is cheaper to bound but less informative. The weighted size sums node weights that make nonlinear functions more expensive than additions (table 2.1). The recursive measure of Kommenda et al. [34] composes the complexities of the children: a constant counts 1, a variable 2, a sum the sum of the complexities of its arguments, a product or a quotient the product of (cl + 1), a square c2, a square root c3, and a transcendental function 2c. It charges nested nonlinearities far more than wide sums and thus prefers additive models with simple terms, which are easier to interpret. The number of parameters and the number of distinct variables are further measures. All are available through fitness.complexity; size is the default.

2.2.7 Losses and information criteria

The default loss is the mean squared error MSE = 1 N ∑ ⁡ i(yi −ŷi)2; its normalized version NMSE = MSE∕Var ⁡ (y) = 1 −R2 is scale-free and is used in the figures. Mean absolute error, the Huber loss and the maximum error are robust alternatives; the logistic loss and the misclassification rate serve classification (chapter 8). When equations of different size are compared on the same data, an information criterion penalizes the parameters. With Gaussian errors the maximized log-likelihood is ln ⁡ L^ = −N 2 (ln ⁡ (2πRSS∕N) + 1), where RSS is the residual sum of squares, and

AIC = 2(p + 1) −2ln ⁡ L^,BIC = (p + 1)ln ⁡ N −2ln ⁡ L^
(2.3)

[35, 36], where p counts the fitted parameters including the two of linear scaling and the extra one stands for the error variance. Neither criterion knows the structure of the tree. A two-part description length that also codes the structure, L = −ln ⁡ L^ + |f|ln ⁡ ns + p 2 ln ⁡ N with ns the number of available symbols [37], is a simplified form of the criterion that Bartlett, Desmond and Ferreira [38] use to rank exhaustively enumerated equations (section 5.2.4).

2.2.8 Linear scaling

A target y = 120 + 35x0x1 has the shape of x0x1, but a search that compares raw predictions with the target rewards x0x1 only after it has assembled the constants 120 and 35. Keijzer [32, 39] proposed to evaluate every candidate f in its best affine form a + bf, with the least-squares values

b = ∑ i(fi −f¯)(yi −ȳ) ∑ i(fi −f¯)2 ,a = ȳ −bf¯,
(2.4)

which cost one pass over the data. The mean squared error after scaling is Var ⁡ (y)(1 −ρfy2), where ρfy is the correlation of f and y: the search then rewards shapes, not constants, and the offset and scale of the target no longer matter. Linear scaling is on by default in eqdisco; the printed equations show a and b as the outer constants.

2.2.9 Parameter estimation

Constants inside nonlinear functions, such as E in (2.1), are not reached by linear scaling. With the analytic Jacobian of section 2.2.3, the parameters of a structure are estimated by nonlinear least squares, min ⁡ 𝜃 ∑ ⁡ i (yi −a −bf(xi;𝜃) )2, with the Levenberg–Marquardt method [40, 41]: each step solves (JTJ + λdiag(JTJ))δ = JTe for the residual vector e and adapts the damping λ. eqdisco calls the implementation of SciPy with the analytic Jacobian, starts from the current values (and optionally from random restarts), and keeps the result only if it improves the fit. Kommenda et al. [24] showed that such local optimization inside the search improves the accuracy of genetic programming substantially; section 3.2.5 applies it to the offspring of every generation.

Not every parameter of an evolved expression can be estimated: in 𝜃1𝜃2x only the product is identifiable, and in e𝜃1+x𝜃2 the same holds after rewriting. The rank of the Jacobian at the estimate counts the identifiable directions; a rank below p reveals redundant parameters that the simplifier of chapter 10 can merge [42].

Algorithm

In a nutshell: Expressions and parameters

  • An expression is a prefix sequence of functions, variables and constants; subtrees are contiguous slices, constants form the parameter vector 𝜃.
  • Protected primitives make every candidate finite; exported code uses the same definitions.
  • One backward pass gives the values and the exact Jacobian with respect to 𝜃 (algorithm 2.1); another gives interval bounds over a box, exact for single-occurrence monotone expressions.
  • The space of canonical expressions grows exponentially with size; complexity is measured by size, weighted size or the recursive measure.
  • Linear scaling (2.4) removes offset and scale from the search, and the Levenberg–Marquardt method estimates the inner constants; the rank of the Jacobian reveals redundant parameters.

2.3 Using it in eqdisco

Expression

Construction

Expression.from_string(text, pset) parses a formula (the text is checked against a whitelist of names before SymPy sees it); Expression.var(j), Expression.const(v), Expression.apply(name, *args) build trees; from_sympy, from_list convert.

Structure

nodes, size, depth, subtree(i), replace(i, other), theta, with_theta(theta), variables.

Computation

evaluate(X), jacobian(X) returns (value, J), interval(lower, upper) returns the bounds over one box or a batch of boxes.

Forms

to_string(digits), to_sympy(), latex(), to_list().

Related

PrimitiveSet(n_features, functions, feature_names), register_primitive, Equation(expr) with predict, score, metrics, sympy(), latex(), to_json(); optimize.linear_scaling, optimize.fit_parameters, optimize.jacobian_rank; fitness.complexity(expr, kind).

2.4 Examples

One expression, many views. The rate (2.1) with k0 = 2000 and E = 1500 is parsed from text:

pset = eq.PrimitiveSet(n_features=2, feature_names=["c", "T"]) 
rate = eq.Expression.from_string("2.0e3 * c * exp(-1500 / T)", pset) 
print(rate, "| size", rate.size, "| depth", rate.depth, "| parameters", rate.theta) 
print(rate.nodes[:4])  # prefix order: mul, mul, constant, variable ...
   

It has eight nodes, depth 4 and the parameter vector 𝜃 = (2000,−1500). The same object is evaluated on 200 temperatures, differentiated with respect to its two parameters (the Jacobian has shape 200 ×2), and bounded over the box c = 2, 300 ≤T ≤450 K:

T = np.linspace(300, 450, 200) 
X = np.column_stack([np.full_like(T, 2.0), T]) 
r = rate.evaluate(X)  # vectorized over the rows of X 
value, J = rate.jacobian(X)  # d r / d theta, forward mode 
lo, hi = rate.interval([2.0, 300.0], [2.0, 450.0])  # guaranteed bounds on the box 
print("Jacobian shape", J.shape, "| bounds on the box:", lo[0], hi[0])
   

The interval bound [26.95,142.70] coincides with the range of the curve, because c and T occur once and the expression is monotone in both. The net rate of a reversible reaction, 2000ce−1500∕T −40c2, contains c twice. On the box 1 ≤c ≤3, 300 ≤T ≤450 its true range, computed on a grid, has width 350.9; the interval bound on the whole box has width 520.6, and splitting each variable into 2, 4, 8, 16 and 32 parts narrows it to 435.7, 393.3, 372.1, 361.5 and 356.2 (fig. 2.2). The symbolic forms come from the same object: SymPy prints 2000*c*exp(-1500/T), the LaTeX form is r = 2000ce−1500∕T , and the code generator writes a three-line Python function.

Figure 2.2

Figure 2.2. Tree of the Arrhenius-type rate (left) and its values over 300 ≤T ≤450 K at c = 2 with the interval bound over the same box (right). Because every variable occurs once and the expression is monotone, the bound is exactly the range of the curve.

Open in ColabExample plot_01_expressions.py in the gallery

The size of the space. The enumerator counts the canonical expressions of two variables with at most three parameters:

sets = {"+ x": ("add", "mul"), "+ x -": ("add", "sub", "mul", "div"), "+ x - / exp log": ("add", "sub", "mul", "div", "exp", "log")} 
counts = {} 
for label, funcs in sets.items(): 
    pset = eq.PrimitiveSet(2, funcs) 
    sizes = [e.size for e in enumerate_expressions(pset, max_size=7, max_params=3)] 
    counts[label] = np.bincount(sizes)[1:] 
    print(label, counts[label])
   

With addition and multiplication there are 3, 10, 60 and 470 canonical expressions of one, three, five and seven nodes (even sizes cannot occur with binary functions only). Adding subtraction and division raises the number of seven-node expressions to 8 558; adding the exponential and the logarithm, which allow even sizes, raises it to 19 958 (fig. 2.3). Limiting the number of parameters prunes the space strongly: with the four arithmetic operations there are 1 862 expressions of at most seven nodes without any parameter, 5 967 with at most one, 8 547 with at most two and 8 979 with at most three. The right panel of the figure compares the three complexity measures on seven textbook formulas. Size ranks x0 2 + x1 2 and esin ⁡ (x0x1) close to each other; the recursive measure charges the nested exponential of a sine far more than the Euclidean norm, which is what an analyst would expect.

formulas = ["x0 + x1", "x0*x1", "x0^2 + x1^2", "sqrt(x0^2 + x1^2)", "exp(-x0)*x1", "sin(x0*x1)", "exp(sin(x0*x1))"] 
kinds = ["size", "weighted", "recursive"] 
table = np.array([[complexity(eq.Expression.from_string(f), k) for k in kinds] for f in formulas])
   

Figure 2.3

Figure 2.3. Left: number of canonical expressions of two variables by size for three function sets (logarithmic scale). Right: size, weighted size and the recursive complexity of Kommenda et al. for seven formulas, each scaled to its maximum.

Open in ColabExample plot_03_search_space.py in the gallery

Linear scaling. The target y = 120 + 35x0x1 + 3sin ⁡ (3x0) is searched ten times with and ten times without linear scaling, with a population of 200 and 20 generations:

hist = {True: [], False: []} 
for scaling in (True, False): 
    for seed in range(10): 
        sr = eq.SymbolicRegressor(population_size=200, generations=20, linear_scaling=scaling, functions=("add", "sub", "mul", "sin"), random_state=seed) 
        sr.fit(X, y) 
        hist[scaling].append(sr.history_["best_loss"].to_numpy() / np.var(y))
   

With scaling, the median normalized error of the best equation after 20 generations is 6.4 ⋅10−3; without scaling it is 0.26, forty times higher (fig. 2.4). The parameter study changes only the offset of the target. With scaling, the median R2 stays between 0.991 and 0.996 for offsets 0, 10, 100 and 1000; without scaling it falls from 0.991 at offset 0 to 0.497 at offset 100 and 0.354 at offset 1000, because the search spends its effort on building the constant.

Figure 2.4

Figure 2.4. Normalized mean squared error of the best equation in ten runs with linear scaling (blue) and ten runs without (vermilion); thick lines are the medians. With scaling, the search rewards the shape x0x1 from the first generation.

Open in ColabExample plot_04_linear_scaling.py in the gallery

2.5 Further reading

The prefix representation and protected operators go back to Koza [16]; the field guide of Poli, Langdon and McPhee [28] discusses alternative representations (linear, graph-based, grammar-based). Keijzer [32, 39] introduced linear scaling and interval-arithmetic checks, Ni, Drieberg and Rockett [31] the analytic quotient. Moore, Kearfott and Cloud [33] is a textbook of interval analysis. Kommenda et al. compared complexity measures [34] and nonlinear least-squares tuning of constants [24]; de França and Kronberger [42] show how often evolved models are overparameterized and how equality saturation removes redundant parameters. Bates and Watts [43] is the standard reference for nonlinear least squares and parameter identifiability.