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

Chapter 5
Sparse regression and deterministic search

If the unknown law is a short combination of terms from a known list, the search for an equation becomes a regression problem with a sparsity requirement. This chapter presents the libraries of candidate terms and four ways to select a few of them: sequentially thresholded least squares, the Lasso, forward orthogonal least squares and best-subset search. It then describes fast function extraction, which generates thousands of nonlinear bases and follows a regularization path, and exhaustive search, which enumerates every expression up to a given size and ranks them by their description length. All three are deterministic: the same data give the same answer, which genetic programming cannot promise.

5.1 Problem and idea

Genetic programming searches the space of expressions without assuming anything about the form of the answer. Often a weaker but useful assumption is possible: the law is a linear combination of a few terms taken from a large, known list. In chemical kinetics the list contains products of concentrations; in mechanics, polynomials of positions and velocities and trigonometric functions of angles; in empirical correlations, powers and logarithms of dimensionless groups. Once the list, the library, is fixed, the search is replaced by a regression with a sparsity requirement: among the M candidate terms, find the few whose combination explains the data (fig. 5.1). The problem is still combinatorial, but it has excellent heuristics, and their results are reproducible.

Figure 5.1

Figure 5.1. Sparse regression over a library of candidate terms. Every column of Θ(X) is one term evaluated on the data; a sparse coefficient vector ξ selects the few that form the equation.

The price of the library is that a term outside it cannot be found, and a library that is too large makes the selection ambiguous. The second half of the chapter goes in the opposite direction: exhaustive search makes no library assumption at all but restricts the size of the equations, and enumerates the whole space below that size.

5.2 Theory

5.2.1 Libraries

A library Θ(X) = [𝜃1(X),…,𝜃M(X)] holds candidate terms evaluated on the data. eqdisco builds three kinds: all monomials of the inputs up to a given degree (with n = 3 and degree 3 there are 19 terms besides the constant), unary functions of the inputs (sines, cosines, exponentials, logarithms) optionally multiplied by the monomials, and hinge functions max ⁡ (0,xj −κ) and max ⁡ (0,κ −xj) at quantile knots κ, the building blocks of multivariate adaptive regression splines [65]. Every term is an Expression, so the selected model is an ordinary Equation that can be analyzed and exported like any other.

5.2.2 Selecting terms

The model is y = ξ0 + Θξ + e with a sparse ξ. Four selection methods are available.

Sequentially thresholded least squares (STLSQ). Brunton, Proctor and Kutz [66] estimate ξ by least squares, set the coefficients below a threshold λ to zero, refit on the remaining terms, and repeat until the support no longer changes. With normalized columns the threshold is relative to the scale of each term. STLSQ is simple and fast, and on well-conditioned libraries it recovers the true support reliably; its weakness is the threshold, which must lie between the smallest true coefficient and the largest spurious one.

The Lasso. The ℓ1-penalized least squares problem min ⁡ ‖y −ξ0 −Θξ‖2∕(2N) + α ‖ξ‖1 [67] sets coefficients exactly to zero; the penalty α is chosen by cross-validation along the regularization path computed by coordinate descent [68]. The Lasso shrinks the surviving coefficients and, with correlated terms, tends to keep several of them with small weights.

Forward orthogonal least squares. FROLS (algorithm 4.1) adds the term with the largest error reduction ratio until an information criterion stops improving.

Best subset. For small libraries and few terms, every subset of up to k terms is fitted and the one with the lowest information criterion is kept. The search is exact but grows as (M k) ; Bertsimas, King and Mazumder [69] solve larger instances by mixed-integer optimization.

Algorithm

5.2.3 Fast function extraction

