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

Chapter 4
Linear-in-parameters models: OLS, MGGP and GP-OLS

Many models of engineering practice are sums of nonlinear terms with linear weights: polynomial and NARX models, rate laws with several mechanisms, empirical correlations. This chapter shows how this structure makes the search easier. Orthogonal least squares estimates the weights and measures the contribution of each term by its error reduction ratio; multi-gene genetic programming evolves the terms; and GP-OLS, the method from which eqdisco grew, uses the error reduction ratio to prune the terms that do not contribute. Two new methods follow, ERR-guided variation and a cooperative algorithm in which the population is a library of terms, both evaluated honestly on test problems.

4.1 Problem and idea

A tree evolved by genetic programming mixes structure and parameters: changing one node can change the meaning of the whole tree. Many target functions, however, are of the form

y = w0 + ∑ j=1mw jφj(x) + e,
(4.1)

a weighted sum of nonlinear terms φj (genes) with linear weights wj. Such linear-in-parameters models include polynomial models, the nonlinear autoregressive models with exogenous inputs (NARX) of system identification [58, 59], and most empirical correlations of chemical engineering. For a given set of terms the weights follow from linear least squares in one step; only the terms have to be searched. Hinchliffe, McKay and Willis applied this idea to process modeling [60, 61], and Searson’s GPTIPS made it popular as multi-gene genetic programming [21, 22].

The structure offers more than fast weights. Orthogonal least squares [62] decomposes the explained variance of the model into contributions of the individual terms, the error reduction ratios. GP-OLS [1] uses them to prune: a tree built from additions and multiplications is read as a sum of terms, OLS assigns each term its contribution, and terms below a threshold are cut from the tree before it reproduces (fig. 4.1). The search is spared from carrying useless terms, and the models stay small and interpretable.

Figure 4.1

Figure 4.1. The idea of GP-OLS. The additions at the top of a tree split it into terms; orthogonal least squares estimates their weights and error reduction ratios; terms whose ratio is below the threshold δ (vermilion) are removed from the tree, which then carries only the terms that explain the data.

4.2 Theory

4.2.1 Orthogonal least squares and the error reduction ratio

Let Φ = [φ1,…,φm] ∈ ℝN×m hold the values of the terms on the data, with the columns and y centered so that the intercept drops out. Orthogonal least squares [62] factors Φ = WA with an upper unit-triangular A and mutually orthogonal columns w1,…,wm of W, computed by the modified Gram–Schmidt procedure in a chosen order of the terms. In the orthogonal basis the model is y = ∑ ⁡ jgjwj + e with gj = wjTy∕wjTwj, and the sum of squares of y splits into independent parts:

yTy = ∑ j=1mg j2w jTw j + eTe,ERR j = gj2wjTwj yTy .
(4.2)

The error reduction ratio ERRj is the share of the output variance that term j explains in addition to the terms before it; because y is centered, the ratios sum to the coefficient of determination R2 of the model. The weights of the original terms follow from Aw = g by back substitution. The ratios depend on the order: a term that is correlated with an earlier one receives only what the earlier one did not explain. Forward regression with OLS (FROLS) [59, 62] removes the arbitrariness by choosing at every step, among the remaining candidates, the term with the largest ratio given the terms already chosen, and stops when the ratio falls below a tolerance or when an information criterion stops improving.

Algorithm

4.2.2 Multi-gene genetic programming

In multi-gene GP (MGGP) an individual is a list of up to m genes, each an expression tree, and its prediction is the least-squares combination (4.1). Variation acts on two levels [21]: high-level crossover exchanges whole genes between two individuals, low-level crossover exchanges subtrees between one gene of each parent, and gene-level mutations add a new random gene or delete one. The weights are re-estimated for every new individual, with a tiny ridge penalty that keeps the estimate stable when two genes are collinear. Arnaldo, Krawiec and O’Reilly [63] pushed the idea further by regressing on all subtrees of a single tree.

4.2.3 GP-OLS

GP-OLS [1] was proposed for the identification of linear-in-parameters input–output models of dynamical systems, such as NAARX and polynomial ARMA models. With the function set {+,×} every tree is a polynomial; the additions at the top of the tree separate it into terms, and the products below them form the monomials. Orthogonal least squares computes the weights and the error reduction ratio of every term, and terms whose ratio is below a threshold δ are removed from the tree, which is written back into the population (Lamarckian pruning). The fitness of the pruned tree combines its error with a penalty on its size. Any function set can be used in eqdisco; the default is {+,×} as in the paper.

