Chapter 3
Genetic programming
Genetic programming is the oldest and most widely used search method of symbolic regression. This chapter builds it from its parts: the initial population, the variation operators that create new expressions from old ones, the selection schemes that decide which expressions reproduce, the control of bloat, the tuning of constants inside the search, the island model, and the archive of non-dominated equations from which one model is finally selected. It closes with library learning, a new mechanism of eqdisco that reuses building blocks found during the run. The examples compare the alternatives on benchmark problems and report where they help and where they do not.
3.1 Problem and idea
The space of expressions is too large to enumerate beyond a handful of nodes (section 2.2.5), but it has structure: an expression that is close to the target usually contains parts that are useful in other expressions too. Genetic programming [16, 28] exploits this structure in the way evolution does. It keeps a population of candidate expressions, lets the better ones reproduce more often, and creates offspring by recombining parts of two parents (crossover) or by changing a random part of one parent (mutation). Over the generations good parts spread through the population and are combined into better wholes (fig. 3.1).
The difficulty of GP is not to make it work but to make it work reliably. The search is stochastic, it converges prematurely to a few structures, its programs grow without improving (bloat), and the numerical constants are hard to evolve by random changes. Each section of the theory addresses one of these problems with the remedies that the literature found most effective.
3.2 Theory
3.2.1 Initialization
The grow method builds a random tree top-down, choosing at each node between functions and terminals until a maximum depth forces terminals; the full method uses only functions above the maximum depth, which gives bushy trees. Koza’s ramped half-and-half [16] creates half of the population by each method, with maximum depths spread over a range (by default 2 to 5), so that the initial population contains trees of many shapes and sizes. Luke’s PTC2 [44] draws a target size first and grows the tree breadth-first until the size is reached, which controls the size distribution directly. Duplicates are discarded. Terminals are variables or, with probability p_constant, constants drawn uniformly from const_range.
3.2.2 Variation
Subtree crossover replaces a random subtree of the first parent by a random subtree of the second; inner nodes are chosen with probability 0.9, Koza’s bias against exchanging single leaves. Subtree mutation replaces a random subtree by a new random tree; point mutation replaces a node by another of the same arity; hoist mutation replaces the tree by one of its subtrees and shrink mutation a subtree by a terminal, both of which reduce size; insertion wraps a subtree into a new function; constant mutation perturbs the parameters by Gaussian noise. An offspring that violates the size or depth limit is discarded and replaced by a copy of its parent.
Syntactic crossover ignores what the exchanged subtrees compute: a large subtree can be replaced by one with identical outputs (no change) or with completely different outputs (a random jump). Uy et al. [45] proposed semantic similarity-based crossover: subtree pairs are drawn until the mean absolute difference of their outputs on the training data lies between a lower and an upper threshold ( and 0.4 by default), so that offspring differ from their parents in small but real semantic steps.
3.2.3 Selection
Tournament selection draws individuals at random and selects the one with the lowest loss; the tournament size sets the selection pressure. Double tournament [46] holds two fitness tournaments and lets the smaller of the two winners win with probability ( by default), which adds a mild, non-parametric pressure toward small programs. -lexicase selection [47, 48] does not aggregate the errors over the training cases: it shuffles the cases and, case by case, keeps only the candidates whose absolute error is within of the best on that case, where is the median absolute deviation of the population’s errors on the case. Individuals that are excellent on a subset of the cases survive even if their mean error is mediocre, which maintains diversity.
NSGA-II [49] treats error and complexity as two objectives. Parents and offspring are sorted into non-dominated fronts; the next population is filled front by front, and the last front that does not fit is thinned by the crowding distance, which prefers isolated points. In symbolic regression the small expressions tend to fill the first front with copies, so eqdisco removes structural duplicates before the sorting. Age–fitness Pareto optimization (AFP) [50] replaces complexity by age: every individual carries the number of generations since its oldest ancestor was created, offspring inherit the age of their older parent plus one, and a few new random individuals of age zero enter every generation. Selection on the two objectives protects young individuals from being eliminated by old, highly optimized ones before they had time to improve.
3.2.4 Bloat and its control
The average size of the programs in a GP run usually grows over the generations, much faster than their accuracy improves. The growth comes from inactive code (introns) that protects good programs from destructive variation and from the bias of crossover toward larger offspring; Silva and Costa [51] review the competing theories, Luke and Panait [52] compare the remedies. eqdisco offers four. Hard limits on size and depth (by default 60 nodes and depth 10) are always active. Parsimony pressure adds a penalty to the loss; the coefficient is scale-dependent and hard to tune. Double tournament prefers the smaller of two good programs without a coefficient. Multi-objective selection with NSGA-II keeps the best program of every size and lets size compete with error on equal terms [53, 54].
3.2.5 Constants inside the search
Linear scaling (section 2.2.8) handles the outer offset and scale of every candidate; the constants inside nonlinear functions remain. eqdisco tunes them by the Levenberg–Marquardt method of section 2.2.9, applied after every generation to the best share of the offspring (optimize_fraction, 10% by default) with a small number of iterations, and writes the tuned values back into the genome. The offspring of a tuned individual inherit the acquired constants, which is Lamarckian rather than Darwinian evolution. Kommenda et al. [24] found that this kind of local optimization is one of the most effective improvements of GP for symbolic regression; Operon [23] and PySR [25] use it by default.
3.2.6 Islands
The island model splits the population into sub-populations that evolve separately and exchange their best individuals every migration_interval generations along a ring. Each island can converge to a different structure, and migration combines them; the model also parallelizes naturally. Too frequent migration makes the islands one population, too rare migration makes them independent runs.
3.2.7 The archive and the choice of one model
A run produces many good equations, and the most accurate one is rarely the most useful: on noisy data it overfits, on exact data it is often a large equivalent of a small law. eqdisco keeps an archive of the equations that are non-dominated in (training error, complexity) over the whole run and selects one of them by an explicit rule (model_selection):
- best
-
the lowest training error;
- bic, aic
-
the lowest information criterion (2.3) (the default is BIC); the residual sum of squares is floored at of the total sum of squares, so that equations that fit exact data to machine precision tie, and ties go to the simplest equation;
- knee
-
the point of the front farthest below the straight line between its extremes, with log-error and complexity scaled to ;
- tolerance
-
the simplest equation whose error is at most times the lowest;
- score
-
the rule of PySR [25]: among the equations whose error is at most 1.5 times the lowest, the one with the largest decrease of the log-error per unit of complexity relative to the next simpler equation;
- validation
-
the lowest error on held-out data (validation_fraction).
3.2.8 Library learning
Many laws contain a motif more than once: a product that appears in a numerator and in a denominator, a sum of two exponentials of similar form. Crossover can copy a useful subtree from one individual to another, but only by chance. With library_learning=True, eqdisco mines the frequent subtrees of the best fifth of the population every few generations (section 10.2.5), keeps up to eight blocks that contain a variable and occur in at least 20% of these individuals, and inserts randomly chosen blocks into random positions of a share p_library of new offspring. The idea is related to the automatically defined functions of Koza and to the concept libraries of LaSR [55], which abstract good hypotheses into textual concepts with a language model; here the abstraction is syntactic and needs no model. This mechanism is new in eqdisco.
In a nutshell: Genetic programming
- A population of expressions evolves by selection, crossover and mutation (algorithm 3.1); linear scaling and Lamarckian Levenberg–Marquardt tuning take care of the constants.
- Selection: tournament (pressure by its size), double tournament (mild parsimony), -lexicase (case-wise, diverse), NSGA-II (error and size), AFP (error and age).
- Bloat is controlled by limits, parsimony pressure, double tournament or multi-objective selection; semantic crossover and islands maintain diversity.
- The archive of non-dominated equations is the real result of a run; one model is selected from it by an explicit rule, BIC by default.
- Library learning (new) reinserts frequent building blocks of the best individuals into offspring.
3.3 Using it in eqdisco
SymbolicRegressor(population_size=500, generations=50, functions=..., selection="tournament", ...)
- Search space
-
functions (names of primitives), init_depth=(2, 5), max_depth=10, max_size=60, p_constant, const_range, complexity ("size", "weighted", "recursive").
- Selection
-
selection ("tournament", "double_tournament", "lexicase", "nsga2", "afp"), tournament_size, parsimony, elitism, lexicase_epsilon.
- Variation
-
p_crossover, crossover ("subtree" or "semantic"), p_subtree_mutation, p_point_mutation, p_hoist_mutation, p_constant_mutation, p_shrink_mutation, p_insert_mutation.
- Constants
-
linear_scaling=True, optimize ("none" or "lm"), optimize_fraction, optimize_iterations.
- Structure of the run
-
n_islands, migration_interval, migration_size, patience, time_limit, max_evaluations.
- Model choice
-
model_selection ("bic", "aic", "best", "knee", "tolerance", "score", "validation"), selection_tolerance, validation_fraction, refit.
- Knowledge and guidance
-
constraints, units, constraint_weight (chapter 9); seed_equations, library, library_learning, library_interval, p_library; llm_proposer, llm_interval (chapter 6).
- Related
-
analysis.select_model(front, rule, X, y), viz.plot_pareto, viz.plot_convergence, viz.plot_tree.
3.4 Examples
Five selection schemes. Keijzer-14, , is sampled at 100 training points in and searched five times with each selection scheme, with the four arithmetic operations, a population of 200 and 25 generations:
runs = {} for sel in schemes: runs[sel] = [] for seed in range(5): sr = eq.SymbolicRegressor(population_size=200, generations=25, selection=sel, functions=("add", "sub", "mul", "div"), random_state=seed) sr.fit(prob.X_train, prob.y_train) runs[sel].append(sr)
The result is a lesson about local optima more than about selection (fig. 3.2). In every scheme most runs end at the paraboloid , which explains about 74% of the training variance and has a test of 0.706; the medians of all five schemes are this same equation. Only one of the 25 runs found the exact law, with -lexicase selection; its test error is zero to machine precision and is drawn at the bottom of the right panel. The schemes differ in the size of what they return: plain tournament selection reaches the paraboloid through equations with a median of 31 nodes, double tournament, NSGA-II and AFP return the 11-node paraboloid itself, lexicase a 13-node equation. The parameter study shows the effect of the tournament size on diversity: the share of distinct structures in the last generation is 0.91, 0.95 and 0.86 for tournaments of 2, 4 and 7 and drops to 0.57 for tournaments of 12, where a few structures take over the population. A larger budget or the constant tuning of section 3.2.5 helps more on this problem than the choice of the selection scheme.
Open in ColabExample plot_05_selection_schemes.py in the gallery
Bloat. Nguyen-6, , is searched four times under four policies: the size limit only, parsimony pressure with coefficient 0.001, double tournament, and NSGA-II on error and size:
results = {} for name, kw in policies.items(): results[name] = [eq.SymbolicRegressor(random_state=s, **base, **kw).fit(prob.X_train, prob.y_train) for s in range(4)]
With the size limit only, the mean program size grows to 53.8 nodes after 30 generations, close to the limit of 60 (fig. 3.3). It also gives the lowest training error () and a test error , because the data are noise-free and large programs can approximate the target closely. Parsimony pressure keeps the mean size at 5.8 nodes but raises the test error to ; double tournament gives 16.7 nodes and . NSGA-II keeps the mean size at 15.3 nodes and reaches the lowest test error of all, : it preserves good equations of every size and lets the small ones improve without being crowded out. The parameter study confirms that the parsimony coefficient is a blunt instrument: coefficients 0, , and give mean sizes of 51.8, 13.6, 6.4 and 4.1 nodes, and the test error grows from to .
Open in ColabExample plot_06_bloat_control.py in the gallery
Constants inside the search. The target has a constant inside the exponential. Five runs without and five with Levenberg–Marquardt tuning of the best 10% of the offspring are compared:
runs = {} for opt in ("none", "lm"): runs[opt] = [ eq.SymbolicRegressor(population_size=200, generations=20, optimize=opt, optimize_fraction=0.1, optimize_iterations=10, functions=funcs, random_state=s).fit(X, y) for s in range(5) ] for opt, rr in runs.items(): print(opt, [str(r.equation_) for r in rr[:2]])
With tuning, the median normalized error after 20 generations is ; without, , with practically the same number of fitness evaluations (3 319 against 3 262; the function evaluations inside Levenberg–Marquardt are not counted, and they make a tuned run several times slower in wall-clock time). The left panel of fig. 3.4 shows that one tuned run finds the exact law after about 1 700 evaluations, its error dropping to the level of rounding, and that the other tuned runs stay below the untuned ones throughout. The evolved equations show the other side of tuning: free constants make it easy to build very accurate but convoluted equations, such as a constant of that switches a term off, so tuning should be combined with complexity control and the simplification of chapter 10. Tuning a larger share of the offspring helps further: with 0, 5, 20 and 50% tuned, the median after 15 generations is , , and .
Open in ColabExample plot_07_parameter_optimization.py in the gallery
One front, six rules. Nguyen-7, , is sampled at 100 points with 2% noise. One run produces a front, and six rules choose from it:
sr = eq.SymbolicRegressor(population_size=300, generations=30, functions=("add", "sub", "mul", "div", "log", "sqrt"), random_state=2) sr.fit(prob.X_train, prob.y_train) front = sr.pareto_front_ chosen = {rule: select_model(front, rule, prob.X_train, prob.y_train) for rule in ("best", "bic", "aic", "knee", "tolerance", "score")} for rule, e in chosen.items(): print(f"{rule:9s} size {e.complexity:3d} test R2 {e.score(prob.X_test, prob.y_test):.5f} {e}")
The lowest error, BIC, AIC and the tolerance rule all select the 31-node equation, whose test is 0.99999; the knee and the score rule select a 17-node polynomial-like equation with test (fig. 3.5). On these data the larger equation is better on the test set as well, so the information criteria are right to prefer it; the smaller one is a cubic approximation that a human would find easier to read. The parameter study repeats the run at noise levels 0, 1, 5 and 10%. The most accurate equation has 25, 36, 16 and 24 nodes, without a trend; BIC selects 25, 13, 13 and 5 nodes and the knee 16, 13, 13 and 8, so both become more conservative as the noise grows, which is what a selection rule should do.
Open in ColabExample plot_08_pareto_selection.py in the gallery
Diversity. Vladislavleva-7 is a difficult two-variable problem with trigonometric interactions. Standard subtree crossover, semantic similarity-based crossover and four islands are compared, four runs each:
results = {name: [eq.SymbolicRegressor(population_size=240, generations=25, functions=("add", "sub", "mul", "sin"), random_state=s, **kw).fit(prob.X_train, prob.y_train) for s in range(4)] for name, kw in variants.items()}
The share of distinct structures stays high in all three variants (on average 0.956, 0.909 and 0.917 over the run), so the population does not collapse on this problem. Semantic crossover reduces the median final error slightly, from 0.180 to 0.165, and four islands reduce it to 0.145 (fig. 3.6). The differences are of the size of the run-to-run variation with four runs, and none of the variants solves the problem in 25 generations. The migration interval of the island model has no consistent effect between 2 and 25 generations (median errors 0.151, 0.137, 0.159 and 0.160).
Library learning. The target with repeats one block three times. Six runs without and six with library learning are compared:
runs = {} for lib in (False, True): runs[lib] = [eq.SymbolicRegressor(population_size=250, generations=30, functions=funcs, library_learning=lib, library_interval=3, p_library=0.05, random_state=s).fit(X, y) for s in range(6)] learned = eq.analysis.mine_library([r.ind for r in runs[True][0]._final_population[:50]], max_blocks=5) print("library of run 0:", [str(blk) for blk in learned])
The library of the first run contains the blocks , , , and : products of the right variables, but not the whole block . Even these partial blocks help: the median final error falls from 0.097 without the library to 0.047 with it (fig. 3.7). The injection rate matters less than the presence of the library: rates of 0, 2, 5, 10 and 20% give median errors of 0.051, 0.046, 0.042, 0.042 and 0.030 in three runs each. On problems without repeated motifs the library is harmless but useless; it pays off when the same subexpression is needed in several places.
Open in ColabExample plot_10_library_learning.py in the gallery
3.5 Further reading
Koza [16] and the field guide of Poli, Langdon and McPhee [28] cover the classical operators; Langdon and Poli [56] develop the schema theory of GP; Eiben and Smith [57] place GP among the other evolutionary algorithms. Lexicase selection was introduced by Helmuth, Spector and Matheson [47] and adapted to regression by La Cava, Spector and Danai [48]. Smits and Kotanchek [53] made the Pareto front of error and complexity central to industrial symbolic regression; Kommenda et al. [54] study NSGA-II with complexity measures; Schmidt and Lipson [50] introduced age–fitness Pareto optimization. Silva and Costa [51] and Luke and Panait [52] review bloat. The book of Kronberger et al. [18] gives practical advice on all these choices for symbolic regression.