Scientific Machine Learning:
Symbolic Regression

The two previous notebooks discovered equations by choosing among candidates. Sparse Regression for Equation Discovery picked the terms of an algebraic law out of a library, and Sparse Identification of Nonlinear Dynamics did the same for the right-hand side of a differential equation. Both found only what the library contained. A law whose form nobody thought to offer, $\sin(x^2)$ rather than $\sin x$ and $x^2$, a ratio of sums, a constant inside a function, is invisible to them, and the remedy of making the library larger runs into the collinearity that the first notebook warned about.


Symbolic regression removes the library. It searches the space of mathematical expressions directly, assembling formulas from operators, variables and constants, and judges each candidate by how well it fits the data and how short it is. The search is combinatorial and the standard engine for it is genetic programming, which evolves a population of expressions by selection, crossover and mutation. That engine is a genetic algorithm with trees in place of strings, and a genetic algorithm is something no earlier notebook has needed, since every method so far followed a gradient. This notebook therefore builds the genetic algorithm first, from local search and its failure on landscapes with many hills to the population, the operators and the evolutionary loop, on bit strings where every step can be watched; then it puts expression trees in the place of the strings and builds genetic programming from scratch, so that nothing in it is a black box; then it uses the libraries gplearn and PySR for problems of realistic size, and shows what makes the search tractable: dimensional analysis before the search, and a clear statement of what counts as simple. It closes by comparing the three discovery methods of this course.


One convention is set here once. The genetic algorithm comes from a literature that speaks of fitness, a quantity to be made as large as possible, and Chapters 2 and 3 follow it: every problem there is written as a maximization, $\max f(x)$, and a better solution is one with a larger $f$. A minimization is the same problem with the sign of the objective changed, $\min g(x)$ is $\max -g(x)$, and from Chapter 5 on, where the quantity to be made small is an error, the selection rule used there compares candidates instead of adding their fitness, so the error is used as it stands.


Learning Objectives

After studying this notebook, you should be able to

  • explain why a library-based method cannot find a law whose functional form is absent from the library, and what symbolic regression searches instead;
  • define a local optimum with respect to a neighborhood, write the local search algorithm, and explain why it stops on the first hill it climbs and how simulated annealing escapes;
  • describe a genetic algorithm in terms of a population, a fitness function and the three operators selection, crossover and mutation, write each operator for bit strings in a few lines, and encode an integer, a real or a categorical variable as a binary string;
  • represent a mathematical expression as a tree of nodes, evaluate it, print it, measure its size, and generate random expressions;
  • implement genetic programming for symbolic regression as the same evolutionary loop with subtree crossover, subtree mutation, tournament selection, scored by error with linear scaling and a parsimony penalty;
  • use gplearn and PySR for symbolic regression on several variables, and read a hall of fame;
  • reduce a problem by dimensional analysis before searching, and explain from an example why this decides whether the search succeeds; and
  • choose between sparse regression, SINDy and symbolic regression for a given discovery problem.

Setup

NumPy and Matplotlib. The genetic algorithm and the genetic programming of Chapters 2 to 5 use nothing else; gplearn is imported in Chapter 6.

In [150]:
import numpy as np
import matplotlib.pyplot as plt

Sparse regression

The sequential thresholded least squares of the previous notebooks, for the comparisons.

In [151]:
def stls(Theta, y, threshold, n_iter = 10):
    xi = np.linalg.lstsq(Theta, y, rcond = None)[0]
    for it in range(n_iter):
        small = np.abs(xi) < threshold
        xi[small] = 0
        big = ~small
        if np.sum(big) == 0:
            break
        xi[big] = np.linalg.lstsq(Theta[:, big], y, rcond = None)[0]
    return xi




1. Why a Library Is a Limitation

1.1. A Law the Library Does Not Contain

The data below follow $y = \sin(x^2)$ on $[0, 3]$, with $2\%$ noise. The function is as simple as any in the earlier notebooks, a sine of a square, but it is not a sum of simple terms: its oscillations get faster as $x$ grows, and no finite combination of the usual candidates, powers of $x$, $\sin x$, $\cos x$, $\sin 2x$, reproduces that.

In [152]:
np.random.seed(0)
x = np.sort(np.random.uniform(0, 3, 200))
y = np.sin(x**2) + 0.02*np.random.randn(200)

x_fine = np.linspace(0, 4, 400)

plt.figure(figsize = (6, 4))
plt.plot(x_fine, np.sin(x_fine**2), 'k', linewidth = 3, alpha = 0.3, label = 'True law')
plt.plot(x, y, 'b.', markersize = 3, label = 'Data')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([0, 4])
plt.ylim([-1.5, 1.5])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

Sparse regression is given the library of powers of $x$ up to the seventh, and the threshold is swept.

In [153]:
def library(x):
    cols = [np.ones_like(x)]
    names = ['1']
    for p in range(1, 8):
        cols.append(x**p)
        names.append('x^%d' % p)
    return np.column_stack(cols), names

Theta, names = library(x)
col_scale = np.sqrt(np.mean(Theta**2, axis = 0))

for threshold in [0.05, 2.0, 5.0]:
    xi = stls(Theta/col_scale, y, threshold)/col_scale
    kept = [names[k] for k in range(len(names)) if abs(xi[k]) > 1e-10]
    err_in = np.sqrt(np.mean((Theta @ xi - y)**2))
    Theta_out, _ = library(x_fine[x_fine > 3])
    err_out = np.sqrt(np.mean((Theta_out @ xi - np.sin(x_fine[x_fine > 3]**2))**2))
    print('threshold %.2f : %2d terms | error on data %.4f | error on [3, 4] %.3f | %s' % (threshold, len(kept), err_in, err_out, ', '.join(kept)))
threshold 0.05 :  8 terms | error on data 0.0649 | error on [3, 4] 96.415 | 1, x^1, x^2, x^3, x^4, x^5, x^6, x^7
threshold 2.00 :  6 terms | error on data 0.0678 | error on [3, 4] 106.463 | x^2, x^3, x^4, x^5, x^6, x^7
threshold 5.00 :  4 terms | error on data 0.0793 | error on [3, 4] 116.669 | x^4, x^5, x^6, x^7

There is no good answer in this library. At threshold $0.05$ all eight powers survive and the error on the data is $0.065$, three times the noise; at $5$ four powers survive with error $0.079$. The Pareto curve of the first notebook has no elbow, because every term dropped costs accuracy and no number of terms reaches the noise floor. Beyond the data, on $[3, 4]$, the errors are in the hundreds. The eight-term fit is drawn below.

In [154]:
xi = stls(Theta/col_scale, y, 0.05)/col_scale
Theta_fine, _ = library(x_fine)

plt.figure(figsize = (6, 4))
plt.plot(x_fine, np.sin(x_fine**2), 'k', linewidth = 3, alpha = 0.3, label = 'True law')
plt.plot(x, y, 'b.', markersize = 3, label = 'Data')
plt.plot(x_fine, Theta_fine @ xi, 'r--', linewidth = 1.5, label = 'Sparse regression, polynomial library')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([0, 4])
plt.ylim([-1.5, 1.5])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

The polynomial follows the data through the first two oscillations, misses the third, and leaves the plotting window just past $x = 3$. It is doing what a polynomial does with an oscillation: imitating it with a growing number of terms and failing as soon as it has to continue the pattern. A richer library would help here only if it happened to contain $\sin(x^2)$, and a library that contained every function somebody might need would be too collinear to use. The limitation is the library itself.


1.2. Searching Expressions Instead of Coefficients

Sparse regression fixes the functions and searches over the coefficients, a continuous problem with a convex relaxation and a fast algorithm. Symbolic regression searches over the functions, which is a discrete, combinatorial problem: the set of expressions that can be built from a handful of operators and a variable is infinite, and there is no gradient to follow from one expression to a better one. What makes the problem approachable is that expressions have structure. An expression is a tree, a tree can be grown, cut and grafted, and small changes to a tree make small changes to the function it computes often enough for a search by trial and improvement to work. That search is genetic programming. It is a genetic algorithm, a search by a population of candidates that are selected, recombined and perturbed, and the next two chapters build the genetic algorithm on the simplest kind of candidate, a string of bits, before Chapters 4 and 5 put trees in its place.


The price of giving up the library is paid in three currencies. The search is slower, minutes where sparse regression took milliseconds. It is stochastic, so two runs can return two different expressions. And the result is harder to validate, since an evolved expression can fit the data with a form that has no physical reading. The notebook will meet each of these.




2. Optimization Without Gradients

The problem is the one of Optimization, written as a maximization,


$$ \max_{x \in F} \; f(x) , $$


with a feasible set $F$ that may be discrete, and with no gradient available. A point $x^*$ is a global optimum if $f(x^*) \ge f(x)$ for every $x \in F$. A point $\tilde{x}$ is a local optimum with respect to a neighborhood $N(\tilde{x}) \subseteq F$ if $f(\tilde{x}) \ge f(x)$ for every $x \in N(\tilde{x})$. The neighborhood is part of the definition: a point can be a local optimum for a small neighborhood and not for a larger one, and if the neighborhood is all of $F$ the two notions coincide.


Local search is the simplest way to use a neighborhood. Start at some $x_0$; look in $N(x)$ for a better point; if there is one, move to it; if there is none, stop. The point it stops at is, by construction, a local optimum for the neighborhood that was searched. For a maximization the picture is a climber on a landscape, and the method is also called hill climbing.


