Evolutionary genetics concept photograph.
Photo by Maksim Goncharenok on Pexels

Survival of the fittest… is the central notion behind Darwinian evolutionary theory. Organisms that adapt to their environment are more likely to survive, reproduce, and pass on their advantageous genes to the next generation, thereby increasing the offspring’s chances of survival. Inspired by this are the class of optimization algorithms that are known as Genetic Algorithms. They operate in steps inspired by nature on a population of potential solutions, applying steps like selection, crossover, and mutation to evolve solutions over generations. They are widely used in solving complex optimization problems in various domains where brute-force algorithms would take too long.

For example, let’s consider a monkey typing on a keyboard, and given an infinite amount of time, we want to see if it can spell out LinkedIn. If we consider 1 second for one letter, the brute-force algorithm will take 2⁶⁸ seconds, equivalent to 66174.4717 years. However, a genetic algorithm can drastically reduce this time with a proper fitness function that penalizes and rewards the letter in the correct place. We will see what are the steps involved in the next section with an example.

Pros

Real-world Applications — GAs are used in real-world problems where search space is complex and constraints are non-linear. Applications include ML hyper-parameter tuning and resource allocation, game playing, aircraft design, scheduling, etc

Global Search Capability — Though it has a risk of converging at local optima, with proper parameters, it can explore the entire search space through crossover and mutation.

Intuitive Implementation — Despite various steps in implementation, genetic algorithms are relatively simple and intuitive, requiring a good fitness function and genetic operators. Multiple libraries, such as DEAP, etc, have ready implementation that simplifies the process

Robust — It is robust in the presence of noise and uncertainty in fitness evaluations; since it is population-based, it averages out the errors and minimizes them over generations

Cons

Computationally Intensive — Requires significant computation resources since we calculate fitness for each and every step, especially for those with complex fitness functions.

Premature Convergence — The population might lose diversity in the initial stages and hence might converge prematurely at suboptimal solutions. Also, the solution might stagnate at local optima without exploring better solutions.

Convergence Uncertainty — The genetic algorithm is stochastic in nature; there is no guarantee that it will find a global optimum or even converge at all. The randomly initialized population also determines whether it will converge (or converge at local optimum) or not.

Not for All — While they can handle continuous valued problems as well, they are best suited for discrete-valued or binary search spaces. Also, it is not suitable for well-structured problems where other optimization techniques can perform exponentially better.


Let’s use the famous N-queen problem as an example to simplify the understanding. We will try to solve for 5 Queens. If you are not familiar with it, here is the gist

The problem of placing n chess queens on an n×n chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal

Steps:

1. Chromosome representation

In the field of genetics, an organism’s genotype is its complete set of genetic material that carries its observable traits and characteristics. It is passed down from one generation to the next. In our example, we can represent the chromosome as the row number in which a Queen is present in each column. Similarly, in the case of a monkey spelling out the word LinkedIn, the chromosome would be an 8-letter word with random letters.

Diagram mapping queen positions on a 5x5 board to a 5-element chromosome array.
Chromosome representation of 5-Queens board

2. Fitness function formulation

We need a function to evaluate which chromosome is better and which one is worse so that the better ones can be propagated and not-so-great ones will eventually fade away. This is called the fitness function. We will try to maximize or minimize this function based on how we formulate it. It is best to know the value of optimum beforehand, if possible since we can check for its convergence until then by tuning the parameters. In our example of N-queens, we can represent the fitness function as a number of penalties a Queen has in position w.r.t others on the board.

Diagram showing conflict penalties computed for queens sharing rows or diagonals.

3. Population Initialization

Create a population of N elements, each with a randomly generated chromosome we formulated in step 1. This will give us diverse chromosomes to go over the entire search space rather than getting stuck at a local optimum. In our example, let’s consider N = 4, and its representations would be something like this:

Four randomly initialized 5-Queens boards representing a population of size N = 4.
Population Initialization for N = 4

4. Fitness

Calculate fitness for each individual in the entire population. We will use this fitness score as a weight when deciding which individuals can “mate” to give offspring and which don’t. We can express the fitness scores in a normalized form so as to standardize them to range [0, 1] and then can be expressed as a percentage of the total fitness of the entire population.

Table and chart illustrating raw and normalized fitness scores for the 4 individuals.
Normalized Fitness Scores

