Genetic Algorithm (GA) for NQueens¶
In [1]:
Copied!
from metazoo.bio.evolutionary import GeneticAlgorithm
from metazoo.bio.evolutionary.operators import selection, mutation, crossover
from metazoo.gym.combinatorial import NQueens
from metazoo.bio.utils import encoding
from metazoo.bio.evolutionary import GeneticAlgorithm
from metazoo.bio.evolutionary.operators import selection, mutation, crossover
from metazoo.gym.combinatorial import NQueens
from metazoo.bio.utils import encoding
In [2]:
Copied!
N = 8
fitness_function = NQueens(n=N)
encoder = encoding.Permutation(permutation_size=N)
ga = GeneticAlgorithm(
fitness_function=fitness_function,
crossover_function=crossover.PMX,
mutation_function=mutation.swap,
selection_function=selection.tournament,
population_size=200,
mutation_rate=0.01,
crossover_rate=0.7,
encoder=encoder,
elitism=0.1,
minimize=False,
)
ga.run(generations=500)
N = 8
fitness_function = NQueens(n=N)
encoder = encoding.Permutation(permutation_size=N)
ga = GeneticAlgorithm(
fitness_function=fitness_function,
crossover_function=crossover.PMX,
mutation_function=mutation.swap,
selection_function=selection.tournament,
population_size=200,
mutation_rate=0.01,
crossover_rate=0.7,
encoder=encoder,
elitism=0.1,
minimize=False,
)
ga.run(generations=500)
Output()
In [3]:
Copied!
print(f'Best Individual: {ga.best_individual}')
print(f'Best Fitness: {ga.best_fitness}')
print(f'Best Individual: {ga.best_individual}')
print(f'Best Fitness: {ga.best_fitness}')
Best Individual: [2 5 1 6 4 0 7 3] Best Fitness: 28.0
In [4]:
Copied!
ga.fitness_plot()
ga.fitness_plot()
In [5]:
Copied!
fitness_function.plot(solution=ga.best_individual, attacks=fitness_function.attacks(ga.best_individual))
fitness_function.plot(solution=ga.best_individual, attacks=fitness_function.attacks(ga.best_individual))