Initialization - danielwilczak101/EasyGA GitHub Wiki
Initialization is the process of generating a new population based on attributes that can be specified in the code.
This is the method that the initial population is made from. If a chromosome_impl method is defined, then it is used. Otherwise if a gene_impl method is defined, then it is used. If neither are defined then a ValueError is raised.
def initialize_population(self):
"""Initialize the population using
the initialization implimentation
that is currently set.
"""
if self.chromosome_impl is not None:
self.population = self.make_population(
self.chromosome_impl()
for _
in range(self.population_size)
)
elif self.gene_impl is not None:
self.population = self.make_population(
(
self.gene_impl()
for __
in range(self.chromosome_length)
)
for _
in range(self.population_size)
)
else:
raise ValueError("No chromosome or gene impl specified.")There are times when one may desire a more specific initialization of the population, perhaps because a rough estimate of the solution to the problem is known beforehand. There are two main ways to change the initialization of the population without changing the chromosomes possible.
- Write your own
initialize_populationmethod. (Recommended, requires writing a method and allows runs to be reset.) - Set
ga.populationdirectly when initializing the ga object. (Recommended only for simple one-time usage and will not be used to reset runs.)
The notable features required are:
-
ga.populationmust be set to a population. - To make a population, one may use
ga.make_population(data).
Example:
A problem may require chromosomes with 5 genes made of random floats from 0 to 10, but some estimates for a good chromosome are already known. Each gene is then setup accordingly.
from EasyGA import GA
import random
class My_GA(GA):
"""Example GA with custom initialize_population method."""
def initialize_population(self):
"""Custom population initialization with chromosomes where
0 < gene1 < 3
6 < gene2 < 8
5 < gene3 < 7
3 < gene4 < 6
1 < gene5 < 2
"""
self.population = self.make_population(
[
random.uniform(0, 3)
random.uniform(6, 8)
random.uniform(5, 7)
random.uniform(3, 6)
random.uniform(1, 2)
]
for _
in range(self.population_size)
)
# Make a custom ga object
ga = MY_GA()
# Run everything.
ga.evolve()