Adding Mutation
Genetic Algorithms in Elixir — by Sean Moriarity (17 / 101)
👈 Running Your Solution | TOC | What You Learned 👉
Despite initializing your population to a seemingly random distribution, eventually the parents got too genetically similar to make any improvements during crossover. This illustrates the importance of including the mutation step in your algorithm and how vital exploration is to informed search techniques.
After the crossover function in the algorithm, add the following:
|> mutation.()
Now, the structure of the algorithm looks like this:
population
|> fitness.()
|> selection.()
|> crossover.()
|> mutation.()
|> algorithm.(algorithm)
Mutation is similar to the other functions in that it accepts a population as a parameter. You only want to mutate a small percentage of your population as well — this is to preserve the progress that’s already been made. Below your crossover definition, add the following:
mutation =
fn population ->
population
|> Enum.map(
fn chromosome ->
if :rand.uniform() < 0.05 do
Enum.shuffle(chromosome)
else
chromosome
end
end)
end
This function iterates over the entire population and randomly shuffles a chromosome with a probability of 5%. The :rand.uniform() < 0.05 condition is a pattern…