Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Pattern classification with genetic algorithms

How genetic algorithms (GAs) can be used to search for classifiers: encoding classifiers as chromosomes, fitness design, GA operators, schema theorem, and example code for a simple GA classifier.

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 algorithms (GAs) are population-based global search methods useful when the classifier design space is large, non-convex or discontinuous (for example, selecting feature subsets, tuning non-differentiable classifier parameters, or finding weights for non-linear discriminants). Engineers use GAs in pattern classification when classical gradient-based training (e.g. for discriminant functions) fails, or when combined with feature selection to improve generalisation and reduce sensor/feature cost.

Key ideas

Start with clear definitions.

  • Genetic algorithm (GA) — a population-based stochastic search algorithm inspired by biological evolution. A GA maintains a population of candidate solutions (called individuals or chromosomes), evaluates them by a fitness function, and applies selection, crossover and mutation to create new populations.
  • Chromosome — an encoded representation of a candidate classifier. For example, the chromosome may be a real-valued vector of discriminant weights, or a binary string indicating selected features.
  • Fitness function — a scalar measure of how good a chromosome is for the classification task (for example, classification accuracy on a validation set, or a regularised error combining accuracy and number of features).
  • Selection — operator that chooses individuals for reproduction in proportion to fitness (examples: roulette-wheel selection, tournament selection). Selection increases the proportion of better solutions.
  • Crossover (recombination) — operator that combines genetic material of two parents to produce offspring (examples: one-point crossover for binary strings, arithmetic crossover for real vectors).
  • Mutation — operator that introduces small random changes to individuals to maintain diversity (bit-flip for binary strings, Gaussian perturbation for real values).
  • Elitism — strategy to copy the best individual(s) unchanged into the next generation to preserve best solutions found.

Exact statements and assumptions universities ask for:

  1. Encoding: If a classifier is a linear discriminant f(x) = sign(w0 + w^T x), then a straightforward encoding is a chromosome c = [w0, w1, …, wd] where each gene is a real number. Assume features are scaled to similar ranges to avoid bias in evolution. Define sign(0) = +1 (equivalently, classify as +1 when the score ≥ 0) to make the threshold convention explicit.

  2. Fitness design: For classification with labels y_i in {+1, -1}, a common fitness is classification accuracy on a validation set: fitness(c) = (1/N) sum_{i=1..N} I(sign(score_c(x_i)) == y_i). If one must penalise complexity (e.g. feature count k), use fitness = accuracy - λ·(k/d) where λ is a small positive constant. For imbalanced classes, prefer balanced accuracy, F1, or cost-sensitive fitness instead of raw accuracy, and estimate fitness with k-fold cross-validation to reduce variance and overfitting.

  3. Roulette-wheel selection (exact statement): If population P has individuals i with non-negative fitness f_i, the probability of selecting individual i is p_i = f_i / sum_j f_j. Assumes all f_i ≥ 0 and not all zero.

  4. Holland's schema theorem (exact statement used commonly in exams): Let H be a schema (a template over gene positions). Let m(H, t) be the number of individuals in generation t matching H. Let f(H) be average fitness of individuals matching H and f̄ be average fitness of population. Let o(H) = order(H) be the number of fixed positions in H, δ(H) = defining length = distance between outermost fixed positions, l = chromosome length, pc = crossover probability, pm = per-bit (or per-gene) mutation probability. Then (approximate) expected number of copies of H in next generation satisfies

E[m(H, t+1)] ≥ m(H, t) * (f(H) / f̄) * [1 - pc * (δ(H) / (l - 1)) - pm * o(H)].

Assumptions: single-point crossover; mutation is independent per gene; selection is proportional to fitness and produces expected m(H,t)*(f(H)/f̄) copies before disruption factors.

Derivation sketch universities expect (step by step):

  1. After selection (but before crossover/mutation), expected copies from selection = m(H,t) * (f(H)/f̄).
  2. Probability that a schema H is disrupted by single-point crossover ≈ pc * (δ(H)/(l-1)) because there are (l-1) cut points and δ(H) of them lie between fixed positions.
  3. Probability that H survives mutation ≈ (1 - pm)^{o(H)} ≈ 1 - pm*o(H) for small pm.
  4. Combine: E[m(H,t+1)] ≈ m(H,t)(f(H)/f̄)(1 - pc*(δ(H)/(l-1)))(1 - pmo(H)) and approximate to the inequality above.

What to draw in an exam diagram:

  • To show crossover disruption: draw a chromosome as a line of l gene boxes, mark the schema fixed positions with shading or bold, show possible single-point crossover cut positions, label δ(H) as the index distance between the leftmost and rightmost fixed positions (number of cut points between them; δ(H) = j - i if fixed at positions i and j). Label l and show how many cuts disrupt schema.

Practical design advice (engineers use): scale features, choose representation matched to problem (binary for subset selection, real-coded for weights), use elitism, use small mutation rate to preserve search but maintain diversity, use fitness that balances accuracy and complexity to avoid overfitting.

Formulas

p_i = f_i / sum_j f_j — p_i is selection probability of individual i; f_i is fitness (unitless); applies for roulette-wheel selection when f_i ≥ 0.

fitness = (1/N) sum_{i=1..N} I(sign(score(x_i)) == y_i) — fitness is classification accuracy; N is number of validation samples; I is indicator (1 if true, 0 otherwise); unitless; applies when using accuracy as fitness.

score(x) = w0 + w^T x — linear discriminant score; w0 bias (unit: same as score), w vector same units as x scaled appropriately; applies for linear discriminant classifiers.

