Articles / AI · Part 24

Genetic Algorithms in Artificial Intelligence

Discover how Genetic Algorithms use ideas from natural evolution to solve complex optimisation problems. Learn about populations, fitness functions, selection, crossover, mutation, and their Python implementation.

Genetic Algorithms in Artificial Intelligence

Imagine you are trying to design the most efficient aircraft wing. There are thousands of possible designs, and testing every single one would take an enormous amount of time.

Instead of checking every possibility, what if you started with several designs, selected the better ones, combined their features, and introduced small changes to create new designs?

Then you repeated the process, allowing each generation to produce potentially better solutions.

This idea is inspired by natural evolution. In Artificial Intelligence, it is known as a Genetic Algorithm.

Genetic Algorithms are optimisation techniques that use ideas from biological evolution, such as selection, crossover, and mutation, to search for good solutions to complex problems.

1. What Is a Genetic Algorithm?

A Genetic Algorithm (GA) is a population-based optimisation algorithm inspired by the process of natural selection.

It begins with a group of candidate solutions, evaluates their quality, and produces new candidates by combining and modifying existing ones.

Over multiple generations, the population can gradually improve.

The main idea is simple:

  • Create a population of possible solutions.
  • Evaluate how good each solution is.
  • Select better solutions as parents.
  • Combine their information through crossover.
  • Introduce small random changes through mutation.
  • Repeat the process.

Unlike Hill Climbing, which usually improves one current solution at a time, a Genetic Algorithm works with a population of candidate solutions.

2. Understanding the Biological Inspiration

Genetic Algorithms borrow several concepts from natural evolution.

Biological concept Genetic Algorithm equivalent
Individual organism Candidate solution
Population Group of candidate solutions
Chromosome Encoded representation of a solution
Gene A part of a chromosome
Fitness Quality of a candidate solution
Natural selection Selection of better candidates
Reproduction Producing new candidate solutions
Mutation Randomly changing part of a solution

In nature, organisms with traits that help them survive and reproduce may pass those traits to future generations.

In a Genetic Algorithm, better-performing candidate solutions are more likely to contribute to the next generation.

The algorithm does not reproduce biological organisms. It applies these ideas mathematically to solve optimisation problems.

3. How Does a Genetic Algorithm Work?

A Genetic Algorithm generally follows a repeated cycle.

Step 1: Initial Population

The algorithm starts by creating a population of candidate solutions.

These solutions may be generated randomly or using a suitable initialisation method.

For example, if the problem is to find the best combination of products within a budget, each candidate solution could represent a different combination.

Step 2: Fitness Evaluation

Each candidate solution is evaluated using a fitness function.

The fitness function measures how well a solution performs according to the problem’s objective.

For example, in a route optimisation problem, fitness could be based on the total distance travelled. A shorter route would be better.

The fitness function determines which candidates are more desirable.

Step 3: Selection

The algorithm selects candidate solutions to act as parents for the next generation.

Better solutions generally have a higher chance of being selected.

Some common selection methods include:

  • Roulette Wheel Selection: Selection probability depends on relative fitness.
  • Tournament Selection: A small group of candidates is compared, and a better one is selected.
  • Rank Selection: Candidates are ranked, and selection depends on their rank rather than their raw fitness.

Selection allows useful characteristics of good solutions to be carried forward.

Step 4: Crossover

Crossover combines parts of two parent solutions to create new solutions, called offspring.

For example, consider two binary chromosomes:

Parent 1: 110|010

Parent 2: 001|111

If the crossover point is after the third bit, the offspring could be:

Offspring 1: 110111

Offspring 2: 001010

The offspring inherit parts of their parents’ chromosomes.

Step 5: Mutation

Mutation introduces small random changes into a chromosome.

For example:

Before mutation: 110111

After mutation: 110101

A bit has changed from 1 to 0.

Mutation helps maintain diversity in the population and can introduce new characteristics that were not present in the selected parents.

Step 6: Replacement and New Generation

The offspring become part of the next population.

Some algorithms replace the entire previous population, while others preserve selected strong candidates through a technique called elitism.

Elitism ensures that a few of the best solutions are carried forward unchanged.

The algorithm then evaluates the new population and repeats the process.

4. The Genetic Algorithm Cycle

The overall process can be represented as:

Initial Population → Fitness Evaluation → Selection → Crossover → Mutation → New Population

The cycle continues until a stopping condition is reached.

Common stopping conditions include:

  • Reaching a maximum number of generations.
  • Finding a solution with satisfactory fitness.
  • No meaningful improvement over several generations.
  • Reaching a time or computational limit.

The algorithm then returns the best solution it found.

5. A Simple Example

Suppose we want to find a six-bit binary number containing as many 1s as possible.

Our fitness function simply counts the number of ones.

For example:

Chromosome Fitness
000101 2
110010 3
111001 4
111111 6

The best possible solution is 111111, with a fitness value of 6.

A Genetic Algorithm might begin with a random population containing different binary strings.

It evaluates their fitness, selects better candidates, combines them through crossover, and applies mutation.

After several generations, the population may contain increasingly better solutions.

This simple example demonstrates the central idea: repeatedly producing and evaluating new candidate solutions can help the algorithm discover a good answer.

6. Python Implementation

Let’s implement a small Genetic Algorithm to find a six-bit chromosome containing only ones.

import random

CHROMOSOME_LENGTH = 6
POPULATION_SIZE = 6
GENERATIONS = 30
MUTATION_RATE = 0.1


