The Evaluation, Selection and Crossover Steps
Learn how to implement the evaluation, selection, and crossover steps in a genetic algorithm.
We'll cover the following...
Evaluating the population
After initializing our population, the next step is the evaluation phase. In the previous lesson, we created a stub of the evaluate
function. This represents “step 2” in the genetic algorithm and what we would be filling in now.
The main understanding behind this function is that it takes a population
, evaluates each chromosome based on a fitness function
, and sorts the population
based on each chromosome’s fitness. “Fitness” is simply a heuristic that tells us how good or bad a solution is, and the fitness function calculates this fitness for us. In this One-Max problem, the fitness of a chromosome is represented by the sum of the bitstring.
Let us go about implementing the evaluate
function now. In our algorithm defined so far, replace the stub of the evaluate
function with the following:
evaluate =fn population ->Enum.sort_by(population, &Enum.sum/1, &>=/2)end
The evaluate
function uses the Enum.sort_by/3
function to sort the population by the sum in descending order. This means that better solutions will exist at the top of the population and that better solutions will be grouped together. Sorting our ...