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

Chapter 6
Probabilistic and language-guided search

Genetic programming returns a few good equations but says little about how certain the identification is. This chapter presents three methods that treat the search as sampling from a distribution over expressions. The Bayesian machine scientist samples structures in proportion to their approximate posterior probability; the grammar cross-entropy search, new in eqdisco, learns a probabilistic grammar from the best expressions it has seen; and language-model proposers draw candidates from the knowledge of the scientific literature that large language models have absorbed. The chapter ends with the safety measures that are needed when text written by a model becomes an equation.

6.1 Problem and idea

Twenty measured rates of an enzyme reaction are explained almost equally well by the Michaelis–Menten law v = V maxS∕(Km + S) [73], by v = a(1 −e−bS), and by a dozen larger equations. A search that returns one of them hides this ambiguity. A Bayesian view makes it explicit: every structure f has a posterior probability p(f∣D) ∝p(D∣f)p(f), the product of the evidence of the data for the structure and a prior that encodes which equations are plausible before seeing the data. Sampling structures in proportion to their posterior shows which equations compete and how much the data prefer one over the others [74].

The three methods of this chapter differ in where the distribution over expressions comes from (fig. 6.1). The Bayesian machine scientist defines it explicitly by an energy and samples it by Markov chain Monte Carlo. The grammar cross-entropy search learns a sampling distribution from the best expressions found so far, as probabilistic incremental program evolution [75] and deep symbolic regression [76] do. A language model brings a distribution learned from text, which knows that rates saturate, that forces fall with the square of the distance, and that physical laws respect units [55, 77, 78].

Figure 6.1

Figure 6.1. Three ways of sampling equations. The Bayesian machine scientist samples an explicit posterior; the grammar cross-entropy search learns its sampling distribution from the best expressions; a language model proposes skeletons from scientific context and receives the best fits as feedback.

6.2 Theory

6.2.1 The Bayesian machine scientist

Guimerà et al. [74] define the energy of an expression f with fitted parameters as

E(f) = 1 2BIC(f) + ∑ o∈fλo,
(6.1)

where the BIC approximates −2ln ⁡ p(D∣f), the marginal likelihood of the structure, and λo is the prior cost of each operation o in f; at unit temperature e−E is then proportional to the posterior probability of the structure. In the original work the prior costs were estimated from a corpus of equations; eqdisco uses a common cost prior_penalty per operation or a dictionary of costs. The structures are sampled by a Metropolis chain whose moves replace a node by another of the same arity, regrow a subtree, add a new root or remove the root. The posterior landscape is rugged, so several chains run at temperatures 1 = T1 < T2 < … and exchange their states every few steps (parallel tempering); the hot chains cross barriers and pass good structures to the cold one.

eqdisco reports the visited structures with two estimates of their posterior probability. The share of the unit-temperature chain converges to the posterior only for long chains. The energy-based estimate normalizes e−E over the visited structures, a BIC approximation of Bayesian model averaging that is reliable as soon as the competitive structures have been visited. The proposal distribution of the moves is not exactly symmetric, so the chain targets the posterior only approximately; the sample serves to rank structures and to measure how decisive the data are.

Algorithm

6.2.2 Grammar cross-entropy search (new)

The cross-entropy method [79] optimizes by sampling: it draws candidates from a parametric distribution, keeps the best fraction, and refits the distribution to them. Applied to expressions, the distribution is a probabilistic grammar. eqdisco uses a table P(s∣c) that gives the probability of the symbol s (a function, a variable or a constant) in the context c = (parent symbol,argument position), so that the table can learn, for example, that the first argument of a product is often a sine. Each iteration samples a batch of expressions top-down from the table, fits their constants, scores them by the reward 1∕(1 + NRMSE) after linear scaling, keeps the elite above the 1 −𝜀 quantile of the rewards, and moves every row of the table toward the symbol frequencies of the elite with a learning rate; a floor on the probabilities keeps every symbol reachable. Keeping only the best few percent is the risk-seeking principle of deep symbolic regression [76]: what matters is the best expression, not the average one. Petersen et al. train a recurrent network by policy gradients for this purpose; the tabular version of eqdisco, new in this package, needs no network, converges in a few dozen iterations on small problems, and its table can be read: the probabilities show which structure the search believes in.

6.2.3 Language models as proposers

Large language models have read a large share of the scientific literature and can propose equations that fit a verbal description of a problem. Merler et al. [77] let a model refine a functional form iteratively from the data and the errors of earlier proposals, with an external optimizer for the coefficients (in-context symbolic regression); Shojaee et al. [78] represent equations as programs, let the model propose skeletons from the scientific context, and evolve them with a numerical optimizer (LLM-SR); Grayeli et al. [55] abstract the best hypotheses of a genetic programming run into textual concepts that guide later proposals (LaSR); FunSearch [80] pairs a model with an evaluator to discover programs. Common to all is a loop of prompt, proposals, numerical fitting and feedback.