Pruning by the ratios of a single orthogonalization inherits their order dependence: when two terms are nearly collinear, the first one in the order receives a large ratio and the second a small one, even if the second carries the real information. eqdisco therefore adds a backward check: after the forward pruning, the unique contribution of each remaining term, uj = R2 −R(−j)2, the loss of explained variance when the term alone is removed, is computed, and terms with uj < δ are removed one by one, the smallest first. The check is independent of the order and removes terms that are redundant given all the others.

Algorithm

4.2.4 ERR-guided variation (new)

The error reduction ratios also say which genes of an individual are weak and which are strong. ERR-guided variation, new in eqdisco, uses this information in the variation of MGGP: in high-level crossover and gene-level mutation the gene to be replaced is drawn with probability proportional to 1∕(sj + 0.02), where sj is its share of the explained variance, and the gene donated to the other parent is drawn with probability proportional to sj + 0.02 (err_guided=True) or uniformly (err_guided="replace"). The expectation is that weak genes are replaced faster and strong genes spread faster. The operator is experimental and switched off by default, because the benchmark in section 4.4 did not show an advantage.

4.2.5 Cooperative OLS–GP (new)

In GP-OLS every individual is a complete model. The cooperative algorithm of eqdisco, new in this package, turns the population itself into a library of candidate terms. In every generation FROLS (algorithm 4.1) selects from the whole population the subset of terms that best explains the target; the selected individuals form the current model. Credit is assigned by orthogonal least squares: a selected individual earns its error reduction ratio, and an individual that was not selected earns the share of the residual variance it could explain, its squared correlation with the residual of the current model. The members of the model are kept unchanged, and the others are replaced by offspring of tournament-selected parents, so the population is pushed toward the part of the data that the model does not yet explain. The forward selection path is a sequence of nested models of increasing size and gives the Pareto front of accuracy and complexity without extra cost. The idea combines GP-OLS with the cooperative coevolution of features in evolutionary feature synthesis [64] and with FROLS.

In a nutshell: Linear-in-parameters models

  • A model w0 + ∑ ⁡ jwjφj(x) needs only its terms to be searched; the weights follow from least squares.
  • Orthogonal least squares assigns each term its error reduction ratio (4.2); the ratios sum to R2 but depend on the order; FROLS chooses the order greedily (algorithm 4.1).
  • MGGP evolves lists of genes with high- and low-level crossover; GP-OLS prunes the terms with small ratios from the trees (algorithm 4.2); eqdisco adds an order-independent backward check.
  • ERR-guided variation (new, experimental) and the cooperative OLS–GP library (new) use the ratios to guide the search.
  • Main parameters: max_genes, functions, err_threshold (the threshold δ), backward_check, p_high_level.

4.3 Using it in eqdisco

GPOLSRegressor(population_size=300, generations=50, max_genes=6, functions=("add", "mul"), err_threshold=0.01, backward_check=True, ...)

err_threshold

the pruning threshold δ on the error reduction ratio and on the unique contribution.

backward_check

remove terms whose unique contribution is below δ after the forward pruning.

err_guided

False, True or "replace" (section 4.2.4).

Inherited from MultiGeneRegressor

max_genes, init_depth, max_depth, p_crossover, p_high_level, p_add_gene, p_delete_gene, p_constant, ridge, parsimony, selection, model_selection.

Results

equation_, genes_, coef_, intercept_, gene_table() (terms, sizes, weights, ERR), pareto_front_, history_.

Related

MultiGeneRegressor, CooperativeOLSRegressor, ols.ols_err, ols.forward_ols, viz.plot_terms, viz.plot_err_path.

4.4 Examples

The error reduction ratio and its order dependence. The target y = 1.2x0 + 0.9x2 −0.8x0x1 plus 2% noise is generated with x2 = 0.9x0 + 0.2u, so that x2 is strongly correlated with x0. FROLS searches the ten terms of the full quadratic polynomial of three variables:

