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.

Based on our survey. This tutorial follows the structure of Y. Mei, Q. Chen, A. Lensen, B. Xue and M. Zhang, "Explainable Artificial Intelligence by Genetic Programming: A Survey", IEEE Transactions on Evolutionary Computation, 27(3):621–641, 2023, which reviews more than 200 studies. Diagrams marked "adapted from the survey" are simplified redrawings of its figures. How to cite.
~45 minreading and playing time
9interactive demos
Pythoncode for every demo, ready to copy and run
Beginnerno XAI or GP background needed

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:

Catch "Clever Hans" models

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.

Trust and fairness

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.

The law

Regulations such as the EU's General Data Protection Regulation (GDPR) give people a right to meaningful information about automated decisions.

New knowledge

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.

Demo 1 · Spot the Clever Hans

Training photos (snowy background = blue tint, grass = green tint):

Pick a new photo to classify:

Try this: classify the husky in the snow. Both models get it wrong, but only the readable model shows you why. Then press the button to add a few counter-example photos, and watch the readable rule switch to a sensible feature.

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:

1SimulatabilityCan a person work through the whole model in their head, like following a recipe?
2DecomposabilityDoes each part of the model (each input, each piece) have an understandable meaning?
3Algorithmic transparencyDo we understand the process that goes from any input to the final output?

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.

Demo 2 · Be the model: a forward simulation test

ModelComplexityCorrectAverage time
Try this: answer one question with each model (a calculator is allowed!). The small GP model takes seconds. The bloated GP model computes exactly the same function, yet is slower to follow: size matters. The neural network needs 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.

explainability → accuracy → deep neural nets ensembles SVMs decision trees linear GP's goal:accurate & readable
Notional trade-off, adapted from the survey (after Gunning and Aha).

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:

Data Train a model(predictive accuracy) Trained model Explain it afterwards(descriptive accuracy) Intrinsic: make the model itself readable Post-hoc: a second, simpler model explains the first one
Where interpretability enters the machine learning process, adapted from the survey (after Murdoch et al.).
  • 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:

  1. Evaluate each program with a fitness function (for example, its error on the data).
  2. Select good programs as parents (for example, by a tournament: pick a few at random, keep the best).
  3. Vary them: crossover swaps subtrees between two parents, mutation replaces a subtree with a random one.
  4. Replace the old population with the children, and repeat for many generations.

New to GP? The Genetic Programming tutorial lets you watch every step.

× x + x 1
A GP tree: functions (filled) and terminals (light).

The survey highlights three reasons why GP is a natural fit for XAI:

Readable by design

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.

A population of trade-offs

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.

No gradients needed

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:

XAI by GP (XGP) Intrinsic (87% of studies) Post-hoc Visualisation §4 Smaller model size §5 Lower (non-size) complexity §6 Fewer distinct features §7 Interpretable structures §8 Learned interpretability measures §9 Global: explain all inputs §9 Local: explain one input §10 Visualisation by GP §10 Visualisation for GP
Taxonomy of explainable AI by GP, adapted from the survey. Click a box to jump to its section.

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:

Initialisation Evaluation Parent selection Making offspring Survivorselection Depth / size limit Parsimony pressure Anti-bloat operators Size distribution control Explicit simplification an extra step, anywhere in the loop or after it
Strategies to reduce GP model size, and the stages where they act. Adapted from the survey.
  • 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), where f is the error and s the size. A death penalty gives oversized programs the worst fitness; a linear penalty uses p(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.

Demo 3 · Bloat control strategies, side by side

Generation – · average size – · programs on the front –

Last population: error vs size. Big dots form the Pareto front (no other program is both smaller and more accurate).
Average program size (one line per run)
Best error (RMSE)
Try this:
  • 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 → 0 and x ÷ x → 1, or domain rules such as max(x, x − y) → x when y is 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.
Demo 4 · Simplify a bloated program, step by step

Size nodes · error on the data

Program:

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, cos and exp more 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.
Demo 5 · Which model is simplest? It depends on the measure

Click a column header to rank the models by that measure, and a row to see the model.

Output of the selected model for x from −3 to 3
Try this: models A and B have the same size (7) but different depths and visitation lengths: the lopsided tree B counts as more complex. Rank by size: E (5 nodes) looks simpler than A, B and F. Now rank by slope changes or nested non-arithmetic operations: E becomes by far the hardest, because 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.

Demo 6 · Feature selection and construction by GP

A. Feature ranking. How often each feature appears in the best model of a GP run (relevant features in orange).

Runs so far: 0

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.

    Try this: run GP a few times. The bars for x2, x5 and x7 shoot up while the others stay low: GP has selected the relevant features. Then build 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.

    Sub → class Std (spread) Mean (brightness) Gaussian filter Region(x, y, w, h) Region(x, y, w, h) image
    Typed image-processing nodes: region detection, feature extraction and construction (inspired by the survey's examples).

    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 + b and a − b need the same unit, and keep it;
    • a × b adds exponents; a ÷ b subtracts them.

    Programs that break the rules are penalised. This has rediscovered conservation laws and Feynman equations, and produced readable scheduling rules.

    Demo 7 · Check the units of candidate energy formulas

    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.

    Demo 8 · Teach the computer your own interpretability measure

    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:

        Try this: answer about 15 questions, then ask a friend to do the same after pressing Forget my answers. Your weights will probably differ: one person hates long formulas, another hates 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.
        Demo 9 · Explain a black box, globally and locally

        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).

        Try this: click near the centre of the black box map, then near one of its corners: the local explanation says 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.
        axis 1 = x₂ + x₅ − x₇ axis 2 = x₁ × x₃
        Illustration: a scatter plot whose axes are readable GP formulas.

        11. Applications and Open Challenges

        Interpretable GP models are already used across many domains:

        Primary industries

        Agriculture, aquaculture, water resources, seafood and ocean industries.

        Health and medicine

        Disease diagnosis, biomarker detection, drug discovery, melanoma detection.

        Environment and climate

        Global temperature change, natural disaster prediction.

        High-tech industry

        Control, robotics, games, cybersecurity, sustainable energy, scheduling.

        Society and economy

        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

        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}
        }