...

/

The Evaluation, Selection and Crossover Steps

The Evaluation, Selection and Crossover Steps

Learn how to implement the evaluation, selection, and crossover steps in a genetic algorithm.

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:

Press + to interact
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 ...

Access this course and 1400+ top-rated courses and projects.