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

Chapter 10
Analysis of discovered models

A search ends with an equation; the work of the analyst begins there. This chapter collects the tools that turn an evolved expression into a model one can trust and explain. Simplification removes introns and redundant parameters; validation checks the search, not only the final equation, and inspects the residuals; uncertainty quantification gives intervals for the parameters and bands for the predictions; sensitivity analysis says which inputs matter and how they interact. Three tools look beyond one equation: building blocks and variable interaction networks summarize what many good models have in common, model families group equivalent equations, and bootstrap ensembles show which parts of a model the data really support.

10.1 Problem and idea

An equation found by genetic programming is rarely in its simplest form. It contains subtrees that compute constants, additions of terms that cancel, parameters whose product alone is identifiable, and divisions by expressions that vanish. Even after simplification, the equation is one sample of a stochastic search on one sample of data: a different seed, or a different subset of the data, could have produced a different equation of the same accuracy. And even a correct equation has parameters estimated from noisy data, with uncertainties that must be reported.

Because the model is an explicit formula, all these questions can be answered more completely than for a black-box model (fig. 10.1). The formula can be rewritten exactly; its derivatives are available symbolically; its parameter covariance follows from the Jacobian of section 2.2.3; its sensitivity indices can be computed with as many evaluations as needed; and the archive of a run, or the equations of several runs, form a population of models whose common parts are evidence in themselves.

Figure 10.1

Figure 10.1. The analysis of discovered models. A single equation is simplified, validated, given uncertainties and probed for sensitivities; a population of equations reveals the building blocks and families on which many good models agree.

10.2 Theory

10.2.1 Simplification

The simplifier of eqdisco rewrites an expression in four stages, each of which leaves the computed function unchanged except where noted. Constant folding evaluates every subtree without variables and replaces it by a single node. Rewrite rules apply algebraic identities bottom-up: x ±0 = x, x ⋅1 = x, x −x = 0, x∕x = 1, x + x = 2x, x∕(x + x) = 1 2, x2 = |x|, ln ⁡ ex = x, −(−x) = x, a division by a numerically zero constant equals 1 (the protected value), and others; identities that hold for protected operators only away from a singular point are applied, which changes the function on a set of measure zero. Parameter merging flattens every chain of additions and every chain of multiplications, combines their constants into one, cancels identical operands of opposite sign or exponent, and combines like terms (2g + 3g = 5g), which removes redundant parameters in the sense of de França and Kronberger [42]. These three stages are repeated to a fixed point. Optionally, SymPy [11] simplifies the result, and its output is kept only if it is not larger and evaluates to the same values on the data. Finally, the parameters can be refitted and rounded to the fewest significant digits (or simple fractions) that keep the mean squared error within a tolerance.

The rank of the parameter Jacobian (section 2.2.9) counts the identifiable parameters of an expression before and after simplification; a rank below the number of parameters signals redundancy that the rules did not catch.

10.2.2 Validation

An equation selected on the training data must be validated on data it has not seen. Three levels are useful. Holdout validation of the final equation is the minimum. Cross-validation of the search [93] repeats the whole search on k folds and reports the mean and spread of the test error and the structural agreement of the fold equations, the mean pairwise Jaccard similarity of their sets of building blocks; a search that returns very different equations on different folds has not identified a structure, whatever its test error. Extrapolation splits put the samples above a quantile of one variable into the test set and test the model where it will be used beyond the data. Learning curves show how accuracy and equation size change with the amount of data.

The residuals e = y −y^ of a good model are unstructured. eqdisco reports the Shapiro–Wilk test of normality [94], the Durbin–Watson statistic and the Ljung–Box test of autocorrelation in a given order of the samples [95, 96], and the Breusch–Pagan test of heteroscedasticity [97]. Structure in the residuals points to a missing term, a wrong error model, or a dynamic effect.

10.2.3 Uncertainty

With the residual variance s2 = RSS∕(N −p) and the Jacobian J at the estimate, the asymptotic covariance of the parameters is Cov ⁡ (𝜃^) ≈s2(JTJ)−1 [43]. Three kinds of intervals are computed from it or around it. Wald intervals 𝜃^j ±t1−α∕2,N−psej are symmetric and exact only for models linear in the parameters. Profile-likelihood intervals collect the values of 𝜃j for which the residual sum of squares, re-minimized over the other parameters, stays below RSS(𝜃^)(1 + F1,N−p;1−α∕(N −p)); they follow the curvature of the model and are asymmetric where it is. Bootstrap intervals [98] refit the parameters on resampled data and take percentiles. The delta method propagates the covariance to the output: the variance of f^(x) is gT Cov ⁡ (𝜃^)g with g = ∇ ⁡𝜃f(x), which gives the confidence band of the mean response; adding s2 gives the prediction band of a new observation.

10.2.4 Sensitivity

