PyGAD - Genetic Algorithm in Python
raw JSON → 3.6.0 verified Fri May 01 auth: no python
PyGAD is a Python library for building genetic algorithms and training machine learning models (Keras & PyTorch). Current version 3.6.0, released March 2025, with a cadence of several minor releases per year. Supports single- and multi-objective optimization, custom operators, and integration with deep learning frameworks.
pip install pygad Common errors
error TypeError: 'GA' object is not callable ↓
cause In versions <3.0.0, the GA class was instantiated directly; in 3.0.0+, the module import changed.
fix
Use 'import pygad' and then 'ga = pygad.GA(...)'.
error Fitness function must have 2 arguments, but it has 1 ↓
cause After PyGAD 3.0.0, fitness function signature changed to (solution, solution_idx).
fix
Change your fitness function to accept a second argument: def fitness_func(solution, solution_idx):
Warnings
breaking In PyGAD 3.0.0+, the fitness function signature changed: it now receives two arguments (function, solution_idx). The first argument is the solution array, the second is the solution index. ↓
fix Update fitness function from fitness_func(solution) to fitness_func(solution, solution_idx).
gotcha When using 'gene_space' with a step, the gene type is inferred: if step is integer, genes are integers; if step is float, genes are floats. Mixing types can cause unexpected results. ↓
fix Ensure gene_space step matches desired data type.
deprecated The 'delay_after_gen' parameter was removed in v3.4.0. Use 'on_generation' callback to add delay. ↓
fix Replace delay_after_gen with a custom on_generation function containing time.sleep().
Imports
- GA
import pygad
Quickstart
import pygad
import numpy as np
# Define fitness function (must accept two arguments: solution and solution_index)
def fitness_func(solution, solution_idx):
return -np.sum(solution)
# Define gene space
num_genes = 6
gene_space = {'low': 0, 'high': 2, 'step': 1} # integers 0 or 1
# Create GA instance
ga_instance = pygad.GA(
num_generations=10,
num_parents_mating=4,
fitness_func=fitness_func,
sol_per_pop=8,
num_genes=num_genes,
gene_space=gene_space,
parent_selection_type="sss",
keep_parents=1,
crossover_type="single_point",
mutation_type="random",
mutation_num_genes=1
)
# Run GA
ga_instance.run()
# Show best solution
solution, solution_fitness, _ = ga_instance.best_solution()
print(f"Best solution: {solution}")
print(f"Fitness: {solution_fitness}")