Chapter 1
Introduction
This chapter states the problem of equation discovery, explains why it is harder and more rewarding than fitting a model of fixed form, and maps the families of search methods onto the chapters of the book. It then places eqdisco among the existing software, fixes the notation used throughout, describes the conventions shared by all estimators of the package, and ends with a first search that rediscovers Kepler’s third law from the orbits of the eight planets.
1.1 Problem and idea
Given observations of input variables, collected in the rows of a matrix , and of a target , regression looks for a function with . Classical regression fixes the form of and estimates its parameters: a straight line, a polynomial of given degree, a rate law chosen by the chemist. Machine learning replaces the fixed form by a flexible one, such as a tree ensemble or a neural network, whose parameters are many and whose form explains little. Symbolic regression treats the form itself as unknown: it searches over the expressions that can be built from the variables, numerical constants and a set of functions, and returns the expressions that fit the data well and are short enough to be read [16, 17, 18, 19].
The reward is a model that is also a hypothesis. When Kepler compared the orbital periods and the mean distances of the planets known to him, he found in 1619 that is the same for all of them. The law is short, it holds far outside the range of the data that suggested it, and it later became a consequence of Newton’s theory of gravitation. A neural network trained on the same data would predict the periods of the planets just as well, but it would not have suggested Newton’s question. Equation discovery is the attempt to automate the step from data to such compact laws, or at least to propose candidates that a scientist can examine.
The difficulty is the size of the space to be searched. With two variables and the four arithmetic operations, section 2.2.5 counts 8 558 structurally distinct expressions of seven nodes; with exponential and logarithm added, the number of structures with seven nodes is close to twenty thousand, and every one of them has numerical constants to be estimated. Finding the expression of a given size that fits a data set best is NP-hard [20]. Every practical method therefore restricts or guides the search, and the methods differ mainly in how they do so (fig. 1.1): genetic programming evolves a population of trees by selection and variation; linear-in-parameters models restrict the search to sums of terms whose weights are estimated by least squares; sparse regression enumerates a large library of candidate terms and keeps few of them; exhaustive search enumerates all short expressions; Bayesian and probabilistic methods sample expressions from a distribution that is updated by the data; and language models propose expressions from their knowledge of the scientific literature.
The idea of the book follows from this picture. Instead of presenting one algorithm, it presents the search as a sequence of decisions that every method makes, explicitly or implicitly: how equations are represented, which building blocks are allowed, how numerical constants are estimated, how the search moves through the space, how accuracy is traded against complexity, which prior knowledge restricts the space, and how one model is finally selected and checked. eqdisco implements each decision as a separate, exchangeable component, so that the methods can be compared on the same data and combined where they complement each other.
1.2 What an equation buys
The advantages of a discovered equation over a black-box model recur throughout the book and are summarized in chapter 12.
- Interpretability.
-
An equation of ten or twenty nodes can be read term by term; the error reduction ratio of each term (chapter 4) and its variance-based sensitivity (chapter 10) say how much each part contributes.
- Extrapolation.
-
A correct structure holds outside the range of the data, which no interpolating model does. Shape constraints and units (chapter 9) make wrong extrapolation less likely when the structure is only approximately right.
- Analysis.
-
An explicit formula can be differentiated, bounded by interval arithmetic, simplified, and examined for parameters that cannot be identified from the data (chapters 2 and 10).
- Deployment.
-
A formula of a few dozen operations compiles to a few lines of C, a spreadsheet cell or a PMML document, needs no runtime library, and can be certified by inspection (chapter 11).
- Knowledge.
-
A discovered law can be compared with theory, and the building blocks shared by many good models point to the mechanisms in the data (chapter 10).
The disadvantages are equally real. The search is expensive, stochastic and without guarantees; small data sets admit many equations of similar accuracy; and an equation that fits well need not be the true mechanism. Much of the book is therefore about doing the search well and checking its results honestly.
1.3 The software landscape
Symbolic regression software appeared soon after Koza’s book [16]. GPTIPS [21, 22] brought multi-gene genetic programming to MATLAB; HeuristicLab and its successor Operon [23] implement tree-based GP with nonlinear least-squares tuning of constants [24]; PySR [25] combines a multi-population evolutionary search written in Julia with a Python interface; DEAP [26] is a general evolutionary computation framework in which GP can be assembled; PySINDy [27] implements sparse identification of dynamical systems; and the SRBench project [6] compared more than a dozen methods on more than two hundred problems. The GP-OLS MATLAB toolbox of the author’s group [1] combined genetic programming with orthogonal least squares for the identification of input–output models.
eqdisco does not aim to be the fastest of these systems. Its purpose is breadth and transparency: it implements the main families of methods side by side, in plain Python and NumPy, with a common representation of equations and a common interface, so that a method can be studied, modified and compared. It adds the analysis and deployment tools that turn a discovered equation into a usable model, and it reproduces the methods of the author’s group that were previously available only in MATLAB. Where speed matters more than transparency, the equations found by other systems can be imported as text (Equation.from_string) and analyzed with the same tools.
1.4 Notation
Table 1.1 collects the symbols used in more than one chapter. Vectors are bold lowercase, matrices bold uppercase, sets calligraphic. An expression is a tree built from functions, variables and constants; an equation is an expression together with fitted parameters and the metadata of a search.
Symbol | Meaning | In eqdisco |
, | data matrix, its -th row (sample) | X |
, | target, predictions | y, predict(X) |
| expression with parameters | Expression, theta |
, | function set, terminal set (variables and constants) | functions, PrimitiveSet |
, | size (number of nodes) and depth of a tree | size, depth |
| complexity of an expression (section 2.2.6) | complexity |
, , | loss, mean squared error, MSE divided by | loss |
| linear scaling of an expression (section 2.2.8) | linear_scaling |
, , | population, its size, number of generations | population_size, generations |
, | regressor matrix of terms, their weights | gene_table() |
| error reduction ratio of term (section 4.2.1) | err |
, | candidate library, sparse coefficient matrix | SparseRegressor, SINDy |
, | input and output of a dynamic system at sample | NARXRegressor |
, , | output and input orders, input delay | na, nb, nk |
| interval bound of a quantity | interval |
, | first-order and total Sobol indices of input | sobol_indices |
| Pareto archive of non-dominated equations | pareto_front_ |
1.5 Conventions of the package
Every search method of eqdisco is a scikit-learn estimator [12]. It is configured by the arguments of its constructor, trained by fit(X, y), and used through predict(X) and score(X, y), which returns the coefficient of determination ; it can therefore be cross-validated, placed in pipelines and tuned with the tools of scikit-learn. After fitting, every estimator exposes the same attributes:
- equation_
-
the selected model, an Equation with predict, score, metrics, sympy(), latex(), to_json() and the underlying Expression in expr;
- pareto_front_
-
the non-dominated equations of the run, ordered by complexity, from which equation_ was selected by the rule in model_selection (section 3.2.7);
- history_
-
a pandas data frame with one row per generation or iteration (best and median loss, sizes, diversity, number of evaluations, time).
Feature names can be given by feature_names; otherwise the variables are called x0, x1, …. All randomness is controlled by random_state. Operators are protected: division by a number close to zero returns one, logarithm and square root act on the absolute value, and the argument of the exponential is clipped at 100 (section 2.2.2). The same conventions are used by the code generators of chapter 11, so an exported model computes exactly what the search evaluated.
1.6 A first session
The eight planets give eight pairs of semi-major axis (in astronomical units) and sidereal period (in years), taken from the planetary fact sheet of NASA. A genetic programming search with a population of 300 equations, 25 generations and the function set is two lines of code:
planets = eq.datasets.load_kepler() X, T = planets[["a"]], planets["T"].to_numpy() sr = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div", "sqrt"), random_state=0) sr.fit(X, T) print(sr.equation_) # about 1.0 * a * sqrt(a), i.e. T = a^1.5 for e in sr.pareto_front_: print(f"{e.complexity:3d} R2 = {e.metrics[’r2’]:.6f} {e}")
The run returns a front of four equations. The simplest, with five nodes, explains 97.6% of the variance; a quadratic form with seven nodes explains 98.8%; the equation with eight nodes,
explains the data to the precision of the rounded table (), and a 27-node equation adds nothing. The Bayesian information criterion selects the eight-node equation, which is Kepler’s law with a scale factor that differs from one by less than the rounding of the data. Figure 1.2 shows the law, the front and the tree of the selected equation. Genetic programming is a stochastic search, so the script repeats it with ten random seeds and two population sizes: the law is found in all ten runs with a population of 50 and in nine of ten runs with a population of 300. A larger population does not guarantee success; it changes which equations compete in the early generations, and on eight data points a slightly different equation of the same accuracy can win.
1.7 Further reading
Koza’s book [16] introduced genetic programming and symbolic regression; the field guide of Poli, Langdon and McPhee [28] is a free and compact introduction to GP, and the book of Kronberger et al. [18] is a modern, practical account of GP for symbolic regression. Makke and Chawla [19] review the methods and applications of symbolic regression in science, including the neural and transformer-based approaches [29, 30] that this book does not implement. La Cava et al. [6] compare the main methods on a common benchmark, and Virgolin and Pissis [20] prove that the problem is NP-hard. The paper of Schmidt and Lipson [17], which rediscovered conservation laws of mechanical systems from motion-tracking data, did much to bring equation discovery to the attention of the natural sciences.