$$ \begin{aligned} &x \leftarrow x_0 \\ &\text{repeat: if there is } y \in N(x) \text{ with } f(y) > f(x), \text{ set } x \leftarrow y; \text{ otherwise stop} \\ &\text{return } x \end{aligned} $$


The example is a polynomial with two hills on a grid of seven points,


$$ \max\; f(x) = -4x^4 + 8x^2 + x + 5 , \qquad x \in F = \{-1.5, -1, -0.5, 0, 0.5, 1, 1.5\} , $$


with the neighborhood $N(x) = \{x - 0.5,\; x + 0.5\} \cap F$, the two grid points on either side. The global optimum is $x^* = 1$ with $f(x^*) = 10$; the other hill has its top at $x = -1$ with $f(-1) = 8$.

In [155]:
def f(x):
    return -4*x**4 + 8*x**2 + x + 5

F = np.arange(-1.5, 1.6, 0.5)                               # the feasible set: seven grid points

def neighbors(x):                                           # the two grid points on either side
    return [y for y in [x - 0.5, x + 0.5] if -1.5 <= y <= 1.5]

def local_search(f, x0, neighbors):
    x = x0
    path = [x]
    while True:
        better = [y for y in neighbors(x) if f(y) > f(x)]   # every better point in the neighborhood
        if len(better) == 0:                                # none: x is a local optimum
            return x, path
        x = max(better, key = f)                            # move to the best of them
        path.append(x)
In [156]:
xp = np.linspace(-1.6, 1.6, 300)

plt.figure(figsize = (6, 6))
for k, x0 in enumerate([-1.5, 0.5]):
    x_end, path = local_search(f, x0, neighbors)
    plt.subplot(2, 1, k + 1)
    plt.plot(xp, f(xp), 'k', alpha = 0.3, linewidth = 4)
    plt.plot(F, f(F), 'ko', label = 'feasible set')
    plt.plot(path, f(np.array(path)), 'r.-', markersize = 12, label = 'local search')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.title('start %.1f, stop %.1f, f = %.1f' % (x0, x_end, f(x_end)))
    plt.legend()
    plt.grid(True)
plt.tight_layout()
plt.show()
No description has been provided for this image

Started at $x_0 = -1.5$, the search steps to $-1$, finds both neighbours worse, and stops: a local optimum with $f = 8$, short of the global maximum of $10$, and the search has no way of knowing that a higher hill exists half a unit to the right. Started at $0.5$, it climbs the right hill and stops at the global optimum. Local search reaches the top of whichever hill it starts on, and which hill that is depends on $x_0$, which cannot generally be chosen with knowledge of the landscape.


Three remarks make the picture general. First, the neighborhood "moves" with $x$, and at termination $N(x)$ is the neighborhood of the answer. Second, how the better point is chosen is open: taking any better point is a random (greedy) search, taking the best point in $N(x)$ is steepest ascent, and the gradient methods of Optimization are steepest ascent (or descent) with an infinitesimal neighborhood, which is why they too stop at local optima. Third, the one general remedy within local search is multistart: run from many random $x_0$ and keep the best, which works when there are few hills and wastes most of its runs when there are many.


2.2. Heuristics

A heuristic is a method that does not guarantee the best solution but finds a good one in reasonable time. It gives up completeness, the promise that the global optimum will be found, and gains the ability to attack problems that cannot be solved any other way: large, nonlinear, non-convex, with discrete variables, with many local optima. Where a gradient method in a convex landscape returns the mathematician's answer, the optimum with a proof, a heuristic returns the engineer's answer, a solution that is good enough and was found before the deadline.


The heuristics of this notebook are stochastic: they use random numbers, and two runs with the same input can return different outputs. The randomness is not a weakness to be apologized for; it is the mechanism by which the search leaves a hill. A deterministic local search at a local optimum stays there forever, because every move it is allowed to make goes down. A stochastic search can make a downhill move with some probability, and once it has, it may find itself on the slope of a higher hill. The two classical ways of organizing such moves are simulated annealing, which moves one point and lets it go downhill with a probability that decays over time, and the genetic algorithm, which moves a whole population and lets the good points breed. The rest of this notebook is about the second, with a short look at the first for contrast.


2.3. Simulated Annealing

Annealing is a process in metallurgy. A metal that is cooled quickly freezes with its atoms in whatever disordered arrangement they happened to be in, a defective solid with high internal energy. Heated and then cooled slowly, the same metal ends in an ordered crystal with low energy, because at high temperature the atoms have enough thermal energy to leave a poor arrangement, and as the temperature falls they settle, step by step, into a better one. The temperature controls how willing the atoms are to move to a state of higher energy: at a high temperature almost any move is possible, at a low one only moves that lower the energy.


Simulated annealing turns this into a search. The negative of the objective, $-f$, plays the role of the energy, so that a high $f$ is a low-energy state; a random neighbor $y \in N(x)$ is a proposed move; and a temperature $t$ that falls over the run sets the willingness to accept a move that makes $f$ worse,


$$ \text{Prob}(x \leftarrow y) = \begin{cases} 1 & \text{if } \Delta f > 0 \quad (\text{uphill}) \\[4pt] \exp\!\left(\dfrac{\Delta f}{t}\right) & \text{if } \Delta f \le 0 \quad (\text{downhill}) \end{cases} \qquad \Delta f = f(y) - f(x) . $$


This is local search with one change. An uphill move is always taken, as before; a downhill move is taken with a probability that is smaller the larger the drop and the lower the temperature. At a high temperature almost every move is accepted and the point wanders over the whole landscape; as $t$ falls, downhill moves of a given size become rarer, and at $t = 0$ the algorithm is plain hill climbing. The cooling schedule $t \leftarrow \alpha t$ with $0 < \alpha < 1$ after every step is the usual choice. On the two-hill problem, started on the wrong hill, the downhill moves are what let the point cross the valley at $x = 0$.

In [157]:
def simulated_annealing(f, x0, neighbors, t0 = 5.0, alpha = 0.95, n_steps = 60):
    x = x0
    t = t0
    path = [x]
    for step in range(n_steps):
        candidates = neighbors(x)
        y = candidates[np.random.randint(len(candidates))]       # a random neighbor
        df = f(y) - f(x)
        if df > 0 or np.random.rand() < np.exp(df/t):            # uphill always, downhill sometimes
            x = y
        path.append(x)
        t = alpha*t                                               # cooling
    return x, path
In [158]:
np.random.seed(2)
x_end, path = simulated_annealing(f, -1.5, neighbors)

plt.figure(figsize = (6, 6))
plt.subplot(2, 1, 1)
plt.plot(xp, f(xp), 'k', alpha = 0.3, linewidth = 4)
plt.plot(F, f(F), 'ko')
plt.plot(path, f(np.array(path)), 'r.-', alpha = 0.5, markersize = 8)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('simulated annealing from -1.5: stop %.1f' % x_end)
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(path, 'r.-', markersize = 6)
plt.xlabel('step')
plt.ylabel('x')
plt.title('the point over the run')
plt.grid(True)
plt.tight_layout()
plt.show()
No description has been provided for this image

The upper panel shows where the point went and the lower panel shows when. In the early steps, while the temperature is high, the point steps down from the left hill, crosses the valley at $x = 0$ and climbs the right one, with a downhill step or two on the way; as the temperature falls it stops accepting such steps, and the last steps sit at the global optimum. Nothing guarantees this: with another seed the point can freeze on the hill it started on, and a cooling that is too fast makes that likely, while a slower cooling makes the crossing more likely at the price of more steps. Simulated annealing is a heuristic. It is also a single point, and a single point carries no memory of where else the landscape was good. The genetic algorithm keeps many points at once, and that is its advantage.




3. The Genetic Algorithm

A genetic algorithm is an optimization method patterned after natural selection and genetics: the way living organisms survive, reproduce and adapt to their environment. Nature keeps many individuals alive at once, lets the fit ones reproduce, and makes the offspring by combining the parents' genes with an occasional random change. Over generations the population adapts to its environment. The genetic algorithm does the same with candidate solutions and an objective function, and the vocabulary is borrowed wholesale. The environment is the objective landscape $f$. An individual is one candidate solution $x$, and a population is a set $P$ of candidate solutions kept together. A chromosome is the encoded solution $s$, a string of symbols, and a gene is one symbol of the string, a bit $a_i$. Fitness is a non-negative score, larger for a better solution, here $f(x)$ itself. Natural selection is the selection operator, by which the fit reproduce more; reproduction is crossover, two parents giving two children that mix their strings; and mutation is a small random change to a child's string.


A genetic algorithm keeps a population of candidate solutions, and improves it by imitating natural selection. Each candidate is an individual, written as a string of symbols called a chromosome, and each has a fitness, a non-negative number that is larger for better candidates. A new generation is made from the old one in three steps.

  • Selection picks parents, with a probability that grows with fitness, so that the fit reproduce more.

  • Crossover combines two parents into two children that each inherit part of either parent.

  • Mutation makes a small random change to a child.

The children replace the old population, and the cycle repeats until the population has converged or a budget of generations is spent.