terms = polynomial_library(3, degree=2) 
Phi = library_matrix(terms, X) 
res = forward_ols(Phi, y, criterion="bic") 
labels = [t.to_string() for t in terms] 
for j in res.order: 
    print(f"{labels[j]:10s} ERR = {res.err[j]:.4f}  weight = {res.coef[j]: .3f}")
   

It selects x0 (ERR = 0.9439), x0x1 (0.0478) and x2 (0.0080) and stops; the weights 1.190, −0.801 and 0.912 are the true ones up to the noise. The small ratio of x2 does not mean that x2 is unimportant: when the same three terms are orthogonalized in the reverse order, x2 receives 0.9407 and x0 only 0.0159, and in the order x0x1,x0,x2 the ratios are 0.0094, 0.9823 and 0.0080 (fig. 4.2). The sum is always the same; its split reflects the order whenever terms are correlated. With noise levels of 0, 0.05, 0.2 and 0.5, the BIC, the AIC and an ERR tolerance of 10−3 all stop at the three correct terms.

Figure 4.2

Figure 4.2. Left: the ERR path of forward selection over a quadratic library; the cumulative sum approaches R2. Right: the ratios of the three selected terms in three orders of orthogonalization. Because x2 is correlated with x0, whichever of the two comes first receives the shared variance.

Open in ColabExample plot_11_ols_err.py in the gallery

Multi-gene GP. The rate r = 2cAcB −0.5cA2 + 0.3cB∕(1 + cA), a sum of three mechanisms, is searched with at most four genes and the four arithmetic operations:

mg = eq.MultiGeneRegressor(population_size=250, generations=30, max_genes=4, functions=("add", "sub", "mul", "div"), feature_names=["cA", "cB"], random_state=0) 
mg.fit(X, r) 
print(mg.equation_) 
print(mg.gene_table())
   

The search returns exactly the three mechanisms, with weights 2.001, −0.501 and 0.299. The third gene is printed as cB∕(cA∕cA + cA): without constants in the function set, GP builds the number 1 as cA∕cA, a harmless redundancy that the simplifier of chapter 10 removes. The error reduction ratios, 0.900, 0.098 and 0.002, say that the bimolecular term dominates and the inhibition term is a small correction (fig. 4.3). The number of genes matters up to the number of mechanisms: with at most 1, 2, 4 and 6 genes the median final normalized error is 2.6 ⋅10−3, 8.6 ⋅10−5, 4.3 ⋅10−5 and 4.0 ⋅10−5.

Figure 4.3

Figure 4.3. A multi-gene model of a reaction rate with three mechanisms. Left: the Pareto front of the run with the selected 23-node model circled. Right: the error reduction ratios of its three genes.

Open in ColabExample plot_12_mggp.py in the gallery

GP-OLS against plain MGGP. The polynomial y = 2x0x1 −1.5x22 + 0.5x0x2x3 with 2% noise is searched by GP-OLS and by MGGP with the same function set {+,×}, population and number of generations:

gpols = eq.GPOLSRegressor(population_size=250, generations=30, max_genes=6, err_threshold=0.01, random_state=0).fit(X, y) 
mggp = eq.MultiGeneRegressor(population_size=250, generations=30, max_genes=6, functions=("add", "mul"), random_state=0).fit(X, y) 
print("GP-OLS:", gpols.equation_) 
print("MGGP:  ", mggp.equation_) 
print(gpols.gene_table())
   

GP-OLS returns the three true terms with weights 1.999, −1.500 and 0.4999 and error reduction ratios 0.659, 0.326 and 0.015. MGGP finds the same three terms but keeps four more with tiny weights, among them a product of three sums; its model has 57 nodes against 21 and is no more accurate (fig. 4.4). The mean size of the individuals stays lower under GP-OLS throughout the run, because the pruned trees carry no dead terms. The threshold decides what counts as a term: thresholds of 10−3, 5 ⋅10−3 and 10−2 keep all three terms (R2 = 0.99917), while 0.05 and 0.1 remove the third term, whose ratio is 0.015, and the model drops to R2 = 0.98453.

Figure 4.4

Figure 4.4. GP-OLS prunes what multi-gene GP keeps. Left: error reduction ratios of the three terms of the GP-OLS model. Right: mean size of the individuals during the two runs; the final models have 21 (GP-OLS) and 57 nodes (MGGP).