McConaghy’s FFX [70] takes the library idea to its limit and drops evolution altogether. It generates univariate bases (xj, xj2, |x j|, |xj|, ln ⁡ |xj| and hinge functions at quantile knots) and, optionally, all pairwise products of them, and follows the regularization path of the elastic net with a mostly-ℓ1 penalty (l1_ratio = 0.95). Every point of the path selects a different set of bases; eqdisco refits each support by least squares and keeps the models that are non-dominated in the number of bases and the error, which gives a Pareto front in a fraction of a second. The front is selected from by the rules of section 3.2.7. FFX is deterministic and fast; its models are sums of many simple bases, accurate but less compact than evolved equations.

5.2.4 Exhaustive search

For small equations the whole space can be searched. ExhaustiveRegressor enumerates every canonical expression up to a maximum size (section 2.2.5): commutative arguments are ordered, subtrees without variables are merged into a single parameter, at most max_params parameters are allowed, and nestings that are rarely meaningful (an exponential inside an exponential, a logarithm of a logarithm) are pruned. The parameters of every candidate are fitted by Levenberg–Marquardt, candidates that compute the same values on the data as an earlier, not larger one are removed, and the rest are ranked by a criterion. Bartlett, Desmond and Ferreira [38] showed with their exhaustive symbolic regression that the ranking criterion matters as much as the search, and proposed the minimum description length: the number of nats needed to transmit the data given the model plus the number needed to transmit the model. eqdisco uses the simplified two-part code of section 2.2.7, which charges the structure by |f|ln ⁡ ns and each parameter by 1 2 ln ⁡ N; the BIC and the AIC can be chosen instead. Kammerer et al. [71] reduce the search space further by a grammar and deduplicate structures by semantic hashing. The number of candidates grows exponentially with the maximum size, so exhaustive search is practical up to about seven nodes with a few variables, where it gives a guarantee that no other method gives: no equation of that size was missed.

Algorithm

In a nutshell: Sparse and deterministic search

  • A library of candidate terms turns the search into sparse regression; terms outside the library cannot be found.
  • STLSQ (algorithm 5.1) thresholds and refits; the Lasso penalizes the ℓ1 norm; FROLS adds terms by error reduction ratio; best subset is exact for small problems.
  • FFX follows the elastic-net path over thousands of univariate and pairwise bases and returns a front in a fraction of a second.
  • Exhaustive search (algorithm 5.2) enumerates all canonical expressions up to a size, removes duplicates and ranks by description length; it guarantees that no small equation was missed.
  • All are deterministic: the same data give the same equation.

5.3 Using it in eqdisco

SparseRegressor(library=None, degree=2, functions=(), method="stlsq", threshold=0.05, max_terms=None, criterion="bic", ...)

library

a list of Expression terms; if None, monomials up to degree and the unary functions of the inputs (interactions adds their products with the monomials).

method

"stlsq", "lasso", "frols" or "best_subset"; threshold and ridge for STLSQ, criterion and err_tol for FROLS and best subset.

Results

equation_, terms_, coef_, support_.

Related

FFXRegressor(interactions, n_knots, operators, l1_ratio, max_bases, model_selection); ExhaustiveRegressor(functions, max_size, max_params, criterion="mdl", restarts) with results_, n_candidates_; models.polynomial_library, function_library, hinge_library, library_matrix, stlsq; models.enumerate_expressions.

5.4 Examples

Four ways to select terms. A polynomial heat-release model, y = 1.5T2p −0.8c + 0.6Tc with 2% noise, is regressed on all 19 monomials of T, p and c up to degree 3:

models = {m: eq.SparseRegressor(degree=3, method=m, threshold=0.05, max_terms=4, feature_names=["T", "p", "c"]).fit(X, y) for m in ("stlsq", "lasso", "frols", "best_subset")} 
for m, s in models.items(): 
    print(f"{m:12s} {s.support_.sum():2d} terms  R2 {s.score(X, y):.5f}  {s.equation_}")
   

