This repository demonstrates a basic implementation of a Genetic Algorithm (GA).
Given a set of points in 2D space, determine the polygon that maximises the ratio of its area to the square of its perimeter
The following animations demonstrate the evolution of the polygon shapes over many generations.
Example 1
Example 2
Clone the repository and install the necessary dependencies using pipenv
.
git clone https://github.com/mark-hobbs/ga-demo.git
cd ga-demo
pipenv install
pipenv shell
Execute the demo script to run the genetic algorithm and output an animation illustrating the evolution of the population towards optimal solutions.
python demo.py
demo.py
contains the following logic. The values can be edited as desired:
Start by generating 10 random points.
n_points = 10
points = [Point(np.random.rand(), np.random.rand()) for _ in range(n_points)]
Create an initial population of 25 polygons using the generated points.
population_size = 25
individuals = [Polygon(np.random.permutation(points)) for _ in range(population_size)]
population = Population(individuals)
Set up the Genetic Algorithm with the initial population, number of generations, number of parents, and mutation probability. You can also enable animation.
ga = GeneticAlgorithm(
population=population,
num_generations=100,
num_parents=4,
mutation_probability=0.05,
animate=True,
)
Run the genetic algorithm to evolve the population towards optimal solutions.
ga.evolve()
Run the demonstration as a notebook to easily modify the parameters and explore their influence on the final results.
jupyter lab demo.ipynb
Or you can run the notebook using Google Colab:
This project is licensed under the MIT License. See the LICENSE file for details.