Open in ColabExample plot_13_gpols.py in the gallery

Does ERR guidance help? A six-term polynomial in six variables is searched ten times by MGGP with uniform variation, with guided replacement only, and with full guidance:

final, hist = {}, {} 
for name, g in variants.items(): 
    runs = [eq.MultiGeneRegressor(population_size=150, generations=25, max_genes=8, functions=("add", "mul"), err_guided=g, random_state=s).fit(X, y) for s in range(10)] 
    hist[name] = np.array([r.history_["best_loss"] for r in runs]) / np.var(y) 
    final[name] = hist[name][:, -1] 
print({k: f"{np.median(v):.2e}" for k, v in final.items()}) 
print("Mann-Whitney p (uniform vs fully guided):", stats.mannwhitneyu(final["uniform"], final["fully guided"]).pvalue)
   

The median final normalized errors are 1.48 ⋅10−2, 1.49 ⋅10−2 and 2.00 ⋅10−2, and the Mann–Whitney test finds no difference between uniform and full guidance (p = 0.91; fig. 4.5). The parameter study varies the share of high-level crossover (0.1, 0.3 and 0.6) with three runs per setting and is equally inconclusive: the median errors are 2.9 ⋅10−2, 8.2 ⋅10−5 and 2.9 ⋅10−2 with uniform variation and 1.8 ⋅10−3, 7.8 ⋅10−3 and 1.7 ⋅10−2 with full guidance, jumps of orders of magnitude without a pattern that would favor either. The operator is therefore off by default. An honest negative result is useful: the ratios already act through pruning in GP-OLS, and steering variation by them adds little on this problem.

Figure 4.5

Figure 4.5. ERR-guided variation does not beat uniform variation. Left: median normalized error over ten runs per variant. Right: final errors of the ten runs; the Mann–Whitney test between uniform and fully guided variation gives p = 0.91.

Open in ColabExample plot_14_err_guided.py in the gallery

The cooperative library. The target y = 2sin ⁡ x0 + x1x2 + 1∕(1 + x22) with 1% noise mixes a periodic, a multiplicative and a rational term. The cooperative algorithm uses a population of 150 terms and at most six terms in the model:

coop = eq.CooperativeOLSRegressor(population_size=150, generations=30, max_terms=6, random_state=0).fit(X, y) 
print(coop.equation_) 
print(coop.history_.tail(3))
   

The returned model, the one with the lowest BIC over all generations, contains 2sin ⁡ x0 and 1 ⋅x1x2 with the exact weights and approximates the rational term by four smooth functions of x2; its error 1 −R2 = 2.5 ⋅10−5 is at the level of the noise (fig. 4.6). The left panel of the figure shows a property of greedy forward selection: after generation 20 the current model becomes worse although its six members are kept, because new candidates in the library can lead the greedy path to a different and poorer set of six terms. This is why the estimator keeps the best model over the whole run. The population size matters little on this problem: with 40, 80, 150 and 300 terms, the median 1 −R2 is 2.6 ⋅10−5, 2.6 ⋅10−5, 2.5 ⋅10−5 and 2.5 ⋅10−5. The rational term is not found in closed form because the shared library rewards any term that reduces the residual, and four smooth terms do so earlier than the exact quotient; a smaller max_terms or a function set with division changes this balance.

Figure 4.6

Figure 4.6. A cooperative OLS–GP run. Left: 1 −R2 of the current model (blue) and its number of terms (vermilion) over the generations. Right: the Pareto front of the nested models along the forward selection path.

Open in ColabExample plot_15_cooperative.py in the gallery

4.5 Further reading

Chen, Billings and Luo [62] introduced orthogonal least squares with the error reduction ratio for nonlinear system identification; Billings [59] gives a complete account of NARMAX modeling with FROLS. McKay, Willis and Barton [60] and Hinchliffe and Willis [61] applied multi-gene GP to chemical processes; Searson [21, 22] describes GPTIPS. Madár, Abonyi and Szeifert [1] proposed GP-OLS and applied it to the identification of input–output models; chapter B maps the functions of their MATLAB toolbox to eqdisco. Arnaldo, Krawiec and O’Reilly [63] and Arnaldo, O’Reilly and Veeramachaneni [64] develop regression on subtrees and cooperative feature synthesis.