The partial derivatives ∂f∕∂xj of an equation are themselves equations, obtained by SymPy; local sensitivities average their absolute values over the data. Global, variance-based sensitivity treats the inputs as independent random variables on given ranges and decomposes the variance of the output [99]. The first-order index Sj = Var ⁡ (𝔼[f∣xj])∕Var ⁡ (f) is the share of the variance explained by xj alone; the total index STj = 𝔼[Var ⁡ (f∣x−j)]∕Var ⁡ (f) includes all interactions of xj. eqdisco estimates both with the sample designs of Saltelli et al. [100] and the total-index estimator of Jansen [101], at a cost of n(d + 2) model evaluations for d inputs and base sample size n; an explicit equation makes large n cheap. A gap STj −Sj > 0 reveals that xj interacts with other inputs.

10.2.5 Building blocks and variable interactions

The final population or the archive of a run contains many good equations, and the subtrees they share are evidence of useful structure. eqdisco canonicalizes every subtree (constants replaced by a placeholder, commutative arguments ordered), counts in how many equations each occurs (its support), and keeps the frequent ones. A co-occurrence network links two blocks that appear together in more equations than independence predicts (lift above one). The variable interaction network of Kronberger et al. [102] links two variables whenever they occur together below a nonlinear function in a model; the edge weight is the share of models in which they interact, and isolated or rarely linked variables are candidates for removal. The same mining feeds the library learning of section 3.2.8.

10.2.6 Model families (new)

Ten runs of genetic programming on the same data typically return dozens of accurate equations that look different but compute nearly the same function on the data. eqdisco groups them into families by their behavior rather than their syntax, a method new in this package: the semantic distance of two equations is the root-mean-square difference of their predictions on the data divided by the mean standard deviation of the two prediction vectors (or one minus the absolute correlation, which ignores offset and scale), and average-linkage hierarchical clustering cut at a threshold gives the families. Each family is represented by its simplest member. A metric multidimensional scaling of the distance matrix [88] draws the equations as a map. Families answer two questions that a single equation cannot: how many genuinely different explanations fit the data, and whether they agree outside the range of the data, where the families typically diverge.

10.2.7 Bootstrap ensembles

Bagging [103] repeats the search on bootstrap samples of the data. The median of the member predictions is a robust ensemble prediction, and the spread of the members, given as a percentile band, measures model uncertainty, which includes the uncertainty of the structure and is largest where the data are sparse. The frequency with which each variable and each building block occurs among the members shows which parts of the model the data support.

Algorithm

In a nutshell: Analysis of discovered models

  • Simplification folds constants, applies identities, merges parameters and like terms, optionally calls SymPy, refits and rounds; the Jacobian rank counts identifiable parameters.
  • Validate the search by cross-validation with structural agreement and extrapolation splits; test the residuals for normality, autocorrelation and heteroscedasticity.
  • Wald, profile and bootstrap intervals of the parameters; delta-method confidence and prediction bands.
  • Sobol indices Sj and STj quantify main effects and interactions.
  • Building blocks and variable interaction networks summarize populations of models; model families (algorithm 10.1, new) group equivalent equations; bootstrap ensembles show model uncertainty and stable structure.

10.3 Using it in eqdisco

simplify(model, X=None, y=None, sympy=False, refit=False, round_digits=False, tolerance=0.01)

Simplification

simplify.apply_rules, fold_constants, merge_parameters, simplify_sympy, round_coefficients, canonical_form; optimize.jacobian_rank.

Validation

analysis.cross_validate_search(estimator, X, y, cv), extrapolation_split, learning_curve, residual_diagnostics(y, yhat, order), term_table(equation, X, y), structure_agreement.

Uncertainty

analysis.confidence_intervals(equation, X, y, method) with "wald", "profile", "bootstrap"; prediction_intervals(equation, X, y, X_new, kind); parameter_covariance.

Sensitivity

analysis.partial_derivatives, local_sensitivity, sobol_indices(model, bounds, n), permutation_importance.

Populations

analysis.frequent_building_blocks, building_block_network, variable_interaction_network, mine_library, semantic_distance_matrix, model_families(models, X, y, threshold), family_map; SymbolicEnsemble(estimator, n_estimators).

Figures

viz.plot_residuals, plot_prediction_band, plot_partial_dependence, plot_sensitivity, plot_sobol, plot_building_blocks, plot_variable_interactions, plot_families.

10.4 Examples

Simplification. The largest equation on the front of a run on Keijzer-12, x4 −x3 + y2∕2 −y, with 1% noise has 45 nodes and three parameters:

