Chapter 11
From discovery to deployment
A discovered equation becomes useful when it runs where decisions are made: in a control system, a spreadsheet, a data platform or a report. This chapter covers the last steps of the workflow. It shows how equations are exported as source code and as PMML documents that compute exactly what the search evaluated, how they are versioned, documented and tracked, and how a deployed equation is monitored for changes in the process that would make it invalid. It ends with the benchmark tools that compare methods on problems with known solutions and with a one-page report of a search.
11.1 Problem and idea
Machine learning systems accumulate technical debt: the model is a small part of a larger system of data pipelines, configuration, monitoring and serving, and most failures happen outside the model [104]. MLOps applies the practices of software operations to these systems, with versioned models, reproducible training, automated deployment and continuous monitoring [105]. A discovered equation simplifies several of these steps, because it is small, readable and needs no runtime library, but it does not remove them: an equation trained on last year’s operating range is as invalid as a neural network when the process moves, and an equation copied by hand into a control system can be copied wrongly.
eqdisco provides the steps that an equation needs (fig. 11.1): code generation and PMML export that preserve the protected operators of the search, a file-based registry with data fingerprints and stages, model cards that state the intended use and the validity domain, a run tracker with an optional MLflow back end, and a drift monitor that compares new data with the training data.
11.2 Theory
11.2.1 Export
The code generators translate the prefix sequence of an equation into the expression syntax of the target language, with parentheses placed by operator precedence and the protected primitives written as small helper functions (pdiv, plog, …) or inline conditionals in Excel. By default the generated code computes exactly what Equation.predict computes, including the protected values; with protected=False it writes the plain textbook formula, which is easier to read but undefined where a protected operator acts. Python (scalar or NumPy), C, MATLAB, Julia, Excel formulas with cell references and LaTeX are available; JSON stores an equation with its parameters, feature names and metadata and restores it exactly.
The Predictive Model Markup Language (PMML) is an XML standard for exchanging models between analytics systems [106]. eqdisco writes an equation as a DerivedField of the transformation dictionary, built from nested Apply elements of PMML’s built-in functions, and uses it in a regression model with coefficient one. PMML has no protected division or logarithm, so the PMML document computes the plain formula; whether the equation needs its protection on the operating range can be checked, as in section 11.4, by comparing the plain and the protected code on the data.
11.2.2 Registry, model cards and tracking
The registry stores every version of a named equation as a JSON file together with a record: the metrics, the SHA-256 fingerprint of the training data, the range of every input (the validity domain), the software environment, free tags, and a stage (none, staging, production, archived). Versions can be listed, compared, promoted and loaded by stage, so that a deployment refers to “the production version of the quality sensor” rather than to a file. A model card [107] documents an equation for its users: the formula, the method, the intended use and known limitations, the performance metrics, the validation results, the validity domain, and the prior knowledge used; it is written as Markdown, HTML or JSON. The run tracker appends the parameters, metrics and equations of every search to a JSON-lines file and, if MLflow [108] is installed, logs them to its tracking server as well.
11.2.3 Drift monitoring
A deployed equation becomes invalid when the inputs move outside the region it was trained on, or when the relation between inputs and output changes [109]. The DriftMonitor compares each new batch of data with the training data in three ways.
Input distributions. For every input used by the equation, the population stability index compares the shares and of the reference and the new samples in bins defined by the deciles of the reference,
|
| (11.1) |
and a two-sample Kolmogorov–Smirnov test is reported alongside. The customary thresholds 0.1 (moderate shift) and 0.25 (major shift) ignore the sample sizes. For two samples of sizes and from the same distribution, a second-order expansion of the logarithm shows that is asymptotically -distributed with degrees of freedom [110]; with 300 reference and 100 new samples in ten bins, the 95% point of the PSI is 0.23, so the rule of thumb would raise false alarms on small batches. eqdisco therefore uses the larger of the customary threshold and the 95% (warning) or 99% (retraining) point of this distribution.
Extrapolation. The share of new samples outside the box of the training ranges measures how much the equation is asked to extrapolate.
Residuals. When the output is measured, the residuals of the equation are standardized by the reference residual spread, and the Page–Hinkley test [111, 112] accumulates , where for standard normal residuals and is the tolerated drift; it raises an alarm when exceeds the threshold . A small detects a change quickly but also raises false alarms; a large one is safe but slow.
The monitor combines these signals into the status ok, warning or retrain with the reasons spelled out.
11.2.4 Benchmarks
Comparing methods requires problems with known solutions and a criterion for success. The SRBench study [6] counts a run as an exact solution when the difference between the found and the true equation simplifies to a constant, or their ratio to a nonzero constant, after the constants of the found equation have been rounded. eqdisco implements this criterion with SymPy. Because symbolic simplification of large expressions can take minutes, a cheap numerical screen runs first: if neither the difference nor the ratio is nearly constant on sample points, the symbolic test is skipped. Since every equation of eqdisco carries the parameters of linear scaling, an optional relaxation also accepts for the true , tested numerically and reported separately. run_benchmark runs a dictionary of estimators on named problems with several seeds and records the test , the size, the time and the solution flag; summarize reports medians and solution rates.
In a nutshell: From discovery to deployment
- Code generators for Python, NumPy, C, MATLAB, Julia, Excel and LaTeX reproduce the protected operators; PMML 4.4 uses plain built-in functions.
- The registry versions equations with data fingerprints, validity domains, environments and stages; model cards document intended use, performance and limits; runs are tracked locally or in MLflow.
- The drift monitor (algorithm 11.1) checks input distributions by PSI with sample-size-aware thresholds and KS tests, the share of extrapolated samples, and the residuals by the Page–Hinkley test.
- Benchmarks use the SRBench solution criterion, with a numerical screen before symbolic simplification and an optional affine relaxation.
11.3 Using it in eqdisco
export.to_code(model, lang="python", name="f", protected=True)
- Languages
-
to_python(model, numpy=False), to_numpy_function, to_c, to_matlab, to_julia, to_excel(model, cells), to_latex(model, lhs), to_pmml(model, path, target); Equation.to_json, Equation.from_json.
- Registry
-
mlops.ModelRegistry(root) with register(name, equation, X, y, metrics, tags), promote(name, version, stage), load(name, version | stage), list(), compare(name), record.
- Documentation and tracking
-
mlops.ModelCard(equation, name, intended_use, limitations, X, y, validation) with to_markdown, to_html, save; mlops.RunTracker(directory, mlflow); mlops.fingerprint, mlops.environment_info.
- Monitoring
-
mlops.DriftMonitor(equation, X_ref, y_ref, psi_warning, psi_retrain, domain_tolerance, ph_delta, ph_lambda, sample_size_correction=True) with check(X_new, y_new) and page_hinkley(residuals); mlops.population_stability_index, mlops.psi_critical_value.
- Benchmarks and reports
-
benchmarks.run_benchmark(estimators, problems, n_runs, noise), benchmarks.summarize, benchmarks.is_symbolic_solution(found, truth, X, affine); viz.plot_benchmark, viz.plot_drift, viz.plot_dashboard; interactive.pareto_figure.
11.4 Examples
Export. A yield model of two inputs, flow and time, is evolved with parameter optimization, simplified, and exported:
print(export.to_python(eqn, name="yield_model")) print(export.to_c(eqn, name="yield_model")) print(export.to_excel(eqn, {"flow": "B2", "time": "C2"})) print(export.to_latex(eqn, lhs="Y")) pmml = export.to_pmml(eqn, target="yield") print(pmml.count("<Apply"), "Apply elements in the PMML document")
The script prints the same equation as a Python function, a C function with the protected helpers, an Excel formula referring to cells B2 and C2, a LaTeX formula, and a PMML document with 52 Apply elements. Executing the generated Python and NumPy code on the 200 training samples reproduces Equation.predict exactly; the largest difference is zero (fig. 11.2). The parameter study writes the plain formula instead and finds it undefined on all 50 test rows: the evolved equation takes the logarithm of , which is negative over the whole range of the data, and is meaningful only with the protected logarithm . The example shows why the code generators keep the protection by default, and why a PMML export, which cannot, must be checked against the data.
Registry, model card and monitoring. A soft sensor of product quality, plus noise, is evolved from 300 samples, registered, promoted to production and documented:
reg = ModelRegistry(tempfile.mkdtemp()) v = reg.register("quality-sensor", model.equation_, X=X, y=y, tags={"unit": "reactor 2"}) reg.promote("quality-sensor", v, "production") card = ModelCard(model.equation_, "quality-sensor", intended_use="estimate product quality every minute", X=X, y=y) print(reg.list()) print(card.to_markdown()[:600])
The evolved equation, , is the true law up to small corrections, since ; the model card states it with , its 17 nodes and two parameters, the intended use and the validity domain K, . The monitor then receives twelve weekly batches of 100 samples, in which the temperature starts to rise after week 5 and the relation drifts slightly:
monitor = DriftMonitor(reg.load("quality-sensor", stage="production"), X, y) reports = [] for week in range(12): drift = max(0, week - 5) * 6.0 # the temperature rises after week 5 Xw = np.column_stack([rng.uniform(300, 360, 100) + drift, rng.uniform(1, 5, 100)]) yw = 0.02 * Xw[:, 0] * np.sqrt(Xw[:, 1]) * (1 + 0.004 * max(0, week - 5)) + rng.normal(0, 0.05, 100) reports.append(monitor.check(Xw, yw)) print([r["status"] for r in reports])
The status is ok for weeks 0 to 5 and retrain from week 6 on (fig. 11.3), where the PSI of the temperature jumps to 1.23, 8% of the samples fall outside the training box, and the Page–Hinkley test detects the residual drift at the 45th sample of the batch. Without the sample-size correction of the PSI thresholds, five of the six stable weeks would have raised a warning, with PSI values between 0.10 and 0.14 that are entirely due to sampling. The Page–Hinkley threshold sets the trade-off between speed and false alarms: after a sudden offset at sample 200, thresholds of 5, 10, 20 and 40 detect it after 4, 6, 14 and 30 samples, while a threshold of 2 raises an alarm before the change.
Open in ColabExample plot_39_registry_monitoring.py in the gallery
A small benchmark. Five methods are run twice on six problems (Nguyen-1, 5 and 7, Keijzer-11 and 14, Feynman I.12.2) with small budgets:
methods = { "GP": eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "sin", "cos", "exp", "log")), "GP + LM": eq.SymbolicRegressor(population_size=200, generations=20, optimize="lm", functions=("add", "sub", "mul", "div", "sin", "cos", "exp", "log")), "MGGP": eq.MultiGeneRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "div", "sin", "cos")), "FFX": eq.FFXRegressor(), "STLSQ": eq.SparseRegressor(degree=4, functions=("sin", "cos", "exp", "log")), } problems = ["nguyen-1", "nguyen-5", "nguyen-7", "keijzer-11", "keijzer-14", "feynman-I.12.2"] results = run_benchmark(methods, problems, n_runs=2) print(summarize(results).round(3))
All three GP variants reach a median test of 1.000; STLSQ reaches 0.991 and FFX 0.976 (fig. 11.4). Exact recoveries by the SRBench criterion are rarer: 25% of the runs for multi-gene GP and for GP with Levenberg–Marquardt, 17% for plain GP and STLSQ, none for FFX, whose sums of bases are accurate but never the closed-form law. Plain GP returns the smallest equations (median 15.5 nodes), STLSQ the largest (65) and the fastest (1 ms against 0.5 to 1.2 s for GP). The budgets are far too small for conclusions about the methods; the example shows the tools. With noise of 0, 1 and 10% on Nguyen-7 and Keijzer-11, the median test of GP is 0.976, 0.975 and 0.974, of FFX 0.979, 0.979 and 0.977.
A one-page report. Coulomb’s law (Feynman I.12.2), , is sampled at 300 points with 0.5% noise and searched with parameter optimization:
sr = eq.SymbolicRegressor(population_size=400, generations=30, functions=("add", "sub", "mul", "div", "sqrt", "square"), optimize="lm", feature_names=prob.feature_names, random_state=0) sr.fit(prob.X_train, prob.y_train) print("selected: ", sr.equation_) print("simplified:", eq.simplify.simplify(sr.equation_, prob.X_train, prob.y_train, sympy=True, refit=True, round_digits=True)) print("law recovered (affine, tol 1e-2):", eq.benchmarks.is_symbolic_solution(sr.equation_, prob.truth, X=prob.X_test, affine=True, tol=1e-2)) fig = eq.viz.plot_dashboard(sr, prob.X_train, prob.y_train, prob.X_test, prob.y_test)
The selected equation is long, but simplification turns it into , in which and the small corrections are fitted noise; the relaxed criterion with a tolerance of accepts it as the law. Figure 11.5 shows the report: the equation, its tree, the Pareto front on the test data, a parity plot and the convergence of the run. Repeated with three seeds, populations of 100, 200 and 400 recover the law 2, 1 and 3 times in 20 generations.
11.5 Further reading
Sculley et al. [104] describe the hidden technical debt of machine learning systems, and Kreuzberger, Kühl and Hirschl [105] define MLOps and its components. Mitchell et al. [107] proposed model cards; Zaharia et al. [108] describe MLflow; Guazzelli et al. [106] introduce PMML. Gama et al. [109] survey concept drift adaptation, Page [111] and Hinkley [112] the cumulative-sum tests behind the Page–Hinkley detector, and Yurdakul and Naranjo [110] the statistical properties of the population stability index. La Cava et al. [6] define the SRBench benchmark and its solution criterion; White et al. [5] discuss what makes a good benchmark for genetic programming.