An Introductory Guide To Genetic Algorithms In Python

What are Genetic Algorithms?

Genetic Algorithms (GAs) are a part of evolutionary computing, which is a rapidly growing area of artificial intelligence. They are inspired by Darwin's theory of evolution—survival of the fittest. GAs simulate the selection, crossover, and mutation events happening in nature to find the optimal solution to complex problems.

How do Genetic Algorithms work?

GAs start with a population of candidate solutions represented by chromosomes, also called individuals. Each chromosome is evaluated to measure the fitness or ability of an individual to solve the problem. The fittest individuals are selected for reproduction—crossover and mutation. This process is repeated for various generations until the optimum solution is found or the set number of generations is completed.

Let's understand GAs practically by writing a Python program to find the maximum value of a given function.

For this tutorial, we will use the DEAP package. DEAP, or Distributed Evolutionary Algorithms in Python, is a powerful library for writing custom GAs.

# Importing required libraries from deap import base, creator, tools import random

Defining the Fitness Criteria and Individuals

# Fitness criteria: maximum problem creator.create("FitnessMax", base.Fitness, weights=(1.0,)) # Individual: list of floats creator.create("Individual", list, fitness=creator.FitnessMax)

Defining the Population

toolbox = base.Toolbox() toolbox.register("attr_float", random.random) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=10) toolbox.register("population", tools.initRepeat, list, toolbox.individual)

Defining the Evolutionary Operators

# Evaluation function: summing all the values in the individual def eval_func(individual): return sum(individual), # Registering genetic operators to the toolbox toolbox.register("evaluate", eval_func) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutGaussian, mu=0, sd=0.2, indpb=0.2) toolbox.register("select", tools.selTournament, tournsize=3)

Defining the Genetic Algorithm

def main(): pop = toolbox.population(n=50) hof = tools.HallOfFame(1) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", numpy.mean) stats.register("std", numpy.std) stats.register("min", numpy.min) stats.register("max", numpy.max) pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40, stats=stats, halloffame=hof, verbose=True) return pop, logbook, hof pop, log, hof = main()

You just wrote a simple Genetic Algorithm using the powerful DEAP library. You can modify various parameters like mutation rate, crossover rate, population size, and number of generations to optimize the solution based on your problem.