Roulette Wheel — Though we have calculated the percentages, we would miss out on the opportunities to explore the search space if we only consider the best half of the population. We should give all the individuals a chance to “mate,” and hence, we can form a Roulette wheel based on the percentages. Here, we spin the wheel N times and consider them to be the new individuals who create the mating pool. Since the Roulette wheel is based on the fitness score percentages, the individuals with more significant scores will have more probability to mate than the ones that have low scores.

Roulette wheel selection chart weighted by each chromosome's fitness probability.
Roulette Wheel of all probabilities

5. Crossover

Now that we have picked our mating pool that forms the parents, we can combine them to produce offspring. This can be done in numerous ways again, but we will stick to single and double split for now. Any split will divide the chromosome into two parts, and the parents participating in the mating would interchange the two parts to form 2 offspring with part parent-1 and part parent-2. This keeps the population still at N, and there is no need to discard any offspring. Not all the matings need to happen at the same split; we can vary the split point randomly and exchange the parts between parents; the more the variation, the better the algorithm will span over the search space.

Single and Double Split Crossover

6. Mutation

True to nature, we need to introduce a small change in the chromosome in order to address the population limit. Since we can’t take all possible chromosomes in the initial population, the initial variation might narrow down over each generation. Mutation introduces additional variable variation that will still be present even after crossover. It is described as a number known as the Mutation Rate and is the chance that a chromosome has at mutating.

Diagram illustrating a 20% random gene mutation on a 5-element chromosome.
20% mutation of our chromosome

As it is evident, a high mutation rate would negate the crossover process and leaves us with random chromosomes without any convergence. Hence, it is usually between 1–5%.

7. Repeat

At this point, the new generation of offspring will become the current population, and the entire process repeats from step 4, evaluating the fitness and selecting the fittest parents for crossover and mutation. As the number of generations progresses, we will clearly see the algorithm being improved (as in converge) or flattening at a number. With enough tuning, we will be able to obtain the global optima we are looking for.

Let’s take a look at another example, very similar to the N-queen puzzle, with a slightly modified constraint and solve using python.

LinkedIn Queens Game

LinkedIn’s Queens Game is a twist on the classic N-queen problem. It adds a new color constraint of 1 Queen per color region and eases the diagonal constraint. For those of you who haven’t played or are unfamiliar with LinkedIn’s Queens game:

Goal: Place exactly one Q in each row, column, and color region.

Rule: Two Qs cannot touch each other — horizontally, vertically or diagonally

LinkedIn Queens Sample

This change in constraint will also change our fitness function. We can penalize if Queens are occurring horizontally, vertically, diagonally or in same color. We can write the fitness functions as:

  1. Maximize: No of conflicting Queens + sum(1 — No of Queens in the color)
  2. Minimize: No of conflicting Queens + No of Queens in same color

We will choose the 2nd function as it is simpler and we already know its value when minimized should always be 0. So we know the convergence criteria and can tune the parameters for it to occur.

The other functions chromosome representation, population initialization, crossover and mutation will remain same. Here is the final code

import random

# Constants for the Genetic Algorithm (GA)
POPULATION_SIZE = 100  # Number of individuals in the population
NUM_GENERATIONS = 500  # Number of generations to evolve
MUTATION_RATE = 0.1    # Probability of mutation for an individual

# Grid representing the problem's constraints (colors)
grid = [
    [1, 2, 2, 2, 2],
    [3, 4, 3, 2, 3],
    [3, 4, 3, 3, 3],
    [3, 3, 3, 5, 5],
    [3, 3, 3, 3, 3],
]

# Set of unique colors in the grid
colors = {1, 2, 3, 4, 5}


# Fitness function to evaluate the quality of a solution
def fitness(solution):
    """
    Calculate the fitness score of a solution.
    Lower fitness scores are better.
    Penalties are incurred for:
    - Column conflicts (two rows with the same column index).
    - Color conflicts (two rows with the same color value).
    - Proximity conflicts (adjacent cells row-wise, column-wise, or diagonally).
    """
    penalties = 0

    # Check for column conflicts
    columns = set()
    for row, col in enumerate(solution):
        if col in columns:
            penalties += 1
        columns.add(col)

    # Check for color conflicts
    color_set = set()
    for row, col in enumerate(solution):
        color = grid[row][col]
        if color in color_set:
            penalties += 1
        color_set.add(color)

    # Check for proximity conflicts
    for i, (row1, col1) in enumerate(enumerate(solution)):
        for row2, col2 in enumerate(solution):
            if i == row2:
                continue
            if abs(row1 - row2) <= 1 and abs(col1 - col2) <= 1:
                penalties += 1  # Conflict if cells are adjacent

    return penalties


