View Source Genetix (Genetix v0.4.0)
Structure of a genetic algorithm in Elixir.
The process of creating an algorithm can be thought of in three phases:
- Problem Definition
- Evolution Definition
- Algorithm Execution
To define a Problem
you need to define the specific-problems funtions:
- Define your solution space (
genotype/1
): How to generate a new individual of your problem. - Define your objective function (
fitness_function/2
): How to evaluate each individual. - Define your termination criteria (
terminate?/2
): When the algorithm must to stop.
implementing-a-problem
Implementing a Problem
A basic genetic problem consists of: genotype/0
, fitness_function/1
, and terminate?/1
.
defmodule OneMax do
@behaviour Genetix.Problem
alias Genetix.Types.Chromosome
@impl true
def genotype(opts \ []) do
size = Keyword.get(opts, :size, 10)
genes = for _ <- 1..42, do: Enum.random(0..1)
%Chromosome{genes: genes, size: size}
end
@impl true
def fitness_function(chromosome, _opts \ []), do: Enum.sum(chromosome.genes)
@impl true
def terminate?([best | _], _opts \ []) do
best.fitness == best.size
end
end
Notice that in this case, we use size
as a hyperparameter to define the gene size.
hyperparameters
Hyperparameters
It refers to the parts of the algotihm you set before the algorithm starts to configure the behavior of the algorithm: which GA operators use,
size of the individuals, etc.. You can provide a Keyword
with hyperparameters.
Check Problem definition for more information.
examples
Examples
iex> alias Genetix.Problems.OneMax
iex> Genetix.run(OneMax, size: 50)
Link to this section Summary
Functions
Run a specific problem with optional hyperparameters
.
Link to this section Functions
Run a specific problem with optional hyperparameters
.
Check Problem definition for more information about hyperparameters
.