Loading…
Glossary term
An optimization method inspired by natural selection, evolving solutions over generations.
A genetic algorithm evolves solutions: it keeps a population of candidates, scores them, lets the better ones 'reproduce' by combining and randomly mutating them, and repeats for many generations.
It suits problems that are hard to describe mathematically but easy to score.
Evolve a string of ones
import random
def fitness(bits): return sum(bits)
pop = [[random.randint(0, 1) for _ in range(20)] for _ in range(30)]
for _ in range(50):
pop.sort(key=fitness, reverse=True)
parents = pop[:10]
pop = parents + [
[b if random.random() > 0.05 else 1 - b
for b in random.choice(parents)] for _ in range(20)
]
print(fitness(pop[0])) # approaches 20It is a flexible optimizer for design, scheduling and tuning problems.