Published in

Code To Express

# Demystifying Genetic Algorithm

“Survival of the fittest”

“It is not the strongest species that survive, nor the most intelligent, but the ones most responsive to change”

— Charles Darwin

# There are Five phases in a genetic algorithm:

1. Creating an Initial population

2. Defining a Fitness function

3. Selecting the parents

4. Making a Crossover

5. Mutation

## Pseudo Code

START
Generate the initial population
Compute fitness
REPEAT
Selection
Crossover
Mutation
Compute fitness
UNTIL population has converged
STOP

# Let’s Understand the phases of genetic algorithms in detail

## Let’s take a simple example:

Suppose we want “Unicorn” word.

Step 1: Population

The process begins with a set of individuals which is called a Population. Each individual is a solution to the problem you want to solve.

Select randomly population of three elements, suppose we get

1. Unijorm
2. caesore
3. popcorn

Step 2: Fitness Function

The fitness function determines how fit an individual is. It gives a fitness score to each individual. The probability that an individual will be selected for reproduction is based on its fitness score.

Here, suppose we define fitness as number of each words match with the desired output.

Unijorm — 4 (4 words matches with Unicorn)

caesore — 2 (2 words matches with Unicorn)

popcorn — 4 (4 words matches with Unicorn)

Step 3: Selection

The idea of selection phase is to select the fittest individuals and let them pass their genes to the next generation.

We take top 2 parents with high fitness score that is, Unijorm & popcorn.

Step 4: Crossover

crossover, also called recombination, is a genetic operator used to combine the genetic information of two parents to generate new offspring.

Here, we combined the genetic information from parents we selected.

We get “Unicorn”.

Step 5: Mutation

Mutation occurs to maintain diversity within the population and prevent premature convergence.

We already got our desired result after crossover so it will not mutate.

# Implementation of Genetic Algorithm in Code

Finding “Unicorn” with (Java & Processing)

Using above DNA class in main file.

Implementation of GA in Simple Flappy Bird Game(Using JavaScript):

# Conclusion

It is better than conventional AI and it is more robust. Unlike older AI systems, they do not break easily even if the inputs changed slightly, or in the presence of reasonable noise. Also, in searching a large state-space it is very efficient.

# Get your own blog published on C2E Blog

Do you want to write for CodeToExpress? We would love to have you as a technical writer. Send us an email with a link to your draft at codetoexpress@gmail.com

--

--

## More from Code To Express

Discovering Life in Tech