Predict

where the future is written

Follow publication

How to create an easy genetic algorithm in Python

Learn how to create your first genetic algorithm using Python in an easy way

Aitor Velasco
Predict
Published in
3 min readJan 29, 2020
Courtesy of Pixabay/TheDigitalArtist

Genetic algorithms are processes that seek solutions to a specific problem replicating the Darwin’s theory of evolution.

Today we will see how to create a simple genetic algorithm which responds to the famous sentence ‘Don’t worry, be happy’.

We will start with a random generation and algorithm will have to find the solution to get the text before cited.

Basically each generation will be better than the previous one and after a few generations we will get the desired result.

DNA Class

To store the gens of each individual we will create a DNA class that will control their behavior within the algorithm.

To do this, we will add some parameters in the class constructor called size and gen_set.

Additionally, each DNA should have its own fitness score so that the best DNA from each generation can be selected.

Finally we are going to add a method that will be in charge of mutating so that future generations will be better, otherwise the population will never reach their goal 😉

Population class

This class will administer all the DNA of each individual. It will also create new generations or make the necessary mutations.

Then, it is time to create the method in charge of passing to the next generation.

Finally all we need now is one condition that will allow us to know whether we have reached the proposed goal.

Organizing the classes

Now let’s save these two classes in a file called Genetics.py

Action! Main File

We are going to create the main.py file 😀

First, we will define the parameters of the algorithm.

Then, we’ll run the algorithm in a loop until we reach the desired objective and, once it’s done, we’ll show a graph with the results.

The results

In terminal

In visual graph

You can see all the code on Github here

I hope you liked it! 😉

Predict
Predict
Aitor Velasco
Aitor Velasco

Written by Aitor Velasco

Software developer born in Windows, nationalized in Linux, and holidays traveling on Mac. Vocation for science. Oh yes, 🐱 and 🍕lover!

No responses yet

Write a response