eqdisco implements this loop without depending on any provider. A proposer is any Python callable that maps a prompt to text, so it can wrap the client library of any model. The prompt (llm.build_prompt) states the task and the meaning and units of the variables, summarizes the data, lists sample rows and the best equations found so far with their errors, and asks for new candidates with constants written as c0, c1, …. The answer is parsed line by line into expressions whose constants become free parameters, the parameters are fitted by Levenberg–Marquardt with restarts, and the pool of evaluated equations is updated. Proposals can also be injected into the population of genetic programming every few generations (llm_proposer of SymbolicRegressor). An offline TemplateProposer, which draws from a list of templates, makes the loop testable and serves as a knowledge-based baseline.

Safety. Text written by a model is untrusted input. SymPy’s parser evaluates its input as Python code, so passing the answer of a model directly to it would let the model execute arbitrary code. eqdisco therefore screens every proposal before parsing: the text may contain only digits, letters, arithmetic operators, parentheses, commas, dots and spaces, no double underscores and at most 2 000 characters, and every identifier must be a variable name, a constant name c0, c1, …, or a known function. Lines that fail the check are discarded silently, and every prompt sent is kept in prompts_ for auditing.

In a nutshell: Probabilistic and language-guided search

  • The Bayesian machine scientist (algorithm 6.1) samples structures with energy 1 2BIC plus a prior; the normalized e−E over the visited structures estimates their posterior and shows how decisive the data are.
  • The grammar cross-entropy search (new) learns a context-dependent symbol table from the best few percent of each batch; its table can be read.
  • Language models propose equation skeletons from context and feedback; eqdisco accepts any callable as proposer, fits the constants, and screens every proposal before parsing.
  • Main parameters: prior_penalty, temperatures, n_steps; elite_fraction, batch_size, learning_rate; proposer, n_proposals, n_iterations.

6.3 Using it in eqdisco

BayesianSymbolicRegressor(functions=..., n_steps=2000, temperatures=(1.0, 1.6, 2.6, 4.2), prior_penalty=1.0, prior=None, ...)

Results

equation_ (the maximum a posteriori structure), posterior_ (equation, posterior, share, energy, BIC, size), trace_, acceptance_, pareto_front_.

Related

GrammarCERegressor(n_iterations, batch_size, elite_fraction, learning_rate, ...) with probabilities_ and history_; LLMGuidedRegressor(proposer, n_iterations, n_proposals, description, ...) with prompts_; TemplateProposer(templates, n); llm.build_prompt, llm.parse_proposals, llm.propose_expressions; viz.plot_posterior.

A real model is connected by a function of a few lines. With the client library of Anthropic, for example (the model name is an example):

import anthropic 
client = anthropic.Anthropic() 
def proposer(prompt): 
    msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=400, 
                                 messages=[{"role": "user", "content": prompt}]) 
    return msg.content[0].text 
model = eq.LLMGuidedRegressor(proposer, n_iterations=5, description="...").fit(X, y)

6.4 Examples

How certain is Michaelis–Menten? Twenty rates of an enzyme reaction with 3% noise are sampled with four chains at temperatures 1, 1.6, 2.6 and 4.2 for 2 500 steps:

bms = eq.BayesianSymbolicRegressor(functions=("add", "sub", "mul", "div", "exp", "log"), n_steps=2500, temperatures=(1.0, 1.6, 2.6, 4.2), feature_names=["S"], random_state=0) 
bms.fit(X, v) 
print(bms.posterior_.head(6)[["equation", "posterior", "share", "energy", "size"]]) 
print("MAP model:", bms.equation_, "| acceptance:", np.round(bms.acceptance_, 2))
   

The maximum a posteriori model is

v = −0.0023 + 1.003 ⋅ 2S 0.6088 + S,

the Michaelis–Menten law with V max ≈2.0 and Km ≈0.61 (true values 2.0 and 0.6). It carries an estimated posterior probability of 0.29 (fig. 6.2). The second structure, 1∕(0.7345 + S) with probability 0.26, is the same three-parameter family written differently: with linear scaling, a + b∕(K + S) and a + 2bS∕(K + S) describe the same curves, so the data cannot prefer one form over the other. Its slightly higher energy and its different K come from a less converged parameter fit, a reminder that the posterior of structures inherits the errors of the parameter estimation. The next four structures are again Michaelis–Menten forms with a redundant exponential or logarithm, so most of the posterior mass lies on one law. The acceptance rates of the four chains are between 0.31 and 0.35.