raw = max(sr.pareto_front_, key=lambda e: e.complexity) 
clean = simplify(raw, prob.X_train, prob.y_train, sympy=True, refit=True, round_digits=True) 
print("before:", raw.complexity, "nodes,", raw.n_params, "parameters (rank", jacobian_rank(raw.expr, prob.X_train), ")") 
print("   ", raw) 
print("after: ", clean.complexity, "nodes,", clean.n_params, "parameters") 
print("   ", clean)
   

Its denominator x0 −x0 is zero, so the protected division returns 1 and a large part of the tree collapses; additions and subtractions cancel, and the rest expands to x04 −0.99x03 −0.89x1 + 1.7 after refitting and rounding, 16 nodes. The simplified form has four parameters instead of three, because the original tree forced the coefficients of x04 and x03 to be nearly equal and the expanded form lets them be estimated separately; it also shows plainly that the model replaced the term y2∕2 −y of the target by a straight line, which is accurate on the training range only. Applied to 120 members of the final population, the rules reduce the mean size from 46.5 to 20.6 nodes (fig. 10.2); of the 307 parameters in these equations, 254 are identifiable by the rank of their Jacobian. Rounding trades digits for accuracy: with tolerances of 0, 0.1, 1 and 10% on the mean squared error, the refitted parameters keep on average 6.0, 2.75, 1.75 and 1.0 significant digits.

Figure 10.2

Figure 10.2. Simplification of a population. Left: size of 120 equations before and after the rewrite rules. Right: number of parameters against the rank of the parameter Jacobian; points below the diagonal have redundant parameters.

Open in ColabExample plot_32_simplification.py in the gallery

Validation and uncertainty. Forty rate constants follow the Arrhenius law k = 3 ⋅106e−6000∕T with 6% multiplicative noise. The structure is refitted and checked:

arr = eq.Equation.from_string("1e6*exp(-5000/T)", feature_names=["T"]).refit(X, k, restarts=5, random_state=0) 
print(arr) 
diag = residual_diagnostics(k, arr.predict(X), order=T) 
print({key: round(v, 3) for key, v in diag.items()})
   

The estimates are k0 = 2.64 ⋅106 and E∕R = 5946 K. The residual diagnostics flag what the data generation built in: the Breusch–Pagan test detects heteroscedasticity (p < 0.001) and the Shapiro–Wilk test rejects normality (p < 0.001), as expected from multiplicative noise; fitting ln ⁡ k instead of k would be the right error model. The three interval methods agree for E∕R, whose 95% intervals are [5623,6270] (Wald), [5636,6280] (profile) and [5675,6228] (bootstrap), all containing the true 6000 (fig. 10.3). For the pre-exponential factor they differ: the Wald interval [0.56,4.73] ⋅106 is symmetric, while the profile interval [1.24,5.96] ⋅106 and the bootstrap interval [1.36,5.17] ⋅106 are skewed to larger values, reflecting the strong nonlinearity of the model in k0 and its correlation with E∕R. The width of the profile interval of E∕R is 768, 813, 588, 441 and 221 K with 10, 20, 40, 80 and 160 samples.

Figure 10.3

Figure 10.3. Left: rate constants with the fitted Arrhenius law and its 95% prediction band. Right: Wald, profile-likelihood and bootstrap intervals of the two parameters, relative to the estimates; for k0 the profile and bootstrap intervals are clearly asymmetric.

Open in ColabExample plot_33_validation_uncertainty.py in the gallery

Sensitivity. The Friedman-1 benchmark [65],

y = 10sin ⁡ (πx0x1) + 20(x2 −0.5)2 + 10x 3 + 5x4,

has five further inputs x5,…,x9 that do not enter the function. A multi-gene model reaches a test R2 of 0.912:

model = eq.MultiGeneRegressor(population_size=300, generations=40, max_genes=5, functions=("add", "sub", "mul", "sin", "square"), random_state=0) 
model.fit(prob.X_train, prob.y_train) 
eqn = model.equation_ 
print(eqn, "| test R2", round(eqn.score(prob.X_test, prob.y_test), 4)) 
print(partial_derivatives(eqn).get("x3")) 
S = sobol_indices(eqn, bounds=[(0, 1)] * 10, n=8192) 
print(S.round(3))
   

The model is linear in x3, and its partial derivative with respect to x3 is the constant 9.29 (the true coefficient is 10). The Sobol indices of the model rank the inputs as x3 (S1 = 0.33), x1 (0.25), x0 (0.18), x2 (0.15) and x4 (0.08), and give exactly zero to the five irrelevant inputs, which the model does not use (fig. 10.4). The gap between total and first-order index is largest for x0 (0.21 against 0.18), the input that interacts with x1 in the target. These are the indices of the model, not of the system; for the true Friedman-1 function x0 and x1 have equal indices, and the difference shows where the model is approximate. The estimate is stable: the total index of x0 averages 0.21 to 0.21 for base sample sizes from 256 to 16 384, with a standard deviation that falls from 0.015 to 0.003.

Figure 10.4

