- ✕This summary was generated using AI based on multiple online sources. To view the original source information, use the "Learn more" links.
A genetic algorithm (GA) is a search heuristic inspired by natural selection. Below is an implementation of a GA in Python to evolve a binary string where all bits are set to 1.
Steps to Implement the Genetic Algorithm
Initialize Population: Create a random population of binary strings.
Fitness Function: Evaluate how close each individual is to the target (all ones).
Selection: Choose the fittest individuals for reproduction.
Crossover: Combine parents to produce offspring.
Mutation: Introduce random changes to maintain diversity.
Repeat: Iterate until the target is achieved or a maximum number of generations is reached.
Python Implementation
import random# ParametersPOPULATION_SIZE = 20CHROMOSOME_LENGTH = 10MUTATION_RATE = 0.1GENERATIONS = 100# Generate initial populationdef initialize_population():return [[random.randint(0, 1) for _ in range(CHROMOSOME_LENGTH)] for _ in range(POPULATION_SIZE)]# Fitness function: Count the number of onesdef fitness(individual):return sum(individual)# Selection: Roulette Wheel Selectiondef select(population, fitnesses):total_fitness = sum(fitnesses)probabilities = [f / total_fitness for f in fitnesses]return population[random.choices(range(len(population)), probabilities)[0]]# Crossover: Single-point crossoverdef crossover(parent1, parent2):point = random.randint(1, CHROMOSOME_LENGTH - 1)return parent1[:point] + parent2[point:], parent2[:point] + parent1[point:]# Mutation: Flip bits with a certain probabilitydef mutate(individual):return [bit if random.random() > MUTATION_RATE else 1 - bit for bit in individual]# Main Genetic Algorithm Loopdef genetic_algorithm():population = initialize_population()for generation in range(GENERATIONS):fitnesses = [fitness(ind) for ind in population]if max(fitnesses) == CHROMOSOME_LENGTH:print(f"Solution found in generation {generation}")breaknew_population = []for _ in range(POPULATION_SIZE // 2):parent1 = select(population, fitnesses)parent2 = select(population, fitnesses)child1, child2 = crossover(parent1, parent2)new_population.extend([mutate(child1), mutate(child2)])population = new_population# Print the best solutionbest_individual = max(population, key=fitness)print("Best Individual:", best_individual)print("Fitness:", fitness(best_individual))# Run the algorithmgenetic_algorithm()Copied!✕Copy Genetic Algorithm: Complete Guide With Python …
Jul 29, 2024 · Now that we have a good handle on what genetic algorithms are and generally how they work, let’s build our own genetic algorithm to solve a simple …
PyGAD - Python Genetic Algorithm! — PyGAD 3.5.0 …
Currently, PyGAD supports building and training (using genetic algorithm) artificial neural networks for classification problems. The library is under active …
Simple Genetic Algorithm From Scratch in Python
Genetic algorithm is a stochastic optimization algorithm inspired by evolution. How to implement the genetic algorithm from scratch in Python. How to apply the …
PyGAD: Genetic Algorithm in Python - GitHub
- PyGAD is an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizin…
Check documentation of the PyGAD. - PyGAD supports different types of crossover, mutation, and parent selection. PyGAD allows different ty…
The library is under active development and more features are added regularly. If you want a feature to be supported, please check the Contact Us section to send a request.
- PyGAD is an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizin…
Genetic Algorithms With Scikit-Learn In Python
Searches you might like
How to Build a Genetic Algorithm from Scratch in Python
Aug 30, 2024 · In this article, I will show the reader how to build their own Genetic Algorithm with Python and apply it to a real-world use case. Why use a Genetic …
Genetic Algorithm in Python - Ander Fernández
In this post you have been able to learn what a genetic algorithm is, how it works and how to use it easily in Python, both for optimization models and for …
Genetic Algorithm in Python: A Comprehensive Guide
Mar 18, 2025 · This blog will walk you through the fundamental concepts, usage methods, common practices, and best practices of genetic algorithms in Python.
Building a Genetic Algorithm from Scratch in Python
Nov 16, 2024 · Master the implementation of genetic algorithms in Python with this comprehensive guide, including step-by-step explanations and code examples.
pygad · PyPI
Jul 8, 2025 · PyGAD is an open-source easy-to-use Python 3 library for building the genetic algorithm and optimizing machine learning algorithms. It supports Keras …