$$ \begin{aligned} &P \leftarrow \text{random population of } |P| \text{ chromosomes}; \quad \text{evaluate the fitness of each} \\ &\text{repeat until done:} \\ &\qquad Q \leftarrow \emptyset \\ &\qquad \text{while } |Q| < |P|: \\ &\qquad\qquad s_1 \leftarrow \text{select}(P), \quad s_2 \leftarrow \text{select}(P) \\ &\qquad\qquad (s_1, s_2) \leftarrow \text{crossover}(s_1, s_2) \\ &\qquad\qquad s_1 \leftarrow \text{mutate}(s_1), \quad s_2 \leftarrow \text{mutate}(s_2) \\ &\qquad\qquad \text{evaluate their fitness; add both to } Q \\ &\qquad P \leftarrow Q \\ &\text{return the fittest member of } P \end{aligned} $$


Two things distinguish this from the searches of Chapter 2, and both come from the population. Local search and simulated annealing are single-point searches: one point, one neighborhood, one hill at a time, and on a landscape with many hills the point is captured by the nearest one. The genetic algorithm is a parallel search: its population is spread over the landscape, and the operators act between its members.

  • Information sharing. There is no neighborhood. A child is not a small step from one parent but a recombination of two, so when two fit parents sit in different promising regions, a child can land in a region that neither parent occupied, and sometimes in a better one.

  • Memory and diversity. The population is a collective memory of where the landscape has been found good: as long as some members sit on the right hill, selection multiplies them. Mutation keeps injecting new traits, so the population does not collapse onto one point before the search is done.


3.2. Encoding and Decoding

The operators act on strings, so the first decision is how a solution $x$ becomes a string $s$ and back. The map from strings to solutions is the decoding $\pi: s \mapsto x$, and the classical choice is a binary string, $s = a_1 a_2 \cdots a_l$ with $a_i \in \{0, 1\}$. Three kinds of variable have to be encoded, an integer, a real number and a choice among categories, and each has its own rule.


Integer variables. An integer $x \in \{x_L, \ldots, x_H\}$ is encoded by writing $x - x_L$ in binary. The string is decoded by reading it as a binary integer and adding $x_L$,


$$ x = x_L + \sum_{i=1}^{l} a_i\, 2^{\,l - i} , \qquad l = \lceil \log_2 (x_H - x_L + 1) \rceil , $$


where $l$ is the smallest number of bits that covers the range: the eight integers from $2$ to $9$ need $\lceil \log_2 8 \rceil = 3$ bits, and $000$ is $2$, $111$ is $9$. The decoding is the usual base-two reading, which the code does by walking along the string and doubling, and the encoding is the reverse, repeated division by two.

In [159]:
def decode_integer(s, x_low):                                                # binary string -> integer from x_low
    integer = 0
    for a in s:
        integer = 2*integer + a                                              # read the string left to right
    return x_low + integer

def encode_integer(x, x_low, l):                                             # integer -> binary string of length l
    integer = x - x_low
    s = np.zeros(l, dtype = int)
    for i in range(l - 1, -1, -1):
        s[i] = integer % 2                                                   # the last bit is the remainder
        integer = integer//2
    return s

l = int(np.ceil(np.log2(9 - 2 + 1)))                                         # integers 2 to 9: eight values, three bits
for x_int in [2, 5, 9]:
    s = encode_integer(x_int, 2, l)
    print('integer %d  ->  %s  ->  %d' % (x_int, ''.join(map(str, s)), decode_integer(s, 2)))
integer 2  ->  000  ->  2
integer 5  ->  011  ->  5
integer 9  ->  111  ->  9

Real variables. A real variable $x \in [x_L, x_H]$ cannot be written in binary exactly, so the interval is divided into $2^l - 1$ equal steps and the string names a step: it is read as a binary integer and scaled into the interval,


$$ x = x_L + \frac{x_H - x_L}{2^l - 1}\sum_{i=1}^{l} a_i\, 2^{\,l - i} , $$


so that $00\cdots0$ is $x_L$, $11\cdots1$ is $x_H$, and the resolution is $(x_H - x_L)/(2^l - 1)$: eight bits divide the interval into $255$ steps, sixteen bits into $65535$. The integer rule is the special case with the scale factor set to one. To encode a real number, the nearest step is taken.

In [160]:
def decode(s, x_low, x_high):                              # binary string -> real number in [x_low, x_high]
    l = len(s)
    integer = decode_integer(s, 0)
    return x_low + (x_high - x_low)*integer/(2**l - 1)

def encode(x, x_low, x_high, l):                           # real number -> binary string of length l (nearest step)
    integer = int(round((x - x_low)/(x_high - x_low)*(2**l - 1)))
    return encode_integer(integer, 0, l)

for s in [np.zeros(8, dtype = int), np.ones(8, dtype = int), np.array([1, 0, 1, 0, 0, 0, 1, 1])]:
    print(''.join(map(str, s)), '->  %.4f' % decode(s, -1.5, 1.5))

print('resolution with 8 bits : %.5f' % (3/(2**8 - 1)))
print('1.0 encoded in 8 bits  :', ''.join(map(str, encode(1.0, -1.5, 1.5, 8))), ' ->  %.4f' % decode(encode(1.0, -1.5, 1.5, 8), -1.5, 1.5))
00000000 ->  -1.5000
11111111 ->  1.5000
10100011 ->  0.4176
resolution with 8 bits : 0.01176
1.0 encoded in 8 bits  : 11010100  ->  0.9941

The string $10100011$ is the integer $163$, and $163/255$ of the way from $-1.5$ to $1.5$ is $0.4176$. The encoding of $1.0$ is not exact, because $1.0$ does not lie on the grid of $255$ steps; the nearest code decodes to $0.9941$, a discrepancy of half a step. This is the price of a binary encoding and it is paid once, at the resolution the designer chooses.


Categorical variables. A choice among $N$ options with no order between them, such as the activation function of a network from ['relu', 'sigmoid', 'tanh', 'gelu'], is encoded by numbering the options $0, \ldots, N - 1$ and encoding the number as an integer in $\lceil \log_2 N \rceil$ bits. When $2^l$ exceeds the number of options there are spare codes, and the simplest rule is to clip a decoded index that is too large to the last option. The feasible set of Section 2.1 is such a case: its seven points are the integers $0$ to $6$ in three bits, with one spare code.

In [161]:
def decode_category(s, categories):                                          # binary string -> one of the categories
    index = min(decode_integer(s, 0), len(categories) - 1)                   # a spare code is clipped to the last one
    return categories[index]

def encode_category(category, categories, l):
    return encode_integer(categories.index(category), 0, l)

categories = ['relu', 'sigmoid', 'tanh', 'gelu']
l = int(np.ceil(np.log2(len(categories))))                                   # four options, two bits
for category in categories:
    s = encode_category(category, categories, l)
    print('%-8s  ->  %s  ->  %s' % (category, ''.join(map(str, s)), decode_category(s, categories)))
relu      ->  00  ->  relu
sigmoid   ->  01  ->  sigmoid
tanh      ->  10  ->  tanh
gelu      ->  11  ->  gelu

Several variables in one chromosome. A problem with more than one decision variable encodes each variable as its own block of bits and concatenates the blocks into one string, $s = s_1 s_2 \cdots s_n$. To evaluate the fitness, the string is cut back into its blocks and each block is decoded by its own rule. The structure is a hierarchy with three levels. A gene is one bit, the smallest unit; a change in one gene is the smallest possible mutation. A block is a group of genes that decodes to one variable: three bits for an integer, two for a category, eight for a real number. The chromosome is the whole string, the complete candidate solution; for a single-variable problem it is one block, and for a multi-variable problem it is the blocks stitched together. The genetic operators of Section 3.4 act on the whole chromosome without knowing where the blocks are, and the fitness function sees only the decoded variables. The example below packs an integer in $[2, 9]$, a choice of activation, and a real number in $[-1.5, 1.5]$ into thirteen bits.

In [162]:
def encode_all(x_int, category, x_real):                                      # three variables -> one chromosome
    return np.concatenate([encode_integer(x_int, 2, 3),
                           encode_category(category, categories, 2),
                           encode(x_real, -1.5, 1.5, 8)])

def decode_all(s):                                                           # cut the chromosome back into its blocks
    return decode_integer(s[0:3], 2), decode_category(s[3:5], categories), decode(s[5:13], -1.5, 1.5)

s = encode_all(6, 'tanh', 0.5)
print('chromosome :', ''.join(map(str, s)), ' (3 + 2 + 8 = %d bits)' % len(s))
print('decoded    : %d, %s, %.4f' % decode_all(s))
chromosome : 1001010101010  (3 + 2 + 8 = 13 bits)
decoded    : 6, tanh, 0.5000

All three come back exactly, the real one because $0.5$ happens to lie on the eight-bit grid, at code $170$ of $255$; a value off the grid, such as the $1.0$ above, would come back with the half-step discrepancy. From here on every example uses one chromosome and one decoding function, and the loop of Section 3.5 never looks inside the string.


3.3. Fitness and Selection

The genetic algorithm maximizes a non-negative fitness $f(\pi(s))$: the objective, evaluated at the decoded string. When the objective is non-negative, as in every example of this notebook, the fitness is the objective itself; an objective that can be negative is shifted up by a constant large enough to keep it non-negative. The fitness is the only place the problem enters the algorithm: selection sees fitness values and nothing else, and crossover and mutation see strings and nothing else.