# Function to generate the initial population
def generate_population(size):
    """
    Generate a population of random individuals.
    Each individual is a list where the index represents the row, and the value represents the column.
    """
    population = []
    for _ in range(size):
        individual = [random.randint(0, len(grid[0]) - 1) for _ in range(len(grid))]
        population.append(individual)
    return population


# Function to perform crossover between two parents
def crossover(parent1, parent2):
    """
    Perform single-point crossover to generate two children.
    """
    point = random.randint(1, len(parent1) - 2)  # Select a random crossover point
    child1 = parent1[:point] + parent2[point:]  # First child combines parent1 and parent2
    child2 = parent2[:point] + parent1[point:]  # Second child combines parent2 and parent1
    return child1, child2


# Function to mutate an individual
def mutate(individual):
    """
    Mutate an individual with a probability defined by MUTATION_RATE.
    Mutation changes the column index of a random row.
    """
    if random.random() < MUTATION_RATE:
        row = random.randint(0, len(individual) - 1)  # Choose a random row
        individual[row] = random.randint(0, len(grid[0]) - 1)  # Assign a new random column


# Genetic Algorithm main function
def genetic_algorithm():
    """
    Run the Genetic Algorithm to find the best solution.
    """
    # Initialize the population
    population = generate_population(POPULATION_SIZE)
    best_solution = None
    best_fitness = float('inf')  # Initialize with a very high fitness score

    # Iterate through generations
    for generation in range(NUM_GENERATIONS):
        # Evaluate fitness for each individual
        fitness_scores = [fitness(individual) for individual in population]

        # Update the best solution if a better one is found
        best_idx = fitness_scores.index(min(fitness_scores))
        if fitness_scores[best_idx] < best_fitness:
            best_fitness = fitness_scores[best_idx]
            best_solution = population[best_idx]

        # Exit early if a perfect solution is found
        if best_fitness == 0:
            break

        # Selection: Weighted random sampling based on fitness (lower fitness is better)
        selected = random.choices(population, weights=[1 / f for f in fitness_scores], k=POPULATION_SIZE)

        # Crossover: Generate the next generation
        next_generation = []
        for i in range(0, POPULATION_SIZE, 2):
            parent1, parent2 = selected[i], selected[i + 1]
            child1, child2 = crossover(parent1, parent2)
            next_generation.extend([child1, child2])

        # Mutation: Mutate individuals in the next generation
        for individual in next_generation:
            mutate(individual)

        # Replace the old population with the new one
        population = next_generation

    return best_solution, best_fitness


# Run the Genetic Algorithm and print the results
solution, fitness_score = genetic_algorithm()

print("Best solution:", solution)
print("Fitness score:", fitness_score)

For the example in the code when converged it produces the output:

Best solution: [0, 3, 1, 4, 2]
Fitness score: 0

Which is our desired fitness score and the correct solution.

Improvements

Genetic Algorithm doesn’t always converge and might get stuck at local optima. This can be evidently seen in our example where the fitness is not equal to zero in some runs.

Best solution: [2, 4, 1, 3, 0]
Fitness score: 1

Best solution: [3, 1, 4, 2, 0]
Fitness score: 2

We can improve the convergence using various techniques:

Adjust Fitness Function — Reiterate over the fitness function to avoid cases where different solutions yield same fitness score, introduce better penalty/reward structure to ensure it aligns well with the desired solution

Increase Population Diversity

Hybridize with Other Methods — Using local search algorithms such as Hill Climbing or Simulated Annealing to fine tune better performing solutions after crossover and mutation

Parameter Tuning — adjust mutation rate, crossover rate, selection threshold. Start with higher mutation rates to explore the search space and decrease them as convergence nears to better solutions

Parallelization — Though not recommended, we can run multiple Genetic Algorithm instances in parallel with varied initial populations and parameters to explore all the regions of search space

Elitism — Retain the best solutions in every generation while ensuring these elite solutions do not dominate entirely

Conclusion

In the article, we’ve seen what Genetic Algorithms are and how they are inspired by evolutionary theories. Though they don’t actually represent biological processes, they are taken as abstract concepts and used as guiding principles for designing systematic approaches to solving complex optimization problems. While they have their own challenges, with proper parameter tuning and population sizes, they can be addressed, and desired convergence can be achieved.


🚀 Explore the code on GitHub and show your support with a ⭐ if you find it helpful! 🙌✨

All images are by the author unless stated otherwise.