def create_chromosome():
    return [
        random.randint(0, 1)
        for _ in range(CHROMOSOME_LENGTH)
    ]


def fitness(chromosome):
    return sum(chromosome)


def selection(population):
    candidates = random.sample(population, 3)
    return max(candidates, key=fitness)


def crossover(parent1, parent2):
    point = random.randint(1, CHROMOSOME_LENGTH - 1)

    child = (
        parent1[:point] +
        parent2[point:]
    )

    return child


def mutate(chromosome):
    chromosome = chromosome.copy()

    for i in range(len(chromosome)):
        if random.random() < MUTATION_RATE:
            chromosome[i] = 1 - chromosome[i]

    return chromosome


population = [
    create_chromosome()
    for _ in range(POPULATION_SIZE)
]

for generation in range(GENERATIONS):

    new_population = []

    best = max(population, key=fitness)

    # Preserve the best solution
    new_population.append(best.copy())

    while len(new_population) < POPULATION_SIZE:
        parent1 = selection(population)
        parent2 = selection(population)

        child = crossover(parent1, parent2)
        child = mutate(child)

        new_population.append(child)

    population = new_population

    best = max(population, key=fitness)

    print(
        f"Generation {generation + 1}: "
        f"{best}, Fitness: {fitness(best)}"
    )

    if fitness(best) == CHROMOSOME_LENGTH:
        break

The program creates a random population of binary chromosomes.

It evaluates each chromosome, selects parents, performs crossover, and applies mutation. It also preserves the best solution from each generation using elitism.

Because mutation and selection involve randomness, different runs may produce different results. For this small problem, the algorithm may discover 111111 within a relatively small number of generations.

7. Advantages of Genetic Algorithms

Genetic Algorithms are useful for problems where searching for the best solution directly is difficult.

Some important advantages include:

Population-Based Search: They explore multiple candidate solutions at the same time instead of depending on only one current solution.

Large Search Spaces: They can be useful when the number of possible solutions is extremely large.

Flexibility: They can be adapted to different optimisation problems by designing suitable representations and fitness functions.

No Gradient Required: They do not require the objective function to be differentiable.

Potential to Escape Local Optima: Crossover and mutation can introduce diversity and help the search explore different regions of the solution space.

8. Limitations of Genetic Algorithms

Despite their advantages, Genetic Algorithms also have limitations.

Computational Cost: Evaluating a large population over many generations can require considerable time and resources.

Parameter Selection: Population size, mutation rate, crossover rate, and selection strategy can influence performance. Choosing suitable values may require experimentation.

Premature Convergence: The population may become too similar too early, reducing diversity and limiting further exploration.

No Guarantee of Global Optimum: A Genetic Algorithm may find a good solution without finding the best possible solution.

Fitness Function Design: A poorly designed fitness function may guide the algorithm towards solutions that do not meet the real objective.

Genetic Algorithms are therefore useful optimisation tools, but their effectiveness depends on the problem and how the algorithm is designed.

9. Applications of Genetic Algorithms

Genetic Algorithms have been applied to several areas of science, engineering, and Artificial Intelligence.

  • Engineering Design: Searching for efficient structures, components, and designs.
  • Scheduling: Optimising timetables, employee shifts, and production schedules.
  • Route Optimisation: Searching for efficient routes and travel arrangements.
  • Machine Learning: Selecting features, tuning parameters, and optimising certain model configurations.
  • Robotics: Optimising movement strategies and control parameters.
  • Resource Allocation: Finding effective ways to distribute limited resources.

They are especially useful when a problem has many possible combinations and traditional optimisation methods are difficult to apply.

10. Genetic Algorithms vs Hill Climbing

Both algorithms are used for optimisation, but they approach problems differently.

Hill Climbing Genetic Algorithms
Usually works with one current solution Works with a population of solutions
Moves towards a better neighbour Produces new solutions through reproduction
Can get stuck at local maxima Uses diversity to explore different regions
Usually requires little memory Requires memory for a population
Often simpler to implement Has more parameters and operations

Hill Climbing focuses on improving a current solution. Genetic Algorithms explore a group of solutions and use selection, crossover, and mutation to generate new candidates.

Neither approach guarantees the global optimum.

Conclusion

Genetic Algorithms show how ideas inspired by nature can help solve complex computational problems.

By maintaining a population of candidate solutions and repeatedly applying selection, crossover, and mutation, they can search through large solution spaces and discover useful results.

Their strength lies in exploring multiple possibilities, while their limitations remind us that a good optimisation algorithm still depends on careful design, suitable parameters, and a meaningful fitness function.

The next article moves from optimisation to another important area of Artificial Intelligence: Game Playing in Artificial Intelligence, where machines make decisions in competitive environments.

Quick quiz

5 questions
What inspires Genetic Algorithms?
What does a fitness function do?
What is crossover?
Why is mutation used?
What is premature convergence?

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

AI · Part 32

Conflict Resolution in Expert Systems

Learn how conflict resolution works in expert systems and why multiple applicable rules require a selection strategy. Explore rule priority, specificity, recency,…

9 min read
AI · Part 17

Heuristic Search and Informed Search Strategies

Discover how informed search uses heuristic knowledge to guide AI problem-solving. Learn about heuristic functions, how informed search differs from uninformed search,…

6 min read

Ask Farhan

Ask anything about Farhan