Remark (why non-negative). The requirement comes from the selection rule introduced next, which draws individuals with probability proportional to fitness and therefore needs fitness values that are non-negative and not all zero. The tournament selection of Chapter 5 compares fitness values instead of adding them, and with it any objective can be used as it stands.


Fitness-proportionate selection picks an individual with probability proportional to its fitness,


$$ \text{Prob}(s \text{ is selected}) = \frac{\text{fit}[s]}{\sum_{t \in P} \text{fit}[t]} , $$


which is the roulette wheel: each individual owns a sector of the wheel whose angle is its share of the total fitness, the wheel is spun, and the sector under the pointer is chosen. The implementation draws $r$ uniformly in $(0, 1]$ and walks through the population adding up fitness until the running sum exceeds $r$ times the total, which costs one pass over the population per draw. A fit individual is chosen often but not always, and an unfit one is chosen rarely but not never; that is what keeps the population from collapsing onto the current best.

In [163]:
def select(population, fitness):                           # roulette wheel: probability proportional to fitness
    r = np.random.rand()*np.sum(fitness)                   # a random point on the wheel
    partial = 0
    for i in range(len(population)):
        partial = partial + fitness[i]                      # the running sum of the sectors
        if r <= partial:
            return population[i]
    return population[-1]

np.random.seed(0)
fitness = np.array([1.0, 2.0, 3.0, 4.0])                   # four individuals, fitness 1 to 4
population = [0, 1, 2, 3]                                  # four individuals, labelled 0 to 3

draws = [select(population, fitness) for k in range(10000)]
print('share of the draws :', np.round(np.bincount(draws)/10000, 3))
print('fitness share      :', np.round(fitness/fitness.sum(), 3))
share of the draws : [0.102 0.203 0.3   0.394]
fitness share      : [0.1 0.2 0.3 0.4]

Ten thousand spins of the wheel give each individual its share of the total fitness, $0.1$, $0.2$, $0.3$ and $0.4$, to two decimals. The fittest individual is chosen four times as often as the least fit, not always, and the least fit is still chosen a tenth of the time. The strength of this preference is set by the fitness values themselves: if a large constant is added to every fitness, every individual becomes nearly equally fit and selection nearly random, and if the fitness is scaled so that the best is many times the worst, selection is sharp. The shift that makes a fitness non-negative is therefore a tuning parameter of the search as well as a convention, and the tournament selection of Chapter 5 does not have it.


3.4. Crossover and Mutation

Crossover makes two children from two parents. With probability $p_{\text{cross}}$, a site $q \in \{1, \ldots, l - 1\}$ is chosen at random, and the strings are cut there and the pieces swapped: the first child takes the first $q$ symbols of the first parent and the rest from the second, the second child the reverse. With probability $1 - p_{\text{cross}}$ the parents are copied unchanged. On four-bit strings with the cut after the first symbol,


$$ \begin{cases} s_1 = 0\,|\,000 \\ s_2 = 1\,|\,111 \end{cases} \quad\Longrightarrow\quad \begin{cases} t_1 = 0\,111 \\ t_2 = 1\,000 . \end{cases} $$


This is one-point crossover. The same operation can be written with a mask $m$, a binary string with ones up to the cut, as $t_1 = (s_1 \wedge m) \vee (s_2 \wedge \neg m)$ and $t_2 = (s_1 \wedge \neg m) \vee (s_2 \wedge m)$, and a mask with ones in arbitrary positions gives multi-point or uniform crossover for free. Crossover is where the population's memory is used: a child inherits whole blocks of symbols from each parent, so a block that has proved useful in one parent can be combined with a block that has proved useful in another.


Mutation changes each symbol of a string independently with a small probability $p_{\text{mutate}}$, flipping a $0$ to a $1$ or back,


$$ s = 0000 \quad\Longrightarrow\quad t = 0010 , $$


where the third bit flipped. Its role is different from crossover's. Crossover rearranges what the population already contains; mutation introduces what it does not, a bit value that every member may have lost. Without it, a population in which every individual has a $0$ in some position can never produce a $1$ there, however much that $1$ would help, and the search is confined to the subspace the initial population happened to span. The mutation rate is kept low, about one flip per string, because a high rate turns the search into a random walk.

In [164]:
def crossover(s1, s2, p_cross = 0.8):                      # one-point crossover with probability p_cross
    if np.random.rand() < p_cross:
        q = np.random.randint(1, len(s1))                   # the cut, between 1 and l - 1
        return np.concatenate([s1[:q], s2[q:]]), np.concatenate([s2[:q], s1[q:]])
    return s1.copy(), s2.copy()

def mutate(s, p_mutate):                                   # flip each bit independently with probability p_mutate
    flip = np.random.rand(len(s)) < p_mutate
    return np.where(flip, 1 - s, s)

np.random.seed(1)
s1 = np.zeros(8, dtype = int)
s2 = np.ones(8, dtype = int)
t1, t2 = crossover(s1, s2)
print('parents  :', ''.join(map(str, s1)), ''.join(map(str, s2)))
print('children :', ''.join(map(str, t1)), ''.join(map(str, t2)))
print('mutated  :', ''.join(map(str, mutate(s1, 0.2))), '(from the first parent, p = 0.2)')
parents  : 00000000 11111111
children : 00000111 11111000
mutated  : 01000000 (from the first parent, p = 0.2)

The children carry a prefix of one parent and a suffix of the other, cut at the same place, and the mutated string has flipped a bit or two of the all-zero parent. In the binary encoding of a real number the leading bits are the large steps and the trailing bits the fine ones, so a crossover cut near the front swaps the coarse position of the two parents while a cut near the back swaps their fine adjustment, and a mutation in a trailing bit is a small move. The encoding decides what the operators mean.


3.5. The Evolutionary Loop

The four pieces are assembled into the loop of Section 3.1. The function takes the fitness as a function of the decoded variable, the decoding and the string length, and returns the best individual of the final generation together with the best fitness of every generation and the decoded population of every generation, for plotting. Each generation is made in the same way: pairs of parents are drawn from the roulette wheel, crossed, and the two children are mutated, until the new generation is as large as the old one, which then is discarded.


The first run is on the two-hill problem of Section 2.1, now on the whole interval $[-1.5, 1.5]$ rather than seven grid points, with eight-bit strings and a population of forty. The objective $f$ is positive everywhere on the interval, its smallest value being $1.25$ at the ends, so it serves as the fitness without any change. The mutation rate is set to $0.02$ rather than one flip per string: in a string of only eight bits a flip in a leading bit sends a child to the other side of the interval, and one such flip per child would keep scattering the population as fast as selection gathers it.

