| name | genetic-algorithms |
| description | Genetic algorithm optimization |
| license | MIT |
| compatibility | opencode |
| metadata | {"audience":"machine-learning-engineers","category":"artificial-intelligence"} |
What I do
- Implement evolutionary algorithms
- Design genetic representations
- Create fitness functions
- Implement selection and crossover
- Handle mutation operators
- Optimize using evolution
When to use me
Use me when:
- Complex optimization problems
- Noisy or non-differentiable fitness
- Multi-objective optimization
- Feature selection
- Neural architecture search
Key Concepts
Genetic Algorithm Flow
┌──────────────┐
│ Population │◀──────────────┐
│ Generation │ │
└──────┬───────┘ │
│ │
▼ │
┌──────────────┐ ┌─────────┐│
│ Evaluate │ │ Select ││
│ Fitness │───▶│ Parents││
└──────────────┘ └────┬────┘
│
▼
┌─────────────┐
│ Crossover │
│ + Mutate │
└──────┬──────┘
│
▼
┌─────────────┐
│ Replace │
│ Population │
└──────┬──────┘
│
▼
┌──────────────┐
│ Continue? │
└──────────────┘
Implementation
import random
import numpy as np
class GeneticAlgorithm:
def __init__(self, pop_size=100, mutation_rate=0.1,
crossover_rate=0.8):
self.pop_size = pop_size
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
def init_population(self):
return [self.create_individual() for _ in range(self.pop_size)]
def fitness(self, individual):
raise NotImplemented
def selection(self, population, fitnesses):
selected = []
for _ in range(len(population)):
i, j = random.sample(range(len(population)), 2)
if fitnesses[i] > fitnesses[j]:
selected.append(population[i].copy())
else:
selected.append(population[j].copy())
return selected
def crossover(self, parent1, parent2):
random.random() > .crossover_rate:
parent1.copy(), parent2.copy()
point = random.randint(, (parent1) - )
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
child1, child2
():
i ((individual)):
random.random() < .mutation_rate:
individual[i] = .random_gene()
individual
():
population = .init_population()
gen (generations):
fitnesses = [.fitness(ind) ind population]
best_idx = np.argmax(fitnesses)
new_pop = [population[best_idx].copy()]
parents = .selection(population, fitnesses)
i (, (parents) - , ):
child1, child2 = .crossover(parents[i], parents[i+])
new_pop.append(.mutate(child1))
new_pop.append(.mutate(child2))
population = new_pop[:.pop_size]
(population, key=.fitness)
Operators
- Selection: Tournament, roulette, rank
- Crossover: One-point, two-point, uniform
- Mutation: Bit flip, swap, Gaussian
- Replacement: Generational, elitism