Figure 10.4. Sobol indices (left) and scaled mean absolute partial derivatives on the test data (right) of a multi-gene model of Friedman-1. The five irrelevant inputs have zero indices; the gap between total and first-order index of x0 shows its interaction.

Open in ColabExample plot_34_sensitivity.py in the gallery

Building blocks. The final population of a run on Vladislavleva-7, (x −3)(y −3) + 2sin ⁡ ((x −4)(y −4)), with an irrelevant third input z added, is mined for frequent blocks:

pop = sr.population_[:200] 
print(frequent_building_blocks(pop, min_support=0.25).head(8)) 
G = building_block_network(pop, min_support=0.2, min_lift=1.05) 
V = variable_interaction_network(pop) 
print({e: round(d["weight"], 2) for e, d in ((tuple(sorted(e)), V.edges[e]) for e in V.edges)})
   

The blocks sin ⁡ x, sin ⁡ y, c −y and y −x occur in all 200 analyzed equations, and the products sin ⁡ (y)(y −x) and sin ⁡ (x)(c −y) in 98% and 97% of them: the population has settled on a common skeleton built from differences and sines, which is not the true structure but approximates it on the data (fig. 10.5). In the variable interaction network, x and y interact in every equation, z with either of them in only 10%; the network identifies z as irrelevant. The minimum support controls the size of the block network: 30, 24, 12 and 7 blocks at supports of 5, 10, 20 and 40%.

Figure 10.5

Figure 10.5. Left: the co-occurrence network of frequent building blocks of a final population on Vladislavleva-7. Right: the variable interaction network; edge widths are the share of equations in which two variables occur together below a nonlinear function.

Open in ColabExample plot_35_building_blocks.py in the gallery

Model families. Ten runs on 60 noisy samples of sin ⁡ (x2)cos ⁡ x −1 in [−1,1] produce 82 equations with R2 above 0.9:

models = [] 
for s in range(10): 
    sr = eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "sin", "cos", "exp"), random_state=s).fit(X, y) 
    models += [e for e in sr.pareto_front_ if e.metrics["r2"] > 0.9] 
labels, table, Z = model_families(models, X, y, threshold=0.05) 
print(len(models), "models,", len(table), "families") 
print(table.head(6).to_string())
   

At a distance threshold of 0.05 they form three families (fig. 10.6). The largest, with 60 equations, is represented by −1.318 + 0.797sin ⁡ (ecos ⁡ x) and contains the most accurate equation; the second, with 12 equations, by 0.489 −1.455cos ⁡ (sin ⁡ x); the third, with 10, by 0.131 −1.078cos ⁡ x. Inside the range of the data the representatives are nearly indistinguishable; outside it they diverge, so the data cannot decide between the families for extrapolation. The threshold sets the resolution: 0.01, 0.02, 0.05, 0.1 and 0.2 give 19, 11, 3, 2 and 1 families.

Figure 10.6

Figure 10.6. Representatives of the three largest model families of 82 accurate equations from ten runs. They agree inside the range of the data (shaded) and diverge outside it.

Open in ColabExample plot_36_model_families.py in the gallery

Bootstrap ensembles. Fifty samples of y = xe−x∕2 in [0,2] and eight in [3.5,4], with a gap between them, and an irrelevant input z are fitted by ten bootstrap members:

ens = eq.SymbolicEnsemble(eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "exp")), n_estimators=10, feature_names=["x", "z"], random_state=0) 
ens.fit(X, y) 
print(ens.variable_frequency()) 
print(ens.structure_frequency(min_support=0.4).head())
   

All ten members use x, four of them also z; the blocks x + x and c ⋅x occur in six members, c + x in four. The percentile band of the members is narrow where the data are dense and widens in the gap (fig. 10.7). The mean width of the band in the gap is 0.075, 0.078, 0.076 and 0.092 with 3, 5, 10 and 20 members: more members do not narrow the band, they estimate it better, and the twentieth member happened to disagree more in the gap.

Figure 10.7

Figure 10.7. A bootstrap ensemble of ten symbolic models. Left: the data, the member predictions and the median; the spread widens in the gap between 2 and 3.5. Right: the share of members that use each variable.

Open in ColabExample plot_37_ensemble.py in the gallery

10.5 Further reading

De França and Kronberger [42] study redundant parameters of evolved models and remove them by equality saturation. Bates and Watts [43] treat inference for nonlinear regression models, including profile intervals and parameter curvature; Efron and Tibshirani [98] the bootstrap. Arlot and Celisse [93] survey cross-validation for model selection. Sobol’ [99], Saltelli et al. [100] and Jansen [101] developed the variance-based sensitivity indices and their estimators. Kronberger et al. [102] introduced variable interaction networks from symbolic regression runs; the book of Kronberger et al. [18] discusses model inspection and simplification at length.