STLSQ, FROLS and best subset return the same three terms with coefficients 1.501, −0.799 and 0.602 and R2 = 0.99898 (fig. 5.2). The cross-validated Lasso reaches a marginally higher training R2 of 0.99904 with twelve terms, nine of them with coefficients below 0.012: the ℓ1 penalty that is optimal for prediction keeps small spurious terms, which is why the sparse identification literature prefers thresholding or forward selection. The parameter study shows how the threshold of STLSQ interacts with the noise. At 2% noise, thresholds of 0.001, 0.007, 0.043 and 0.285 keep 16, 5, 3 and 3 terms; at 10% noise, 19, 14, 3 and 3; at 30% noise, 18, 16, 6 and 3. The larger the noise, the larger the threshold needed to separate the true terms from the spurious ones.

Figure 5.2

Figure 5.2. Coefficients of the 19 monomials selected by STLSQ, the Lasso, FROLS and best-subset search for a three-term polynomial target. The Lasso keeps nine additional terms with tiny coefficients.

Open in ColabExample plot_16_sparse_library.py in the gallery

Fast function extraction. Vladislavleva-1, a Gaussian bump divided by a quadratic in two variables, is a hard target for a sum of bases:

ffx = eq.FFXRegressor(n_knots=3, max_bases=15).fit(prob.X_train, prob.y_train) 
print(len(ffx.bases_), "candidate bases;", len(ffx.pareto_front_), "models on the front") 
print(ffx.equation_)
   

FFX generates 36 candidate bases and returns a front of 14 models in a fraction of a second. The selected model uses 14 bases (a logarithm, eight hinge functions and five products) and reaches a test error of 1 −R2 = 0.034 (fig. 5.3); it is accurate but not a closed-form law. The parameter study switches the two kinds of bases on and off: univariate bases alone give a best test error of 0.160, adding hinges 0.138, adding pairwise interactions 0.035, and both 0.034. The interactions matter because the target couples the two variables.

Figure 5.3

Figure 5.3. The FFX front on Vladislavleva-1. Left: training and test error against the number of bases. Right: test predictions of the selected model.

Open in ColabExample plot_17_ffx.py in the gallery

Exhaustive search. The energy of a spring, E = 1 2kx2 (Feynman I.14.4), is sampled at 100 points with 1% noise, and every canonical expression of up to six nodes with at most two parameters over {+,−,×,÷,x2} is enumerated:

ex = eq.ExhaustiveRegressor(functions=("add", "sub", "mul", "div", "square"), max_size=6, max_params=2, feature_names=prob.feature_names) 
ex.fit(prob.X_train, prob.y_train) 
print(ex.n_candidates_, "expressions,", len(ex.results_), "distinct functions") 
print(ex.results_.head(6)[["equation", "size", "n_params", "mse", "bic", "mdl"]])
   

There are 2 461 candidates, which compute 913 distinct functions on the data. The description length ranks 0.5005x2k first, by more than 300 nats ahead of the next candidate, (x −1.219)2k (fig. 5.4): the law is found, and the margin says that nothing of this size competes. The cost of the guarantee grows quickly: with a maximum size of 3, 4, 5 and 6 nodes there are 29, 89, 591 and 2 461 candidates, enumerated and fitted in 0.03, 0.06, 0.49 and 2.2 seconds.

Figure 5.4

Figure 5.4. Exhaustive search for the energy of a spring. Left: description length of all distinct candidates by size; the best is circled. Right: the ten best candidates, with the description length above the best on a logarithmic scale.

Open in ColabExample plot_18_exhaustive.py in the gallery

5.5 Further reading

Brunton, Proctor and Kutz [66] introduced sparse identification of nonlinear dynamics with STLSQ; PySINDy [27] implements many of its variants. Tibshirani [67] introduced the Lasso and Friedman, Hastie and Tibshirani [68] the coordinate-descent path; Hastie, Tibshirani and Friedman [72] cover subset selection, shrinkage and splines. McConaghy [70] describes FFX. Bartlett, Desmond and Ferreira [38] and Kammerer et al. [71] develop exhaustive symbolic regression with description-length ranking and grammar-based enumeration.