Initialization - danielwilczak101/EasyGA GitHub Wiki

Initialization is the process of generating a new population based on attributes that can be specified in the code.









Use for Initialization

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.

Source Code

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.")

Build your own

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.

  1. Write your own initialize_population method. (Recommended, requires writing a method and allows runs to be reset.)
  2. Set ga.population directly 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:

  1. ga.population must be set to a population.
  2. 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()
⚠️ **GitHub.com Fallback** ⚠️