Applying Termination Criteria to Shipping
Genetic Algorithms in Elixir — by Sean Moriarity (39 / 101)
👈 Defining Termination Criteria | TOC | Crafting Fitness Functions 👉
With three possible means of determining when to stop, you need to decide which one works best for your cargo problem. The simplest is to stop after a certain number of generations. Of course, you could use a temperature mechanism; however, it’s too complicated for the task at hand.
Ensure the terminate? callback in the Problem module is set up to accept a generation argument. Additionally, ensure run and evolve are configured to track generations:
# problem.ex
@callback terminate?(Enum.t(), integer()) :: boolean()
# genetic.ex
def run(problem, opts \\ [])
population = initialize(&problem.genotype/0, opts)
population
» |> evolve(problem, 0, opts)
end
»def evolve(population, problem, generation, opts \\ []) do
...
» if terminate?(population, generation) do
...
|> mutation(opts)
» |> evolve(problem, generation+1, opts)
endNow, implement your termination criteria like this:
def terminate?(_population, generation), do: generation == 1000Now, run your algorithm:
$ mix run scripts/cargo.exs
Current Best: 35
[0, 1, 1, 1, 0, 1, 0, 0, 0, 1]
Weight is: 38While your profit definitely went down, your cargo configuration stayed under the weight limit. You may find if you run this algorithm multiple times, your configuration will vary slightly. Remember, genetic algorithms are subject to randomness, so your solutions will vary. Try to run it mulitple times to see what the best configuration is.
As you can see, how you evaluate solutions significantly impacts the outcome of your algorithms. In this problem, you examined one specific way to evaluate one specific type of problem. Unfortunately, there are countless classes of problems out there. In the next section, you’ll gain a better understanding of fitness and fitness functions, and you’ll learn about some other types of optimization problems and how they’re evaluated.
👈 Defining Termination Criteria | TOC | Crafting Fitness Functions 👉
Genetic Algorithms in Elixir by Sean Moriarity can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.







