Genetic programming
Genetic programming (GP) is an evolutionary method that evolves computer programs (often represented as trees) to solve problems such as symbolic regression, classification or control.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Genetic programming is used by engineers to automatically discover algorithms or expressions when the form of the solution is unknown. It is useful in symbolic regression, automated feature construction, program synthesis and evolving controllers where traditional human design is hard.
Key ideas
Function set — the set of allowed operators (e.g. {+, -, *, /, sin, cos}). Each function has an arity (number of children). Functions must be chosen so resulting trees are syntactically valid. Ensure closure: every function accepts and returns values in the allowed types so any subtree can legally appear where a function's argument is expected.
Terminal set — the set of leaves (e.g. problem inputs like x1, x2 and constants). Constants used only during run are called ephemeral random constants; ERCs are generated at tree creation/mutation time from a distribution (e.g., uniform) rather than being a fixed list of constants.
Fitness — a measure of how well a program solves the problem (higher or lower depending on convention). For regression, a common fitness is mean squared error (MSE) over a dataset. Minimisation GP treats lower fitness as better. To avoid overfitting, evaluate on a validation set and keep a separate test set for final reporting.
Initialization — how the initial population is created. Common methods: full, grow, and ramped half-and-half (a mix to create varied tree depths). Ramped half-and-half produces trees of various depths to maintain diversity.
Selection — method to pick parents biased by fitness. Common methods: tournament selection (choose k random individuals, best wins), roulette-wheel / fitness-proportionate (probability proportional to a nonnegative fitness/score), and rank selection.
Crossover (subtree crossover) — a key GP operator: choose a random subtree in parent A and a random subtree in parent B; swap them to form two children. This preserves syntactic validity if arities and typing are consistent.
Mutation (subtree mutation, point mutation) — replace a randomly chosen subtree with a newly generated subtree (subtree mutation). Point mutation changes a node (e.g., replace + with -) without changing structure.
Reproduction / Elitism — copying best individuals unchanged into next generation to preserve good solutions.
Parsimony pressure — a method to reduce bloat (growth of tree size without fitness improvement). Add a penalty term to fitness proportional to tree size or use a limit on tree depth/size.
Strong typing — restrict functions and terminals so only semantically correct subtrees can be swapped (useful when functions expect certain types: e.g. boolean vs numeric).
Protected operators — operators that avoid runtime errors (e.g. protected division returns 1.0 when divisor is zero). Use protected operators to avoid crashes during evaluation.
Algorithm (generational GP) — exact pseudocode students should be able to write and draw a diagram for (population vs generations):
- Initialize population P0 using ramped half-and-half to a max depth.
- Evaluate fitness of each program in P0 on the training data.
- Repeat for generation t = 1..G (or until a termination criterion such as no-improvement for T generations or acceptable fitness is reached): a. Select parents from Pt-1 using tournament selection. b. Apply crossover with probability pc to parent pairs (subtree swap). c. Apply mutation with probability pm to offspring (subtree replacement). d. Optionally copy elites from Pt-1 to Pt (elitism). e. Evaluate fitness of new individuals to form Pt.
- Return best program found.
Draw this diagram: draw a box labelled Population Pt-1 containing several trees (draw 4 small trees). Draw arrows from two selected trees to a crossover box, show two offspring trees created by swapping subtrees. Also draw a mutation box where one offspring has a subtree replaced. Label selection, crossover, mutation probabilities.
Formulas
fitness = (1/N) * Σ_{i=1..N} (y_i - ŷ_i)^2 — mean squared error (MSE). y_i = target value (unit depends on problem), ŷ_i = program output, N = number of data points. Applies for regression where lower is better.
prob_select_i = f_i / Σ_j f_j — fitness-proportionate selection probability. f_i is fitness score where higher means better; if using error minimisation convert to a score like s_i = 1/(1+error_i) before applying.
p_cross, p_mut — crossover and mutation probabilities (dimensionless, between 0 and 1). Typical defaults: p_cross ≈ 0.8..0.9, p_mut ≈ 0.01..0.1 but verify for problem.
size_penalty = α * size(tree) — parsimony penalty added to fitness (α is tunable), where size(tree) typically counts the number of nodes. Units same as fitness.
Protected division example function: protected_div(a,b) = a / b if b != 0 else 1.0.
Syntax to remember (tree creation in pseudocode): Node(function, child1, child2, ...) and terminals as Terminal(value).
Worked examples
Model answer — one-generation subtree crossover (theory):
- Parents (in prefix form):
Parent A:
(+ (* x x) x)(represents x*x + x) Parent B:(- (/ x 1) 2)(represents x/1 - 2) - Choose random subtree in A:
(* x x)(left child of +). - Choose random subtree in B:
(/ x 1)(left child of -). - Swap them. Offspring O1:
(+ (/ x 1) x)representingx/1 + x(which simplifies algebraically to2x). Offspring O2:(- (* x x) 2)representingx*x - 2. - If using protected division,
/ x 1is safe. Explain each step and draw trees showing swapped nodes. This is the type of step-by-step diagram exam questions expect.
- Parents (in prefix form):
Parent A:
Simple Python GP for symbolic regression (complete program). This is a compact, readable GP that evolves arithmetic expressions to fit target f(x)=x**2 + x + 1 on a small dataset. The code uses protected division, tournament selection, subtree crossover and subtree mutation. It sets a random seed for reproducibility. Note: GP is stochastic; exact output varies by run and budget even with a fixed seed. Do not assume a specific best fitness.
# Simple GP for symbolic regression (readable, small)
import random, math
random.seed(42)
FUNCTIONS = ['+', '-', '*', '/']
TERMINALS = ['x', -1.0, 0.5, 1.0, 2.0]
MAX_DEPTH = 4
POP_SIZE = 50
GENERATIONS = 20
TOURN_SIZE = 3
P_CROSS = 0.9
P_MUT = 0.2
# Tree representation: either ('func', left, right) or ('term', value)
def make_random_tree(depth=0):
if depth >= MAX_DEPTH or (depth>0 and random.random() < 0.3):
t = ('term', random.choice(TERMINALS))
return t
func = random.choice(FUNCTIONS)
return ('func', func, make_random_tree(depth+1), make_random_tree(depth+1))
def eval_tree(tree, x):
ttype = tree[0]
if ttype == 'term':
v = tree[1]
return x if v == 'x' else v
_, op, left, right = tree
a = eval_tree(left, x)
b = eval_tree(right, x)
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
# protected division
return a / b if b != 0 else 1.0
# Fitness: mean squared error on sample points
DATA_X = [-1.0, -0.5, 0.0, 0.5, 1.0]
TARGET = lambda x: x*x + x + 1
def fitness(tree):
err = 0.0
for x in DATA_X:
y = eval_tree(tree, x)
err += (y - TARGET(x))**2
return err / len(DATA_X)
# Selection: tournament
def tournament(pop):
best = None
for _ in range(TOURN_SIZE):
cand = random.choice(pop)
if best is None or cand[1] < best[1]:
best = cand
return best[0]
# Crossover: swap random subtree
def all_nodes(tree):
nodes = []
def rec(t, parent, index):
nodes.append((t, parent, index))
if t[0] == 'func':
rec(t[2], t, 2)
rec(t[3], t, 3)
rec(tree, None, None)
return nodes
import copy
def crossover(a, b):
a_copy = copy.deepcopy(a)
b_copy = copy.deepcopy(b)
nodes_a = all_nodes(a_copy)
nodes_b = all_nodes(b_copy)
node_a, parent_a, idx_a = random.choice(nodes_a)
node_b, parent_b, idx_b = random.choice(nodes_b)
# perform swap by rebuilding trees (simple and safe for tuples)
def replace_subtree(tree, target_node, new_sub):
if tree is target_node:
return new_sub
if tree[0] == 'func':
left = replace_subtree(tree[2], target_node, new_sub)
right = replace_subtree(tree[3], target_node, new_sub)
return ('func', tree[1], left, right)
return tree
child1 = replace_subtree(a_copy, node_a, node_b)
child2 = replace_subtree(b_copy, node_b, node_a)
return child1, child2
# Mutation: replace random subtree with new random subtree
def mutate(tree):
nodes = all_nodes(tree)
node, _, _ = random.choice(nodes)
def replace_subtree(tree, target_node):
if tree is target_node:
return make_random_tree()
if tree[0] == 'func':
left = replace_subtree(tree[2], target_node)
right = replace_subtree(tree[3], target_node)
return ('func', tree[1], left, right)
return tree
return replace_subtree(tree, node)
# Initialize population
population = [(make_random_tree(), None) for _ in range(POP_SIZE)]
for i in range(POP_SIZE):
population[i] = (population[i][0], fitness(population[i][0]))
# Evolution
for gen in range(GENERATIONS):
newpop = []
# elitism: keep best
population.sort(key=lambda x: x[1])
newpop.append(population[0])
while len(newpop) < POP_SIZE:
parent1 = tournament(population)
parent2 = tournament(population)
if random.random() < P_CROSS:
child1, child2 = crossover(parent1, parent2)
else:
child1, child2 = parent1, parent2
if random.random() < P_MUT:
child1 = mutate(child1)
if random.random() < P_MUT:
child2 = mutate(child2)
newpop.append((child1, fitness(child1)))
if len(newpop) < POP_SIZE:
newpop.append((child2, fitness(child2)))
population = newpop
best = min(population, key=lambda x: x[1])
print('Best fitness:', best[1])
print('Best program (prefix):', best[0])
Note on output: Because GP is stochastic, exact output will vary. With this target, an optimal program that achieves zero MSE on DATA_X is:
('func', '+', ('func', '+', ('func', '*', ('term', 'x'), ('term', 'x')), ('term', 'x')), ('term', 1.0))
Do not assume Best fitness will be 0.0 in every run or with this seed and budget.
- Model answer — explain parsimony pressure derivation:
- If raw fitness is error E, define penalised fitness P = E + α·size. For minimisation, show derivative with respect to size when choosing between two programs with equal E: choose smaller if α>0. Show how α controls trade-off.
Common mistakes
- Not constraining tree depth, leading to uncontrolled bloat and very slow evaluation.
- Using raw error as selection in fitness-proportionate selection (if lower is better, must convert to a score or use tournament/rank selection).
- Swapping subtrees without type checks in strongly-typed problems, producing semantically invalid programs.
For your exam
Types of questions:
- Definitions: define GP, subtree crossover, terminal/function sets, parsimony pressure, protected operator.
- Short notes: explain initialization methods (full/grow/ramped half-and-half), tournament selection, bloat and remedies.
- Derivations: show why parsimony penalty chooses smaller trees for equal error; derive MSE expression and how it changes under a small change in output.
- Numericals / worked steps: perform a subtree crossover step, compute fitness values for small trees on given dataset.
- Programs: write pseudocode for GP (initialization, evaluate, select, crossover, mutate, next generation); write a small Python program to evaluate a given tree.
What a full-marks answer includes:
- Precise definitions (bold the defined term).
- Correct pseudocode or step-by-step operations with clear parameter values.
- For diagrams: labelled trees before and after crossover / mutation.
- For programs: correct protected operators and a note on reproducibility (random seed).
Quick check
- What is the usual tree node type used to represent functions in GP?
- Why use protected division in GP?
- Name two methods to control tree bloat.
Answers: 1. Function/internal node (operator) 2. To avoid runtime errors when divisor is zero 3. Parsimony pressure (penalty), maximum depth/size limits, or limiting growth via operator probabilities
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?