In [165]:
def genetic_algorithm(fitness_of_x, decode_x, l, n_pop = 40, n_gen = 30, p_cross = 0.8, p_mutate = 0.02):
    population = [np.random.randint(0, 2, l) for k in range(n_pop)]       # random initial strings
    fitness = np.array([fitness_of_x(decode_x(s)) for s in population])   # evaluate them
    history = [fitness.max()]                                              # best fitness of every generation
    generations = [[decode_x(s) for s in population]]                      # the decoded population of every generation

    for gen in range(n_gen):
        children = []
        for k in range(n_pop//2):                                          # n_pop/2 pairs of parents give n_pop children
            s1 = select(population, fitness)
            s2 = select(population, fitness)
            t1, t2 = crossover(s1, s2, p_cross)
            children.append(mutate(t1, p_mutate))
            children.append(mutate(t2, p_mutate))
        population = children                                              # the children replace the parents
        fitness = np.array([fitness_of_x(decode_x(s)) for s in population])
        history.append(fitness.max())
        generations.append([decode_x(s) for s in population])

    best = population[np.argmax(fitness)]                                  # the best of the final generation
    return best, history, generations

np.random.seed(0)
def decode_1d(s):
    return decode(s, -1.5, 1.5)

best, history, generations = genetic_algorithm(f, decode_1d, l = 8)
print('best string : %s  ->  x = %.4f,  f(x) = %.4f' % (''.join(map(str, best)), decode_1d(best), f(decode_1d(best))))
best string : 11010111  ->  x = 1.0294,  f(x) = 10.0152
In [166]:
plt.figure(figsize = (9, 6))
for k, gen in enumerate([0, 5, 15, 30]):
    plt.subplot(2, 2, k + 1)
    plt.plot(xp, f(xp), 'k', alpha = 0.3, linewidth = 4)
    plt.plot(generations[gen], f(np.array(generations[gen])), 'ro', alpha = 0.5)
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.title('generation %d' % gen)
    plt.grid(True)
plt.tight_layout()
plt.show()

plt.figure(figsize = (6, 3))
plt.plot(history, 'k.-')
plt.xlabel('generation')
plt.ylabel('best f')
plt.grid(True)
plt.show()
No description has been provided for this image
No description has been provided for this image

The initial population is scattered over the whole interval, both hills included. By the fifth generation most of it has climbed the right hill and only a few members are left on the left one; by the fifteenth the left hill has been abandoned and nearly the whole population sits on the top of the right one; by the thirtieth it is a tight cluster there, with a few individuals elsewhere that mutation keeps producing. This is selection at work, generation after generation: the members on the higher hill were fitter, reproduced more, and their children took over, until the population as a whole had moved to where $f$ is largest. The best member sits at the top of the right hill, which on the continuous interval lies just to the right of $x = 1$ with $f$ slightly above $10$, to the resolution of the encoding, $0.012$ with eight bits.


The best fitness reaches the maximum of the eight-bit grid by the fourth generation, and the history also shows something the population plots do not: it is not monotone. In a few generations the best fitness drops and recovers, because the best individual has no special protection. It is selected often, but a selected parent is crossed and mutated, and the child need not be as good; when every copy of the best string has been altered in one generation, the best is lost until crossover or mutation produces it again, which in a population this concentrated takes a generation or two. Practical implementations guard against this by keeping a record of the best individual found so far outside the population, which is what the hall of fame of Section 6.3 does, and some copy the best directly into the next generation. Neither is needed here, and the loop is left in its simplest form.


The genetic algorithm did, without being told where to start, what local search could do only from a lucky $x_0$. It did so by keeping forty points instead of one, by letting the fit ones reproduce, and by making children that combine their parents. On a one-dimensional problem with two hills that is more machinery than needed; the space of mathematical expressions, where the rest of this notebook takes the same loop, is one where it is not.




4. Expressions as Trees

Symbolic regression is regression in which the unknown is the formula. Ordinary regression is given data $(x_i, y_i)$ and a form, $y = ax + b$ or $y = \theta^T \phi(x)$, and finds the parameters; the library methods of the two previous notebooks were given a long list of candidate terms and found which few to keep. Symbolic regression is given the data and only a vocabulary: a set of operators, such as $+$, $-$, $\times$, $\div$, $\sin$, $\cos$ and $\exp$, the input variables, and numerical constants. Its task is to find, among all expressions that can be written in that vocabulary, one that reproduces the data,


$$ \min_{f \in \mathcal{F}} \; \frac{1}{N}\sum_{i=1}^{N} \bigl(f(x_i) - y_i\bigr)^2 , \qquad \mathcal{F} = \{\text{all expressions built from the operators, the variables and constants}\} , $$


and to do so with an expression that is as short as possible. The second requirement is not decoration. The set $\mathcal{F}$ is infinite and contains, for any finite data set, expressions that pass through every point, so accuracy alone selects a monster; what is wanted is the simplest expression that is accurate to the noise, and the two requirements together define a Pareto front of size against error on which the law, when the data contain one, appears as a sharp elbow. The output is an expression a person can read, differentiate, set limits in and compare with a textbook, which is what makes the method a tool for discovery rather than for prediction alone: $\sin(x^2)$ says something about the data that a neural network fitted to the same points does not.


Three things make the problem hard. The space $\mathcal{F}$ is discrete, so there is no gradient from one expression to a better one; it is combinatorial, growing faster than exponentially with the length of the expression, so it cannot be enumerated; and it is rugged, since two expressions one symbol apart, $\sin(x^2)$ and $\cos(x^2)$, can have nothing in common as functions. These are the properties of the landscapes of Chapter 2, and the method of Chapter 3 was built for exactly them: keep a population of candidate expressions, let the accurate and short ones reproduce, make children by recombination and random change, and repeat. Symbolic regression by this route is called genetic programming, from Koza's work of the early 1990s, and it is the engine behind most symbolic-regression software, including the two packages used later in this notebook.


Expressions are trees

The genetic algorithm of Chapter 3 acted on chromosomes that were strings of a fixed length, and an expression cannot be such a string. Written out, $x\sin x + 0.5$ is a line of symbols, but the symbols are not independent positions: the $+$ applies to everything on either side of it, the $\sin$ applies only to the $x$ after it, and a different expression may need a different number of symbols altogether. What an expression has instead of positions is nesting, and the natural picture of nesting is a tree. The root is the operator applied last; each operator has as many children as it has arguments, two for $+$ and $\times$, one for $\sin$; and the leaves, where the branching stops, are the variables and the constants.


            +
           / \
          ×   0.5
         / \
        x   sin
             |
             x

Every node of this tree is the root of a smaller tree, and every one of those smaller trees is itself a complete expression: $\sin x$, $x \sin x$, $x$, $0.5$. This is the property that makes trees the right chromosome. Cutting a tree at any node leaves a valid expression on each side, and any subtree can be grafted onto any node of another tree and the result is still a valid expression, so a tree can be edited by the same two moves the strings allowed, recombination and random change, without ever producing a chromosome that does not decode. A string of symbols has no such property; cutting $x\sin x + 0.5$ between arbitrary characters and splicing it into another string gives nonsense almost always.


How the genetic algorithm meets the tree

Each part of Chapter 3 has its counterpart, and together they are genetic programming. The chromosome is the tree, of whatever size it needs, and a gene is a node. There is no decoding step: a tree computes its own function, so to evaluate an individual is to evaluate its tree at the data. The fitness is built from the error of that function on the data, to be made small, together with a penalty on the size of the tree; the selection rule compares fitness values rather than adding them, so the error is used as it stands and no shift to a non-negative maximization is needed. Selection is the tournament, the better of a few random trees.


Mutation changes one tree at one random node. In its simplest form the node itself is changed, an operator for another operator or a constant for a nearby value, as in the figure, where the $+$ at the root becomes a $-$ and $1.15y + 0.86$ becomes $1.15y - 0.86$; the form used in Chapter 5 replaces the whole subtree below the node by a freshly grown random one. Either way it is the bit flip of Section 3.4 with a node, or a subtree, in place of a bit: a small random change that introduces what the population does not yet contain.


No description has been provided for this image

Crossover takes two parents, picks a random node in each, and exchanges the subtrees beneath them. In the figure the subtree $1.15y$ of the first parent and the leaf $x$ of the second change places, and the two children are $x + 0.86$ and $(1.15y)^x$: each is most of one parent with a piece of the other grafted in, and both are valid expressions, because every subtree is one. This is the one-point crossover of Section 3.4 with "a point in the string" replaced by "a node in the tree", and it is where the population's memory is used: a piece that has proved useful in one parent is combined with a piece that has proved useful in another.


No description has been provided for this image

Both figures are from Cranmer, "Interpretable Machine Learning for Science with PySR and SymbolicRegression.jl", arXiv:2305.01582 (2023), Figures 1 and 2.


The initial population is a set of random trees, and the loop is the loop of Section 3.5.


Two difficulties are new, and both come from the fact that a tree has no fixed length. A tree can grow, and under crossover and mutation it does: a larger tree can always fit a little better, so without a counterweight the population fills with bloated expressions. The counterweight is the penalty on size, the parsimony term, the counterpart of the sparsity threshold of Sparse Regression for Equation Discovery, together with a hard cap on the number of nodes. And a tree needs constants, which evolution finds badly: a random constant is almost never the right one, and the only way to adjust it is a lucky mutation. The remedy is to let least squares find what least squares can, the overall scale and offset of the expression, so that the search has only to find the shape; this is linear scaling, and its generalization, refining every constant by least squares once the structure is found, is what the later packages do. This chapter builds the data structure, a tree as a small Python class that can evaluate, print and measure itself and list its nodes; the next builds the operators on it and runs the loop.

4.1. Representation and Evaluation

The tree is written as a class Node. A node knows three things: what it is, op, which is an operator name such as 'add' or 'sin', or 'x' for the variable, or 'c' for a constant; its children, a list holding two nodes for a binary operator, one for a unary operator and none for a leaf; and, for a constant only, its value. A whole expression is just its root node, since the root holds its children and they hold theirs. The class has four methods, each a few lines of recursion. evaluate computes the value of the expression at an array of inputs by evaluating the children first and then applying the operator; __str__ prints the expression in the usual notation, with parentheses, so that print(tree) shows a formula; size counts the nodes, which is the measure of complexity used throughout; and nodes returns the list of every node in the tree, which the operators of the next chapter will draw from. Division and the exponential are protected: a divisor near zero is replaced by a small number and the argument of the exponential is clipped, so that a random expression cannot produce an infinity that would poison the search.

In [167]:
import copy

SYMBOL = {'add': '+', 'sub': '-', 'mul': '*', 'div': '/'}

class Node:
    def __init__(self, op, children = (), value = None):
        self.op = op                                       # 'add', 'sub', 'mul', 'div', 'sin', 'cos', 'exp', 'x' or 'c'
        self.children = list(children)                     # two nodes, one node, or none for a leaf
        self.value = value                                 # the number, for a constant

    def evaluate(self, x):
        if self.op == 'x':
            return x
        if self.op == 'c':
            return self.value*np.ones_like(x)
        a = self.children[0].evaluate(x)                   # evaluate the children first ...
        if self.op == 'sin':
            return np.sin(a)
        if self.op == 'cos':
            return np.cos(a)
        if self.op == 'exp':
            return np.exp(np.clip(a, -20, 20))             # protected exponential
        b = self.children[1].evaluate(x)
        if self.op == 'add':                               # ... then apply the operator
            return a + b
        if self.op == 'sub':
            return a - b
        if self.op == 'mul':
            return a*b
        if self.op == 'div':
            return a/np.where(np.abs(b) < 1e-6, 1e-6, b)   # protected division

    def __str__(self):
        if self.op == 'x':
            return 'x'
        if self.op == 'c':
            return '%.3f' % self.value
        if self.op in SYMBOL:
            return '(' + str(self.children[0]) + ' ' + SYMBOL[self.op] + ' ' + str(self.children[1]) + ')'
        return self.op + '(' + str(self.children[0]) + ')'

    def size(self):
        return 1 + sum(child.size() for child in self.children)

    def nodes(self):                                       # every node of the tree, root first
        result = [self]
        for child in self.children:
            result = result + child.nodes()
        return result

def show(tree, depth = 0):                                 # the tree as an indented listing
    label = '%.3f' % tree.value if tree.op == 'c' else tree.op
    print('    '*depth + label)
    for child in tree.children:
        show(child, depth + 1)

example = Node('add', [Node('mul', [Node('x'), Node('sin', [Node('x')])]), Node('c', value = 0.5)])

print('expression :', example)
print('size       :', example.size())
print('value at x = 1, 2 :', example.evaluate(np.array([1.0, 2.0])))
print()
show(example)
expression : ((x * sin(x)) + 0.500)
size       : 6
value at x = 1, 2 : [1.34147098 2.31859485]

add
    mul
        x
        sin
            x
    0.500

The example is built from the inside out, a leaf Node('x') and a constant Node('c', value = 0.5) first, then the operators that combine them, which is the tree of the figure above read from the leaves up. Printed, it is $x\sin x + 0.5$ again; it has six nodes and evaluates to $1\cdot\sin 1 + 0.5 = 1.3415$ at $x = 1$. The indented listing is the tree itself, each node one level deeper than its parent: add at the root, under it mul and the constant, under mul the variable and sin, and under sin the variable. Every expression the search will consider is built, evaluated and printed by this one class, so the whole method rests on about forty lines.


4.2. Random Expressions

The search begins from random trees. random_tree(depth) chooses, at each node, between a leaf and an operator, with the probability of a leaf rising as the remaining depth falls, so that trees of varied shape and size are produced; an operator node is made by calling random_tree again for each child, one level shallower. The operator set here is $+$, $-$, $\times$, $\div$, $\sin$ and $\cos$; the exponential is available but not offered, to keep the first search small.

In [168]:
BINARY = ['add', 'sub', 'mul', 'div']
UNARY = ['sin', 'cos']

def random_tree(depth):
    if depth == 0 or (depth < 3 and np.random.rand() < 0.3):               # a leaf, more likely as the depth runs out
        if np.random.rand() < 0.6:
            return Node('x')
        return Node('c', value = np.round(np.random.uniform(-2, 2), 2))
    if np.random.rand() < 0.6:                                             # a binary operator with two random subtrees
        return Node(BINARY[np.random.randint(4)], [random_tree(depth - 1), random_tree(depth - 1)])
    return Node(UNARY[np.random.randint(2)], [random_tree(depth - 1)])     # a unary operator with one

np.random.seed(1)
for k in range(6):
    tree = random_tree(3)
    print('size %2d : %s' % (tree.size(), tree))
size 11 : ((x - x) + ((-1.890 + -0.330) * (0.860 + -1.630)))
size  8 : ((x - (0.130 * -0.740)) + cos(0.640))
size  7 : (((x * x) + -1.150) * x)
size 10 : (sin((-0.030 / x)) - (cos(0.160) - sin(x)))
size 12 : ((cos(-0.580) + (x - 0.650)) + (x / (0.290 * x)))
size  5 : sin((sin(x) - 0.210))

Six random trees of depth at most three, between five and twelve nodes. Most of them are nonsense as laws go, $(x - x) + \text{constant}$ among them, and that is expected: an initial population is raw material, not a set of guesses, and the search will keep what fits and discard the rest.




5. Genetic Programming

5.1. Crossover and Mutation

Genetic programming improves a population of trees by the two operations of Section 3.4, redefined for trees; the crossover and mutate of Chapter 3 acted on strings, and the versions below replace them. Both are short because of the way the tree is stored. A node holds its own operator and its own children, so the subtree below a node is the node: to exchange two subtrees it is enough to exchange what the two nodes contain, their op, value and children, and the rest of each tree, which only points at those nodes, follows along. Nothing has to be searched for or re-assembled.


Crossover copies the two parents, so that they survive unchanged in the population, picks a random node in each copy, and swaps the contents of the two nodes. Each child is then most of one parent with the other parent's subtree grafted in at the chosen node, as in the figure of Chapter 4, and both are valid expressions. Mutation copies one tree, picks a random node, and overwrites its contents with those of a freshly grown random tree, so that the whole subtree below the node is replaced. The copies are made with deepcopy, which copies the node and everything below it; without it the children would still be shared with the parents, and editing a child would edit its parent too.

In [169]:
def crossover(parent1, parent2):
    child1, child2 = copy.deepcopy(parent1), copy.deepcopy(parent2)       # the parents are left unchanged
    n1 = child1.nodes()[np.random.randint(child1.size())]                   # a random node in each child
    n2 = child2.nodes()[np.random.randint(child2.size())]
    n1.op, n2.op = n2.op, n1.op                                            # swap the two nodes ...
    n1.value, n2.value = n2.value, n1.value
    n1.children, n2.children = n2.children, n1.children                    # ... and the subtrees below them
    return child1, child2

def mutate(tree):
    child = copy.deepcopy(tree)
    n = child.nodes()[np.random.randint(child.size())]                      # a random node
    new = random_tree(2)
    n.op, n.value, n.children = new.op, new.value, new.children            # replace it, and its subtree, by a random one
    return child

np.random.seed(2)
p1 = Node('add', [Node('mul', [Node('x'), Node('x')]), Node('c', value = 1.0)])
p2 = Node('sin', [Node('mul', [Node('x'), Node('x')])])
c1, c2 = crossover(p1, p2)
print('parents   :', p1, '  and  ', p2)
print('crossover :', c1, '  and  ', c2)
print('mutation  :', mutate(p1))

point = copy.deepcopy(p1)                                                  # a point mutation: one operator changed
point.op = 'sub'
print('point     :', point)
print('parents after :', p1, '  and  ', p2)
parents   : ((x * x) + 1.000)   and   sin((x * x))
crossover : x   and   sin((x * ((x * x) + 1.000)))
mutation  : ((-0.800 / x) + (x / x))
point     : ((x * x) - 1.000)
parents after : ((x * x) + 1.000)   and   sin((x * x))

The crossover of $x^2 + 1$ with $\sin(x^2)$ happened to pick the root of the first parent and the second leaf $x$ of the second. Swapping the two nodes gave the first child the leaf alone, the single node $x$, and gave the second child the whole of $x^2 + 1$ in the place of that $x$, $\sin(x \cdot (x^2 + 1))$; a draw of two other nodes would have given, for instance, $\sin(x^2) + 1$. The mutation also happened to pick the root, so the whole of the first parent was replaced by a random tree. The point mutation changed one operator and nothing else, $x^2 + 1$ into $x^2 - 1$, which is the move of the first figure of Chapter 4. The last line confirms that the parents are untouched. None of these operations knows anything about the data. Selection, in the next section, is where the data enter.


5.2. Error, Linear Scaling and Parsimony

The quantity that scores a tree is its mean squared error on the data plus a penalty on its size,


$$ E(\text{tree}) = \frac{1}{N}\sum_i\bigl(a\,f_{\text{tree}}(x_i) + b - y_i\bigr)^2 + \lambda\cdot\text{size}(\text{tree}) , $$


to be made as small as possible, with two refinements. It is the fitness of Chapter 3 with the direction reversed: the tournament selection of the next section compares two scores and keeps the smaller, so no sign change and no shift are needed. The first is linear scaling: before the error is computed, the best scale $a$ and offset $b$ are fitted by least squares, which costs nothing and spares the search from having to discover them. A tree that has found the shape $\sin(x^2)$ is scored as if it had also found the amplitude and the baseline, which it would otherwise need two more operators and two constants to express. The second is the parsimony term $\lambda\cdot\text{size}$, the symbolic-regression counterpart of the sparsity threshold: without it, evolution adds nodes freely, because a larger tree can always fit a little better, and the population fills with bloated expressions.

In [170]:
def score(tree, x, y, parsimony):
    f = tree.evaluate(x)
    if not np.all(np.isfinite(f)):
        return 1e10, 1.0, 0.0
    # linear scaling: fit y = a f + b, so that the tree only has to find the shape
    A = np.column_stack([f, np.ones_like(f)])
    ab = np.linalg.lstsq(A, y, rcond = None)[0]
    mse = np.mean((A @ ab - y)**2)
    return mse + parsimony*tree.size(), ab[0], ab[1]

print('score of sin(x*x)    : %.5f' % score(Node('sin', [Node('mul', [Node('x'), Node('x')])]), x, y, 0.0)[0])
print('score of x*x         : %.5f' % score(Node('mul', [Node('x'), Node('x')]), x, y, 0.0)[0])
print('score of cos(x*x)    : %.5f' % score(Node('cos', [Node('mul', [Node('x'), Node('x')])]), x, y, 0.0)[0])
score of sin(x*x)    : 0.00037
score of x*x         : 0.36644
score of cos(x*x)    : 0.36722

Without the penalty, $\sin(x^2)$ has score $0.00037$, essentially the noise variance $0.0004$, while $x^2$ and $\cos(x^2)$ score $0.37$, no better than predicting the mean. The landscape is not smooth: $\cos(x^2)$ is one node away from the answer and is as bad as anything. This is why the search needs a population rather than a single improving candidate.


5.3. The Evolutionary Loop

The loop is the one of Section 3.5 with one change that almost every practical genetic algorithm makes. Score the population; fill the next generation by tournament selection in place of the roulette wheel, in which the better of five random individuals becomes a parent, written as the function tournament in the place of the select of Chapter 3, so that only the ranking of the scores matters and the error is compared directly; then crossover with probability $0.7$, which gives two children, mutation with probability $0.2$, or, with the remaining probability $0.1$, reproduction, the parent copied unchanged into the next generation; and repeat. Reproduction is the third operation of genetic programming after crossover and mutation, and the least eventful: it changes nothing, but it lets a good tree survive into the next generation more than once and so be picked as a parent more often, which is a mild form of the pressure that selection applies. A hard cap of $30$ nodes is a second guard against bloat. Three hundred trees for forty generations is the first run, on the data of Chapter 1.

In [171]:
def tournament(population, scores, k = 5):             # the best of k random individuals
    i = np.random.randint(len(population), size = k)
    return population[i[np.argmin(scores[i])]]

def run_gp(x, y, n_pop = 300, n_gen = 40, parsimony = 1e-3, seed = 0, verbose = True):
    np.random.seed(seed)
    population = [random_tree(np.random.randint(1, 5)) for k in range(n_pop)]
    history = []
    for gen in range(n_gen):
        scores = np.array([score(tree, x, y, parsimony)[0] for tree in population])
        best = population[np.argmin(scores)]
        history.append(scores.min())
        if verbose and gen % 5 == 0:
            print('generation %2d | best score %.5f | size %2d | %s' % (gen, scores.min(), best.size(), best))

        new_population = []
        while len(new_population) < n_pop:
            r = np.random.rand()
            if r < 0.7:
                children = crossover(tournament(population, scores), tournament(population, scores))
            elif r < 0.9:
                children = [mutate(tournament(population, scores))]
            else:
                children = [copy.deepcopy(tournament(population, scores))]   # reproduction: a parent copied unchanged
            for child in children:
                if child.size() <= 30 and len(new_population) < n_pop:    # a hard cap on bloat
                    new_population.append(child)
        population = new_population

    scores = np.array([score(tree, x, y, parsimony)[0] for tree in population])
    best = population[np.argmin(scores)]
    return best, population, history

best, population, history = run_gp(x, y)
mse, a, b = score(best, x, y, 0.0)
print('\nbest expression : y = %.3f * %s + %.3f' % (a, best, b))
print('mean squared error : %.5f  (noise variance 0.0004)' % mse)
generation  0 | best score 0.23090 | size  6 | cos(((x + 0.590) / 0.470))
generation  5 | best score 0.00437 | size  4 | sin((x * x))
generation 10 | best score 0.00437 | size  4 | sin((x * x))
generation 15 | best score 0.00437 | size  4 | sin((x * x))
generation 20 | best score 0.00437 | size  4 | sin((x * x))
generation 25 | best score 0.00437 | size  4 | sin((x * x))
generation 30 | best score 0.00437 | size  4 | sin((x * x))
generation 35 | best score 0.00437 | size  4 | sin((x * x))

best expression : y = 0.998 * sin((x * x)) + -0.002
mean squared error : 0.00037  (noise variance 0.0004)

The best tree in the random initial population is a cosine of a scaled, shifted $x$, with score $0.23$. Within the first few generations the population contains $\sin(x\cdot x)$, with score $0.0044$ including the parsimony term, and nothing better is found in the remaining generations because nothing better exists. With its linear scaling the final answer is $y = 0.998\sin(x^2) - 0.002$ with error $0.00037$: the law that sparse regression could not approach with eight polynomial terms, found by a search that was never told the form.

In [172]:
plt.figure(figsize = (6, 4))
plt.semilogy(history, 'k.-')
plt.xlabel('generation')
plt.ylabel('best score')
plt.grid(True)
plt.show()
No description has been provided for this image

The best score falls in steps and then is flat. The steps are the generations at which crossover or mutation produced a new best, from the initial cosine to $\sin(x^2)$ within the first few; the flat stretch afterwards is the population exploring without finding anything better. A history that is still falling at the last generation is the signal to run longer.


The discovered law is finally compared with the sparse-regression fit of Chapter 1 beyond the data.

In [173]:
plt.figure(figsize = (6, 4))
plt.plot(x_fine, np.sin(x_fine**2), 'k', linewidth = 3, alpha = 0.3, label = 'True law')
plt.plot(x, y, 'b.', markersize = 3, label = 'Data')
plt.plot(x_fine, a*best.evaluate(x_fine) + b, 'r--', linewidth = 1.5, label = 'Genetic programming')
plt.plot(x_fine, Theta_fine @ xi, 'g:', linewidth = 1.5, label = 'Sparse regression (polynomial)')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([0, 4])
plt.ylim([-1.5, 1.5])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

The genetic-programming result continues the oscillation through the third and fourth cycles on $[3, 4]$, where there were no data, because it has the form of the law and not an imitation of its values. The polynomial leaves the window at $x = 3.1$. Of all the tests in this course, extrapolation is the one that most clearly separates a discovered law from a fit, and symbolic regression, when it succeeds, passes it for the right reason.




6. Symbolic Regression with gplearn

6.1. The Same Problem in gplearn

The engine of Chapter 5 is enough to understand the method and too slow for serious use. The Python package gplearn implements the same algorithm with a scikit-learn interface, several mutation operators, protected functions, and populations of thousands. Its SymbolicRegressor takes the function set, the population size and number of generations, the parsimony coefficient, the range of random constants and the probabilities of the genetic operators. It does not do linear scaling, so it has to find amplitudes and offsets itself; on the first problem that makes no difference.

In [174]:
# %pip install gplearn
In [175]:
from gplearn.genetic import SymbolicRegressor

sr = SymbolicRegressor(population_size = 1000, generations = 20,
                       function_set = ['add', 'sub', 'mul', 'div', 'sin', 'cos'],
                       parsimony_coefficient = 0.001, const_range = (-2, 2),
                       p_crossover = 0.7, p_subtree_mutation = 0.1, p_hoist_mutation = 0.05, p_point_mutation = 0.1,
                       random_state = 0, verbose = 0)
sr.fit(x.reshape(-1, 1), y)

print('gplearn program :', sr._program)
print('length %d, fitness %.5f' % (sr._program.length_, sr._program.raw_fitness_))
gplearn program : sin(mul(X0, X0))
length 4, fitness 0.01566

gplearn returns sin(mul(X0, X0)), four nodes, in its own prefix notation. The reported fitness is the mean absolute error, $0.016$, which is the noise. One remark on reading its output: gplearn prints expressions with add, mul, div and so on as function names, and a long program needs patience to translate; a package such as sympy can simplify the string when needed.


6.2. Three Variables: Coulomb's Law

With more than one variable the space of expressions grows quickly, and this is where the population size matters. The data are the force between two charges at a distance, $F = q_1 q_2/r^2$ in units where the constant is one, with $1\%$ noise, from $300$ random triples. The function set is the four arithmetic operators.

In [176]:
np.random.seed(3)
n = 300
q1 = np.random.uniform(0.5, 3, n)
q2 = np.random.uniform(0.5, 3, n)
r = np.random.uniform(0.5, 3, n)
F = q1*q2/r**2*(1 + 0.01*np.random.randn(n))        # Coulomb force in units where k = 1, with 1 % noise

X3 = np.column_stack([q1, q2, r])

sr3 = SymbolicRegressor(population_size = 2000, generations = 20,
                        function_set = ['add', 'sub', 'mul', 'div'],
                        parsimony_coefficient = 0.002, const_range = (-2, 2),
                        feature_names = ['q1', 'q2', 'r'], random_state = 1, verbose = 0)
sr3.fit(X3, F)

print('gplearn program :', sr3._program)
print('length %d, relative RMS error %.4f' % (sr3._program.length_, np.sqrt(np.mean((sr3.predict(X3)/F - 1)**2))))
gplearn program : div(mul(q1, q2), mul(r, r))
length 7, relative RMS error 0.0100

div(mul(q1, q2), mul(r, r)), the inverse-square law, in seven nodes, with a relative error equal to the noise. Twenty generations of two thousand expressions took about fifteen seconds. The law is a product and a quotient of the variables with no constants, which is the easiest kind for genetic programming: constants are what it finds hardest, because a random constant is almost never right and small adjustments to it have to come from mutation.


6.3. PySR

gplearn is the library version of the engine of Chapter 5, and it has the same limits: it is pure Python and slow, it finds constants only by mutation, and it returns one program. The package PySR is the engine most used in current research, and it removes each of these. Its search runs in Julia, with many populations evolving in parallel and migrating between each other; every candidate expression has its constants optimized by a continuous optimizer before it is scored, which is the constant refinement by least squares, built into the loop; expressions are simplified algebraically as they are found; and the result is not one program but a hall of fame, the best expression at every complexity, a Pareto front of size against error returned as a table. The hall of fame is a record kept outside the populations, with one entry per complexity, updated whenever an expression beats the entry at its complexity, so that a good expression is never lost when it disappears from a population; PySR also copies members of the hall of fame back into the populations from time to time. Its inner loop is still the loop of this notebook, with two of the ideas of Chapter 2 built back in: a population is subsampled, a tournament picks a parent, the parent is copied and mutated or crossed, and the child replaces a member of the population. A mutation that makes the fit worse is not always rejected but accepted with a probability that depends on a temperature, the simulated annealing of Section 2.3 inside the genetic algorithm, so that the search can leave a good expression for a better one; the member replaced is the oldest rather than the worst, which keeps the population from converging too early; and the populations are islands that evolve independently and exchange members from time to time, which is the multistart of Section 2.1 made to share what it finds. Its interface is the same as gplearn's, a PySRRegressor with fit and predict.


Installation is one line, but the first import downloads and compiles the Julia backend, which takes a few minutes in Colab; later imports are fast. The problem given to it is one that also shows the most effective thing a scientist can do for a symbolic regression: shrink the problem before starting.

In [177]:
# %pip -q install pysr

from pysr import PySRRegressor

A projectile

The search space grows with the number of variables and with the number of constants the law contains. The range of a projectile launched at speed $v$ and angle $\theta$ is


$$ R = \frac{v^2\sin 2\theta}{g} , $$


two variables, a constant $g = 9.81$ that the search has to discover, and an angle that appears doubled inside a sine. The data are $300$ launches with $1\%$ noise. The search is first run on the raw variables with gplearn.

In [178]:
np.random.seed(3)
n = 300
v = np.random.uniform(5, 30, n)                      # launch speed (m/s)
th = np.random.uniform(0.1, 1.4, n)                  # launch angle (rad)
R = v**2*np.sin(2*th)/9.81*(1 + 0.01*np.random.randn(n))      # range of a projectile, 1 % noise

sr_raw = SymbolicRegressor(population_size = 2000, generations = 30,
                           function_set = ['add', 'sub', 'mul', 'div', 'sin', 'cos'],
                           parsimony_coefficient = 0.002, const_range = (-5, 5),
                           feature_names = ['v', 'th'], random_state = 1, verbose = 0)
sr_raw.fit(np.column_stack([v, th]), R)
print('raw variables (v, th) -> R')
print('length %d, RMS error %.2f m on ranges up to %.0f m' % (sr_raw._program.length_, np.sqrt(np.mean((sr_raw.predict(np.column_stack([v, th])) - R)**2)), R.max()))
print('program (first 120 characters) :', str(sr_raw._program)[:120], '...')
raw variables (v, th) -> R
length 148, RMS error 3.93 m on ranges up to 87 m
program (first 120 characters) : add(sub(div(th, -0.197), cos(th)), sub(add(v, add(mul(add(add(mul(add(v, add(add(add(th, v), add(-3.697, th)), sub(div(t ...

It fails. The best program after thirty generations of two thousand has $148$ nodes and an error of $3.9\,\mathrm{m}$ on ranges up to $87\,\mathrm{m}$, and its first hundred characters show why: it is building the shape out of sums and ratios of $v$ and $\theta$ and random constants, with nothing resembling $v^2$ or $\sin 2\theta$. The constant $1/g = 0.102$ and the factor $2$ inside the sine are each unlikely to be hit by chance, and the two-variable product structure has to be found at the same time.


Dimensional analysis

Dimensional analysis removes most of the difficulty. $R$ is a length and $v^2/g$ is a length, so the ratio $Rg/v^2$ is dimensionless and can depend only on the dimensionless input, $\theta$. The two-variable problem with a hidden constant becomes a one-variable problem with none. Buckingham's $\pi$ theorem guarantees that any physical law can be written in dimensionless groups, and that the number of groups is the number of variables minus the number of independent units, so the reduction is always available and always reduces the number of inputs.

In [179]:
# R has units of length, v^2/g has units of length, so R g / v^2 is dimensionless and depends on th alone
Pi = R*9.81/v**2

plt.figure(figsize = (6, 4))
plt.plot(th, Pi, 'k.', markersize = 4)
plt.xlabel(r'$\theta$ (rad)')
plt.ylabel(r'$R g / v^2$')
plt.grid(True)
plt.show()
No description has been provided for this image

The reduced data are a clean curve of one variable, and PySR is given it with the arithmetic operators and the sine and cosine. maxsize bounds the complexity of an expression, niterations is the number of rounds of evolution over all populations, and deterministic with parallelism = 'serial' makes the run repeatable at the cost of speed.

In [180]:
model = PySRRegressor(binary_operators = ['+', '-', '*', '/'],
                      unary_operators = ['sin', 'cos'],
                      maxsize = 15,
                      niterations = 40,
                      populations = 15,
                      deterministic = True,
                      parallelism = 'serial',
                      random_state = 0,
                      verbosity = 0,
                      progress = False,
                      temp_equation_file = True)
model.fit(th.reshape(-1, 1), Pi, variable_names = ['th'])

print(model.equations_[['complexity', 'loss', 'equation']].to_string(index = False))
print()
print('selected :', model.sympy())
print('relative RMS error : %.4f' % np.sqrt(np.mean((model.predict(th.reshape(-1, 1))/Pi - 1)**2)))
 complexity     loss                                                               equation
          1 0.054970                                                              0.7468658
          4 0.000062                                                    sin(th * 2.0004673)
          6 0.000061                                        sin(th * 2.0008135) * 1.0008024
          8 0.000061                       (sin(th * 2.0006027) * 1.0021529) - 0.0011374789
         10 0.000061               (sin(th * 2.0009878) * 1.0011737) - (0.00016556852 / th)
         12 0.000061 (sin(th * 2.0009878) * 1.0011737) - (0.00016556852 / (th * 1.0011737))

selected : sin(th*2.0004673)
relative RMS error : 0.0100

The table is the hall of fame: one row per complexity, with the loss of the best expression found at that complexity and the expression itself, already simplified. Read it as the Pareto front of size against error, the symbolic-regression version of the number-of-terms curve of Sparse Regression for Equation Discovery. The loss falls as the complexity rises until $\sin 2\theta$ appears, and past that point the extra nodes buy nothing, so the front has its elbow at the law. The row PySR selects by default is chosen by a score that rewards a large drop in loss for a small increase in complexity, which is the elbow rule made automatic, and the selected expression is returned in sympy form with its constants already optimized. The full law follows by multiplying back, $R = (v^2/g)\sin 2\theta$. Nothing about the search changed between the failure and the success; the problem was made one a search could solve.

Remark (what to carry over). Everything this notebook did by hand is in PySR: the population and the operators of Chapter 3, the trees of Chapter 4, the parsimony of Chapter 5, and the refinement of constants. What PySR cannot do is the work before the search: choosing the variables, reducing them by dimensional analysis, and deciding what counts as simple. That remains the scientist's part, with any engine.




7. Where Discovery Stands

Three notebooks have presented three methods, and they are best seen as one method with increasing freedom and increasing cost.


Sparse regression SINDy Symbolic regression
Finds coefficients of given terms coefficients of given terms, per equation the expression itself
Needs a library a library and derivatives of the data operators, variables, and patience
Cost milliseconds seconds minutes to hours
Deterministic yes yes no
Fails when the law is not in the library, or the library is collinear the derivative is too noisy, or the library is wrong the search space is too large, or constants are needed
Best for algebraic laws with known candidate forms dynamics with polynomial or otherwise listable right-hand sides laws of unknown form in few variables

The practical order is this. Reduce the problem first, by dimensional analysis, since every method benefits and symbolic regression depends on it. Try a library, because if the law is in it the answer is immediate and exact, and the Pareto curve will say whether it is. If the curve has no elbow, run a free search, and read its result as a proposal for the library rather than as a final law. Refine constants by least squares, validate by extrapolation, and repeat with different seeds and thresholds until the answer stops changing.


The tools keep improving. PySR, used in Section 6.3, is the most capable symbolic-regression engine available at the time of writing and handles problems of ten or more variables; the methods it implements are the ones this notebook built by hand, and a reader who has followed the hand-built engine will find nothing in it that is new in kind.




Summary

Key takeaways

  • A library-based method finds only what the library contains; $\sin(x^2)$ defeated an eight-term polynomial library at every threshold, and a library large enough to contain everything is too collinear to use.
  • Searching expressions is a search without gradients. Local search stops on the first hill it climbs; a heuristic gives up the guarantee of optimality to search such spaces anyway, simulated annealing by accepting downhill moves with a decaying probability, the genetic algorithm by keeping a population.
  • A genetic algorithm has four parts: an encoding of solutions as chromosomes, a non-negative fitness to be maximized, selection with probability increasing in fitness, and the two operators crossover, which recombines two parents, and mutation, which injects what the population lacks. A population learns where the landscape is good, which a single point cannot.
  • Symbolic regression searches expressions directly. An expression is a tree; genetic programming is the same loop with subtree crossover and mutation and tournament selection, scored by error plus a parsimony penalty, with linear scaling so that the search finds shapes and least squares finds amplitudes.
  • Dimensional analysis decides whether a search succeeds. The projectile was unsolvable on its raw variables and solved at once on its dimensionless group.

Looking ahead. Discovery closes a loop that the rest of this course opened. Physics-Informed Neural Networks put a known equation into the training of a network; Deep Neural Operators and Fourier Neural Operator learned the solution map of a known equation from data. The three discovery notebooks ask where the equation comes from when it is not known, and answer that it can come from the data, provided that what is known, the units, the symmetries, the candidate forms, is given to the method first. Equations found this way can be handed back to a PINN as its physics, and that is the direction in which the field is moving: networks that fit data, discover the equation that the fit obeys, and are then constrained by the equation they discovered.