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,
|
| (2.1) |
consists of three kinds of symbols: functions (multiplication, the exponential, division, negation), variables ( and ), and numerical constants ( and ). 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.
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 is a sequence of nodes in prefix order. A node is a function of the function set with arity , a variable , or a constant. The size is the number of nodes, the depth the number of edges on the longest path from the root to a leaf. The subtree rooted at position ends at the smallest for which the running sum reaches , 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 that is part of a known law). The parameters of are collected in in the order of their appearance, and 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 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 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.
Name | Function | Weight | Protection |
add, sub, mul | , , | 1 | – |
neg |
| 1 | – |
div, inv | , | 2 | 1 if |
aq |
| 2 | smooth everywhere |
square, cube | , | 1.5, 2 | – |
sqrt |
| 2 | absolute value |
pow |
| 4 | exact for integer , otherwise |
exp, log | , | 3 | clipping, absolute value, 0 at 0 |
sin, cos, tan | trigonometric | 3 | tan protected near its poles |
tanh, atan, logistic, gauss | , , , | 3 | bounded |
abs, max, min | , , | 1.5, 2, 2 | – |
2.2.3 Evaluation and the parameter Jacobian
An expression is evaluated on all samples at once: the prefix sequence is read backwards, leaves push a column (the variable or the constant broadcast to length ), and a function pops its arguments and pushes its value. The cost is vector operations. Parameter estimation also needs the Jacobian with entries . eqdisco computes it in the same backward pass by forward-mode automatic differentiation: every stack entry carries its value and its gradient ; a constant pushes the -th unit vector, a variable a zero gradient, and a function of arguments combines them by the chain rule,
|
| (2.2) |
with the partial derivatives of every primitive stored in its definition (including the derivatives of the protected versions). The cost grows to , 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 that is guaranteed to contain it and propagates the intervals through the functions: , 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 , one pass over the tree returns a bound 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 inner nodes has leaves, and the number of distinct tree shapes is the Catalan number ; every inner node can carry any binary function and every leaf any terminal, so the number of labeled trees grows like up to polynomial factors. Many of these trees compute the same function ( and , and ). 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 . The simplest is the size ; 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 , a square , a square root , and a transcendental function . 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 ; its normalized version 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 , where RSS is the residual sum of squares, and
|
| (2.3) |
[35, 36], where 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, with 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 has the shape of , but a search that compares raw predictions with the target rewards only after it has assembled the constants 120 and 35. Keijzer [32, 39] proposed to evaluate every candidate in its best affine form , with the least-squares values
|
| (2.4) |
which cost one pass over the data. The mean squared error after scaling is , where is the correlation of and : 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 and as the outer constants.
2.2.9 Parameter estimation
Constants inside nonlinear functions, such as 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, , with the Levenberg–Marquardt method [40, 41]: each step solves for the residual vector 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 only the product is identifiable, and in the same holds after rewriting. The rank of the Jacobian at the estimate counts the identifiable directions; a rank below reveals redundant parameters that the simplifier of chapter 10 can merge [42].
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 and 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 . The same object is evaluated on 200 temperatures, differentiated with respect to its two parameters (the Jacobian has shape ), and bounded over the box , 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 coincides with the range of the curve, because and occur once and the expression is monotone in both. The net rate of a reversible reaction, , contains twice. On the box , 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 , and the code generator writes a three-line Python function.
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 and 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])
Linear scaling. The target 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 ; 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 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.
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.