Explainable AI by Genetic Programming: An Interactive Tutorial
Machine learning models now help decide who gets a loan, which patient is seen first and how a self-driving car brakes. When such a model makes a decision, we want to know why. This tutorial introduces explainable artificial intelligence (XAI) and shows how genetic programming (GP), a branch of evolutionary computation, can learn models that people can actually read. It assumes no background in XAI, evolutionary computation or GP. Every idea comes with a demo you can play with, and every demo has a Show Python code button with a complete, commented program you can copy and run.
1. Why Should a Model Explain Itself?
A model that is right 99% of the time sounds great. But if nobody can see how it decides, nobody can tell whether it is right for the right reasons. The survey gives four reasons why explanations matter:
Clever Hans was a horse that seemed to do arithmetic but was really reading its trainer's body language. Models do the same: a famous image classifier told wolves from huskies by looking for snow, because most wolf photos in its training data had snowy backgrounds.
A bank that declines a loan must say why. The COMPAS system, used in US courts to predict reoffending, was found to be racially biased: an explanation would have exposed that.
Regulations such as the EU's General Data Protection Regulation (GDPR) give people a right to meaningful information about automated decisions.
AlphaGo played moves that experts first thought were mistakes. If a model can explain such a move, people can learn from it.
Let's catch a Clever Hans ourselves. Two models learn to tell wolves from huskies using three facts about each photo: the animal's weight, whether it has blue eyes, and whether there is snow in the background. One model is a black box: it only gives an answer and a confidence. The other is a tiny readable model, a one-rule decision tree of the kind GP can evolve.
Training photos (snowy background = blue tint, grass = green tint):
Pick a new photo to classify:
2. Key Ideas in Explainable AI
Interpretability and explainability
You will meet many similar words: understandability, comprehensibility, interpretability, explainability, transparency. Their exact definitions differ slightly, but like the survey we use interpretable and explainable interchangeably: a model is interpretable if a person can understand how it turns inputs into outputs. Lipton describes three levels of transparency:
What makes a good explanation? The social scientist Tim Miller argues that people like explanations that are contrastive ("why A rather than B?"), selected (one or two main causes, not all of them) and social (part of a conversation).
How do we measure interpretability?
Doshi-Velez and Kim describe three ways to evaluate an explanation, from most to least expensive:
- Application-grounded: real users judge the explanation on the real task, for example doctors rating an AI diagnosis tool.
- Human-grounded: simpler experiments with ordinary people. In a forward simulation test, people get the model and an input and must predict the output. In a counterfactual test, they must say how to change the input to get a different output.
- Functionally-grounded: no humans at all. Use a proxy measure such as model size, and optimise it alongside accuracy. Most GP research uses this, because it is cheap.
Try a human-grounded test on yourself. Three models predict daily ice-cream sales from the temperature T (°C) and whether it rains (R = 1) or not (R = 0). All three give sensible answers. Predict what each one says, and see how long it takes you.
| Model | Complexity | Correct | Average time |
|---|
tanh and two hidden units, and you cannot tell what any weight "means". This is what simulatability measures.The accuracy–interpretability trade-off
Gunning and Aha sketched a famous trade-off: the most accurate models (deep neural networks, ensembles) tend to be the hardest to explain, while easy-to-read models (linear models, decision trees, rules) may be less accurate. The chart is notional, not measured, but it explains why XAI is hard: we usually want both.
GP sits in an interesting place. Its models are symbolic (formulas and programs you can read), yet it searches a much richer space than a greedy decision-tree learner, so it can often find models that are both accurate and readable.
Intrinsic or post-hoc?
Murdoch et al. separate two kinds of accuracy. Predictive accuracy is how well the model fits the data. Descriptive accuracy is how well an explanation describes what the model has learned. There are two ways to get explanations:
- Intrinsic interpretability: build interpretability into training, so the final model explains itself. This improves descriptive accuracy, sometimes at a small cost in predictive accuracy. For high-stakes decisions, Cynthia Rudin argues this is the right choice, and it is often possible because many different models fit the data almost equally well (a large "Rashomon set").
- Post-hoc interpretability: train any model you like, then explain it with a second, more readable model. Predictive accuracy is untouched, but the explanation is only an approximation.
3. Genetic Programming, and Why It Suits XAI
Genetic programming evolves computer programs, often written as trees. Leaves are inputs and constants (terminals); inner nodes are operations (functions). The tree on the right reads x × (x + 1). GP starts from random trees and repeats an evolutionary loop:
- Evaluate each program with a fitness function (for example, its error on the data).
- Select good programs as parents (for example, by a tournament: pick a few at random, keep the best).
- Vary them: crossover swaps subtrees between two parents, mutation replaces a subtree with a random one.
- Replace the old population with the children, and repeat for many generations.
New to GP? The Genetic Programming tutorial lets you watch every step.
The survey highlights three reasons why GP is a natural fit for XAI:
GP models are symbolic: formulas, rules and programs built from operators people know. GP can also learn other readable model types, such as decision trees, rule sets and fuzzy pattern trees, often more accurately than greedy learners like C4.5.
GP searches with a whole population, so it can return many models at once, from tiny and rough to large and precise, and let a person choose.
Measures of interpretability (size, number of features, unit consistency…) are discrete and not differentiable. Evolution does not care: anything you can compute can be optimised.
But "readable by design" is not enough. Left alone, GP tends to evolve huge programs. The survey groups the ways to fix this into a taxonomy, which the rest of this tutorial follows:
4. Intrinsic Strategy 1: Smaller Models
The most common proxy for interpretability is model size, such as the number of nodes in the tree. Smaller programs take fewer steps to simulate in your head. The enemy is bloat: as evolution goes on, GP programs grow quickly, often filling up with code that does nothing useful (like x − x or × 1). Controlling bloat is one of the oldest topics in GP. The survey groups the strategies by where they act in the GP loop:
- Depth/size limits. Discard (or never create) programs above a limit. Variants adapt the limit during the run, or use fixed-size templates, as Cartesian GP does with its grid of nodes.
- Parsimony pressure. Penalise size in the fitness:
g = f + p(s), wherefis the error andsthe size. A death penalty gives oversized programs the worst fitness; a linear penalty usesp(s) = β × s. Lexicographic selection compares error first and size only to break ties; double tournament runs a size tournament before a fitness tournament. Multi-objective GP (with NSGA-II or SPEA2) treats size as a second objective and returns a whole front of trade-offs. - Genetic operators against bloat. Make children no bigger than their parents: one-point and homologous crossover swap matching parts, size-fair crossover and mutation swap subtrees of similar size, and point mutation changes a single node.
- Size distribution control. Shape the sizes of the whole population, for example with operator equalisation, which accepts children only if they keep the population's size histogram close to a target.
Compare the strategies yourself. GP fits noisy data from y = x³ − x + 1. Run it once with each strategy: the size chart keeps every run so you can compare them.
Generation – · average size – · programs on the front –
- Run No control, then Linear penalty. Plain GP's average size usually keeps climbing while its error hardly improves: that is bloat. With the default β = 0.005, the penalty keeps programs many times smaller, typically with a similar error. (Every run is different, so try each strategy a few times.)
- Raise β to 50 (= 0.05): programs become tiny but inaccurate. Lower it to 1 (= 0.001): bloat creeps back. Choosing β is the hard part.
- Try Lexicographic: errors on noisy data rarely tie, so it controls size much less than the penalty here. It works much better when fitness takes few values (such as classification accuracy, used in Demo 6).
- Run Multi-objective and click points on the Pareto front: you get a menu of models, from
x × x × x-sized to larger and more precise.
Explicit simplification
The fifth strategy is to simplify programs explicitly. The design decisions are when (every k generations, or only at the end), which programs (all, the best, random ones, or the parents) and how. Simplifying too often can destroy useful building blocks, so these choices go together. There are two ways to simplify:
- Genotypic (by structure): algebra rules such as
x − x → 0andx ÷ x → 1, or domain rules such asmax(x, x − y) → xwhenyis always positive. The program computes exactly the same thing. - Phenotypic (by behaviour): replace a subtree with something smaller that behaves almost the same on the data. A popular test is the permutation test: shuffle a subtree's outputs across data points; if the model's error barely changes, the subtree is not contributing.
Size nodes · error on the data
Orange: the part about to change. Green: what replaced it. The data come from y = x² + x + 1.
5. Intrinsic Strategy 2: Lower Complexity
Size is only part of the story. sin(exp(x × x)) has just 5 nodes, but few people can picture it. The survey describes two families of complexity measures beyond size:
- Structural complexity looks at the shape of the tree. Visitation length (also called expressional complexity) adds up the sizes of all subtrees, so deep, lopsided trees score higher than flat, balanced trees of the same size. Other measures weight hard functions such as
sin,cosandexpmore heavily, especially when nested. - Functional (behavioural) complexity looks at what the model computes. Examples: the degree of a Chebyshev polynomial that approximates it, its curvature (how often its slope changes), Tikhonov regularisation, the VC dimension, the Hessian, Rademacher complexity (how well it can fit random noise), or simply how long it takes to evaluate.
- Indirect methods such as evaluating each generation on a random sample or bootstrap of the data reduce overfitting, and with it unnecessary complexity.
Click a column header to rank the models by that measure, and a row to see the model.
sin(exp(x²)) oscillates faster and faster as x grows, and F follows. Each measure captures a different aspect, which is why the survey recommends considering size, complexity, features and structure together.6. Intrinsic Strategy 3: Fewer Features
Miller's "selected" property says a good explanation names one or two causes, not fifty. In GP terms: use few distinct features. GP has two built-in abilities here:
- Feature selection. A tree only contains the features evolution found useful, so it selects features automatically. Features can also be ranked by how often they appear in good GP models, or by permutation importance. On gene-expression data with thousands of features, GP has picked out fewer than 1% of them without losing accuracy.
- Feature construction. A GP tree is itself a new, high-level feature, such as
gene₁ + gene₂ − gene₃ − gene₄, that can separate classes far better than any original feature. Multi-tree GP builds one feature per class, each using only that class's most relevant inputs.
Here, 120 examples have 8 features, but the class depends only on x2 + x5 − x7 (with 4% label noise). GP classifiers say "class 1" when their output is positive; ties in accuracy go to the smaller tree.
A. Feature ranking. How often each feature appears in the best model of a GP run (relevant features in orange).
Best models so far:
B. Build a feature yourself. Click features to add (+), subtract (−) or drop (·) them. Each dot is an example, placed by its value of your feature.
x2 + x5 − x7 yourself and see the two classes pull apart, compared with any single feature alone. That combined feature is exactly what GP constructs.7. Intrinsic Strategy 4: Meaningful Structures
A model is easier to decompose when each part means something. The survey describes three ways to give GP models meaningful structure.
Interpretable function nodes
Instead of generic +, exp or AND, give GP domain-specific building blocks. In image classification, nodes can be "detect this rectangular region", "apply a Gaussian filter" or "take the standard deviation". Strongly typed GP makes sure such nodes only receive the right kind of input (an image, a region, a number), so an evolved tree reads like a recipe: look at the top-right corner, measure its brightness, compare with the centre. GP can also evolve classic readable models directly: decision trees (each node a feature test), oblique decision trees with tests on small linear combinations, rule sets and fuzzy pattern trees.
Interpretable combinations of nodes
Even with plain arithmetic, some combinations make no sense. In physics, adding a mass to a length is meaningless. Dimensionally aware GP gives every node a unit type, written as exponents over kilograms, metres and seconds: speed is [0, 1, −1] (m·s⁻¹). Then:
a + banda − bneed the same unit, and keep it;a × badds exponents;a ÷ bsubtracts them.
Programs that break the rules are penalised. This has rediscovered conservation laws and Feynman equations, and produced readable scheduling rules.
Variables: mass m [kg], speed v [m·s⁻¹], height h [m], time t [s], gravity g [m·s⁻²]. The target is an energy E in joules [kg·m²·s⁻²].
Formulas a free GP might evolve:
Or build your own: (a op b) op (c op d)
A more general way to restrict structure is a grammar. Grammar-guided GP and grammatical evolution only produce programs that follow a context-free grammar written by an expert, for example for scheduling heuristics or physics laws. Even with no domain knowledge, a grammar can force a readable shape: the canonical form alternates "linear" layers (sums of simple polynomial terms) with "nonlinear" layers (a polynomial times one nonlinear function of another linear layer), for example 2x + 3 + y · sin(x − 1).
Problem decomposition
Instead of one giant model, learn several small, understandable pieces:
- Sequential: solve easier sub-problems first and reuse their solutions as building blocks, as in automatically defined functions (ADFs), layered learning and run-transferable libraries.
- Parallel: each piece handles part of the data and the pieces work as a team or ensemble, as in cooperative co-evolution, orthogonal evolution of teams and tangled program graphs.
8. Intrinsic Strategy 5: Learn What "Interpretable" Means
All the measures so far are guesses about what humans find easy. Interpretability is subjective: it depends on who is reading. Virgolin and colleagues therefore asked people to judge many random formulas and learned an interpretability measure from their answers: a weighted sum of four features (size, number of operations, number of non-arithmetic operations, and number of consecutive non-arithmetic operations). Optimising this learned measure gave GP models that were more accurate than just minimising size, at the same level of interpretability. Their later system, ML-PIE, keeps a human in the loop: during evolution it shows the user pairs of models, asks which is easier to read, and updates its interpretability objective as it goes.
Do it yourself: pick the formula you find easier to understand. After each answer, a logistic (Bradley–Terry) model learns how much each feature makes a formula harder for you.
Which formula is easier to understand? (Answers so far: 0)
What makes a formula hard for you (bar to the right = more of this makes it harder):
Easiest for you (of 40 formulas):
Hardest for you:
exp and log. This is why learned and personalised measures matter, and also why collecting enough human feedback is expensive.9. Post-hoc Explanations by GP
Sometimes the model already exists, perhaps a deep neural network or a random forest, and we need to explain it after the fact. Post-hoc XGP methods train a GP model to imitate it. The survey notes that far fewer studies take this route.
- Global explanation imitates the black box everywhere. Sample many inputs, ask the black box for its outputs, and evolve a small GP model (a surrogate) that reproduces them. How well it does is called fidelity. Multi-objective GP has replaced a large neural network with a 4-level decision tree giving the same predictions; G-REX extracts compact rules from opaque models.
- Local explanation imitates the black box only near one input, answering "why this prediction?". Sample inputs close to it (for example from a Gaussian around it), and fit a simple model, as LIME does with linear models. GP can evolve the local model, and a linear model can in turn explain a complex GP model locally. For sequential decisions, a linear model can explain why a GP policy ranks one action above the others in a given state.
The black box (colour = its output; amber high, teal low). Click anywhere to explain that prediction locally.
A global GP surrogate trained only on the black box's answers at 150 random points, with a small size penalty.
Press the button to evolve a surrogate (50 generations).
x₁ matters most in the middle, while x₂ takes over in the corners. One local explanation is simple and faithful, but only locally. The global surrogate describes the whole map in one formula, at the price of lower fidelity. Run it twice: GP may find different, equally good formulas.10. Visualisation
People understand pictures much faster than tables of numbers. The survey covers two directions:
- Visualisation by GP. To plot high-dimensional data in 2D, GP can evolve the mapping itself, as readable formulas. GP-MaL (manifold learning) keeps each point's neighbours in the same order, and GP-tSNE uses the t-SNE objective; both compete with standard methods but also tell you which features make up each axis. Multi-objective versions such as MOG3P trade off class separation, visual clarity and formula simplicity. Even the constructed features of Demo 6 can serve as the axes of a scatter plot.
- Visualisation for GP. Plots of fitness and diversity over time, heat maps of how often subtrees are used, ancestry graphs of a whole run and maps of evolved scheduling rules help researchers understand how GP found its models, and how to improve it.
11. Applications and Open Challenges
Interpretable GP models are already used across many domains:
Agriculture, aquaculture, water resources, seafood and ocean industries.
Disease diagnosis, biomarker detection, drug discovery, melanoma detection.
Global temperature change, natural disaster prediction.
Control, robotics, games, cybersecurity, sustainable energy, scheduling.
Education, price-index prediction, council resource management.
XGP is still a young field. The survey highlights open challenges:
- What is interpretability, really? It depends on the reader's expertise, culture and priorities. Proxies like size are convenient, but there is little evidence of how well they match real human understanding, and "small" is not automatically "interpretable". We need more human studies and automatic, user-specific explanations.
- The trade-off is hard to optimise. It is much harder to make a small model accurate than a large one with many parameters, and search easily gets stuck. Post-hoc simplification is limited by the structure the tree already has.
- Many objectives at once. Size, complexity, features and structure can conflict with each other and with accuracy, turning XGP into a difficult many-objective optimisation problem.
12. Check Your Understanding
1. A model separates wolves from huskies almost perfectly, but only by detecting snow. What is this called?
2. You give people a model and an input, and ask them to work out the output. What are you testing?
3. Which approach returns a whole set of models with different size–accuracy trade-offs?
4. Shuffling a subtree's outputs barely changes the model's error. What does phenotypic simplification do?
5. A dimensionally aware GP sees m + v × v (mass plus speed squared). What happens?
6. What does a post-hoc local explanation describe?
Where to Go Next
- Read the survey: Explainable Artificial Intelligence by Genetic Programming: A Survey, with references to all the methods mentioned here.
- Learn GP first: the Genetic Programming tutorial explains trees, crossover, mutation and bloat step by step.
- See it applied: the Job Shop Scheduling tutorial shows the kind of decision rules GP evolves, and my explainable AI research theme lists our papers.
- Try it in code: DEAP (Python) supports multi-objective GP and custom bloat control; pyNSGP and GP-GOMEA focus on small, interpretable symbolic regression models.
How to cite
If this tutorial helps your work, please cite the survey:
@article{mei2023xgp,
author = {Mei, Yi and Chen, Qi and Lensen, Andrew and Xue, Bing and Zhang, Mengjie},
title = {Explainable Artificial Intelligence by Genetic Programming: A Survey},
journal = {IEEE Transactions on Evolutionary Computation},
volume = {27},
number = {3},
pages = {621--641},
year = {2023},
doi = {10.1109/TEVC.2022.3225509}
}