E[m(H,t+1)] ≥ m(H,t) * (f(H)/f̄) * [1 - pc * (δ(H)/(l-1)) - pm * o(H)] — schema theorem (approximate); m counts, f average fitness, pc crossover prob (unitless, 0..1), pm mutation prob (unitless). A tighter bound is E[m(H,t+1)] ≥ m(H,t) * (f(H)/f̄) * (1 - pc * (δ(H)/(l-1))) * (1 - pm)^{o(H)} under the same assumptions.

mutation: gene' = gene + N(0, σ^2) — Gaussian mutation for real gene; σ is standard deviation (same units as gene).

Worked examples

Example 1 — Python program: toy GA to find weights for a 2D linear classifier. With np.random.seed(0) and pm = 0 (no mutation), the run is deterministic; the small discrete search space simply makes enumeration feasible.

The optimal solution is present in the initial population because it enumerates all combinations of genes in {-1, 0, 1}. Elitism ensures best solution survives.

Program (save as ga_classifier.py):

import numpy as np
np.random.seed(0)

# Training data: two linearly separable classes
X = np.array([[2,2],[3,3],[2,3],[-2,-1],[-3,-2],[-2,-3]])
y = np.array([1,1,1,-1,-1,-1])

# Evaluate a chromosome c = [b, w1, w2]
def eval_chrom(c):
    scores = c[0] + X.dot(c[1:])
    preds = np.where(scores >= 0, 1, -1)
    return np.mean(preds == y)  # accuracy

# Create initial population: all combos of genes in {-1,0,1}
vals = [-1, 0, 1]
pop = [np.array([b,w1,w2], dtype=float) for b in vals for w1 in vals for w2 in vals]

# GA params
pop_size = len(pop)
generations = 5
pc = 0.7
pm = 0.0  # no mutation for determinism
elitism_k = 1

# Fitness evaluation
fitness = np.array([eval_chrom(c) for c in pop])

for gen in range(generations):
    # Elitism copy
    elite_idx = np.argmax(fitness)
    new_pop = [pop[elite_idx].copy()]

    # Roulette-wheel selection probabilities
    total = np.sum(fitness)
    probs = fitness / total if total > 0 else np.ones(pop_size)/pop_size

    # Fill new population using one-point crossover on discrete genes
    while len(new_pop) < pop_size:
        # select parents
        i, j = np.random.choice(pop_size, size=2, p=probs)
        p1, p2 = pop[i], pop[j]
        if np.random.rand() < pc:
            # one-point crossover on 3 genes: choose cut after gene 0 or 1
            cut = np.random.choice([1,2])
            child = np.concatenate([p1[:cut], p2[cut:]])
        else:
            child = p1.copy()
        # no mutation (pm=0)
        new_pop.append(child)
    pop = new_pop
    fitness = np.array([eval_chrom(c) for c in pop])

best_idx = np.argmax(fitness)
best = pop[best_idx]
print('Best chromosome:', best.tolist())
print('Best accuracy:', float(fitness[best_idx]))

Sample input: none (program uses internal data). Exact output (deterministic):

Best chromosome: [-1.0, 0.0, 1.0] Best accuracy: 1.0

Explanation: the chromosome [-1,0,1] yields score = -1 + x2, which perfectly separates the two classes in this toy set (all positives have x2 ≥ 2 and all negatives have x2 ≤ -1), so accuracy 100%.

Example 2 — Theory/derivation question (model exam answer): Question: Show how the schema theorem explains why short, low-order schemata with above-average fitness grow exponentially in a GA.

Model answer (concise, exam style):

  1. Define schema H as a template over l positions with o(H) fixed genes and defining length δ(H).
  2. Number of copies at generation t is m(H,t). After selection, expected copies = m(H,t) * (f(H)/f̄) because selection samples proportionally to fitness.
  3. The probability schema survives single-point crossover is 1 - pc*(δ(H)/(l-1)); survives mutation approximately 1 - pm*o(H).
  4. Multiply these survival probabilities with selection result to get E[m(H,t+1)] ≈ m(H,t)(f(H)/f̄)(1 - pc*(δ(H)/(l-1)))(1 - pmo(H)).
  5. For short (small δ) and low-order (small o), the disruption terms are small; if f(H) > f̄, the multiplicative factor > 1 so m(H,t) tends to increase roughly exponentially with generations. Hence GA implicitly combines building blocks (good short schemata) into better solutions.

Common mistakes

  • Forgetting to normalise or scale features before evolving weights: different scales bias the search.
  • Mis-stating schema theorem: leaving out δ(H) or o(H), or treating the inequality as exact equality.
  • Using very high mutation rates that turn the GA into a random search; exam students sometimes pick pm = 0.5 incorrectly for real encoding.

For your exam

  • Short notes: explain representations for classifiers (binary for feature subset, real-valued for weights) and pros/cons of each.
  • Derivations: derive the schema theorem steps (selection expectation, crossover disruption probability, mutation survival approximation) and explain assumptions.
  • Numericals/programs: implement a toy GA or trace one generation of a GA for a small population; show fitness calculations and new population after selection/crossover/mutation.
  • Diagrams: draw a chromosome and indicate crossover cut positions and the defining length δ(H).

Full-marks answers include clear definitions, assumptions stated (e.g. single-point crossover, pm small), stepwise derivation, and a final boxed formula.

Quick check

  1. What is a chromosome in a GA?
  2. Give the roulette-wheel selection probability formula.
  3. In the schema theorem, what two schema properties increase the chance of survival (i.e., reduce disruption)?

Answers: 1. A chromosome is an encoded candidate solution (vector of genes) used by the GA. 2. p_i = f_i / sum_j f_j. 3. Small defining length δ(H) and small order o(H) (short and low-order schemata).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?