The prior decides how much complexity the posterior tolerates. Without a prior cost per operation (penalty 0), the posterior mass is spread over sizes 6 to 11; with the default penalty 1, 58% of the mass lies on structures of size 8 and 21% on size 9; with penalty 3 the prior dominates and 82% of the mass lies on trivial structures of size 2.

Figure 6.2

Figure 6.2. Posterior sampling of enzyme kinetics. Left: energy of the unit-temperature chain. Middle: the structures with the highest estimated posterior probability. Right: the data with the three most probable models.

Open in ColabExample plot_19_bayesian.py in the gallery

Learning a grammar. Nguyen-10, 2sin ⁡ xcos ⁡ y, is searched by the grammar cross-entropy method with batches of 300 expressions and an elite of 5%:

gce = eq.GrammarCERegressor(functions=("add", "sub", "mul", "sin", "cos"), n_iterations=40, batch_size=300, elite_fraction=0.05, random_state=0, feature_names=["x", "y"]) 
gce.fit(prob.X_train, prob.y_train) 
print(gce.equation_) 
root = gce.probabilities_[(-1, 0)] 
print("root symbol probabilities:", {k: round(p, 2) for k, p in sorted(root.items(), key=lambda kv: -kv[1])[:4]})
   

After 40 iterations the best expression is exactly 2sin ⁡ xcos ⁡ y, and the learned table puts probability 0.97 on a product at the root (fig. 6.3): the search distribution has concentrated on the right structure. The entropy of the table falls as the elite becomes homogeneous. The elite fraction is the main parameter, and its effect is not monotone: with elites of 1, 5, 20 and 50%, the mean best reward after 25 iterations is 0.949, 0.996, 0.949 and 0.983 in three runs each. A very small elite learns from too few examples, a large one from mediocre ones.

Figure 6.3

Figure 6.3. Grammar cross-entropy search on Nguyen-10. Left: best and mean elite reward (blue) and the mean entropy of the table (vermilion) over the iterations. Right: the learned probabilities of the root symbol.

Open in ColabExample plot_20_grammar_ce.py in the gallery

Proposals from domain knowledge. Thirty enzyme rates are given to the proposer loop together with a description of the task and the variable. The offline template proposer stands in for a language model, so the example runs without network access:

templates = ["c0*x0", "c0*x0/(c1 + x0)", "c0*(1 - exp(-c1*x0))", "c0*x0^c1", "c0*log(1 + c1*x0)", "c0*x0^2/(c1 + x0^2)", "c0*x0/(c1 + x0 + c2*x0^2)"] 
proposer = eq.TemplateProposer(templates, n=3, random_state=1) 
llm = eq.LLMGuidedRegressor(proposer, n_iterations=5, n_proposals=3, feature_names=["S"], 
                            description="initial rate of an enzyme reaction as a function of the substrate concentration", 
                            variable_descriptions={"S": "substrate concentration, mmol/L"}) 
llm.fit(X, v) 
print(llm.equation_) 
print(llm.prompts_[0][:500])
   

The first prompt states the task, the meaning and unit of S, a summary of the data and eight sample rows, and asks for three candidates; the script prints it. The loop returns 1.993S∕(S + 0.5868), Michaelis–Menten with the right constants (fig. 6.4). Given to genetic programming as an injection source, the same proposer leads to −0.0022 + 1.994S∕(S + 0.585) after ten generations. With this offline proposer, one proposal per iteration reaches a final error of 7.1 ⋅10−4, three or six proposals 6.9 ⋅10−4, the level of the noise. A real language model brings a much larger repertoire than seven templates, and its value lies precisely in proposing forms that a generic search would reach only by chance; its proposals must be checked by the same fitting and validation as any other.

Figure 6.4

Figure 6.4. An iterative proposal loop for enzyme kinetics. Left: best mean squared error of the pool over the iterations. Right: the data with the three largest equations of the final Pareto front.

Open in ColabExample plot_21_llm_proposals.py in the gallery

6.5 Further reading

Guimerà et al. [74] introduced the Bayesian machine scientist and discuss priors learned from corpora of equations. Sałustowicz and Schmidhuber [75] proposed probabilistic incremental program evolution, an early estimation-of-distribution algorithm for programs; Rubinstein and Kroese [79] describe the cross-entropy method; McKay et al. [81] survey grammar-based GP. Petersen et al. [76] introduced risk-seeking policy gradients for symbolic regression; Biggio et al. [29] and Kamienny et al. [30] pretrain transformers to map data to equations. Merler et al. [77], Shojaee et al. [78] and Grayeli et al. [55] represent the first generation of methods that use language models for equation discovery.