def makeNewGeneration(self):
        new_population = Population()
        elected = self.population.getTheBest()
        new_population.add(elected)

        while len(new_population) < self.population_size:
            couple = self.population.selectACouple()
            child = Person.copulate(couple['man'], couple['woman'], self.contrainsts)
            if child is not None:
                new_population.add(child)

        self.population = new_population
 def generation(self, population):
     '''
     1. Selection: Pick two parents with probability according to relative fitness
     2. Crossover: Create a child combining the genotype of these two parents
     3. Mutation: Mutate the child based on a given probability
     4. Add the new child to a new population
     '''
     new_population = Population(0)
     for i in range(int(len(population) / 2)):
         parents = self.selection(population)
         if random.random() <= self.crossover_rate:
             children = self.crossover(parents)
         else:
             children = parents
         children = self.mutation(children)
         for child in children:
             new_population.add(child)
     return new_population
Ejemplo n.º 3
0
print("Preprocessing complete")

vocabulary = set()

for text in train_data['text']:
    tokens = word_tokenize(text)
    bigrams = ngrams(tokens, 2)
    for unigram in tokens:
        vocabulary.add(unigram)
    for bigram in bigrams:
        vocabulary.add(bigram)

vocabulary = list(vocabulary)
random.shuffle(vocabulary)
vocabulary_size = len(vocabulary)

indivisual_vocabulary_size = vocabulary_size // CONSTANTS.POPULATION_SIZE
assert (indivisual_vocabulary_size > 0)
start = 0

population = Population(vocabulary)
for indivisual_number in range(CONSTANTS.POPULATION_SIZE):
    end = vocabulary_size if indivisual_number + 1 == CONSTANTS.POPULATION_SIZE else start + indivisual_vocabulary_size
    indivisual_vocabulary = vocabulary[start:end]
    start = end
    indivisual = Indivisual(indivisual_vocabulary, train_data, test_data)
    population.add(indivisual)

print("Population initialized")

run(population, CONSTANTS.EPOCHS)
Ejemplo n.º 4
0
    names = [
        'Rick Sanchez', 'Morty Smith', 'Jerry Smith', 'Summer Smith',
        'Beth Smith', 'Jerry C-137', 'Birdperson', 'Squanchy',
        'Mr. P**pyb****ole', 'Noob Noob', 'Doofus Rick', 'Evil Morty',
        'Scary Terry', 'The Cromulons', 'Mr. Meeseeks', 'Mr. Goldenfold',
        'Jessica', 'MC Haps', 'Beth Smith', 'Dr. Xenon Bloom', 'Unity',
        'Crocubot', 'Elon Tusk', 'Mr. Lucius Needful', 'King Jellybean',
        'King Jellybean', 'Zeep Xanflorp', 'Beta VII', 'Glexo Slim Slom',
        'Cornvelious Daniel', 'Frank Palicky', 'Pickle Rick', 'Toby Matthews'
    ]

    population = Population()

    for name in names:
        colleague = Organism(rand_pos(), name)
        population.add(colleague)

    amish_cyborg = Organism([1, 1], 'Amish Cyborg')
    amish_cyborg.infected = True
    population.add(amish_cyborg)

    baby_wizard = Organism([1, 1], 'Baby Wizard')
    baby_wizard.infected = True
    population.add(baby_wizard)

    cousin_nicky = Organism([1, 1], 'Cousin Nicky')
    cousin_nicky.infected = True
    population.add(cousin_nicky)

    population.infected_count = 3
def main():
    t0 = time.time()
    # 1
    # generate initial population of N organisms randomly
    # but maybe with given conditions taken into account
    # i.e. one queen per row and one queen per column
    # one individual should probably look like
    # Individual = ([(0,0), (1,2), (2,1), ...,(7,7)], fitness value) as numpy array: np.
    # 2
    # compute fitness of each individual
    # population = individual.compute_fitness_of_all(population)
    my_population = Population(size=config.number_of_organisms, sort=True)

    # compute the max_fitness value, i.e. no collisions, for a given field_size
    max_fitness = config.field_size * (config.field_size - 1) * 0.5
    iterations = 0
    while my_population[
            0].fitness != max_fitness and iterations < config.max_iterations:
        iterations += 1
        if iterations % 100 == 0 and config.verbose:
            print(iterations, my_population.max_fitness_value())

        # if adapt mutability is set to True it will increase the mutation_probability each 1000 iterations
        # by 10%
        if iterations % 500 == 0 and config.adapt_mutability:
            config.mutation_probability = min(
                config.mutation_probability + 0.05, 1)

        ### NEXT GENERATION ###
        # produce next generation
        # copy the fittest Organisms to the new population "they survive"
        # percentage is determined by config.copy_threshold
        new_pop = Population(my_population[:int(my_population.size() *
                                                config.copy_threshold)])

        # repeat as long as the new population is smaller than the population size
        while new_pop.size() < config.number_of_organisms:
            ### SELECTION ###
            # selecting two organisms from old generation for mating
            # choose fitter ones, maybe not THE fittest
            parent1 = my_population.select_parent(
                method=config.selection_method)
            parent2 = my_population.select_parent(
                method=config.selection_method)

            ### CROSSOVER ###
            # recombine genetic material with probability p_c, i.e. crossover
            # mutate with very small probability
            # create a pair of children
            child1, child2 = my_population.crossover(
                parent1, parent2, method=config.crossover_method)

            ### MUTATION ###
            # let the children mutate with a small probability
            if np.random.uniform() < config.mutation_probability:
                child1.mutate(config.mutation_method)
            if np.random.uniform() < config.mutation_probability:
                child2.mutate(config.mutation_method)

            # insert into new population
            new_pop.add(child1, child2)

        # 4
        # replace the old population with the new one
        my_population = new_pop
        my_population.sort()

        # 5
        # if satisfied with fittest individual -> finish
        # if population converged, i.e. 95% of individuals are the same -> finish
        # otherwise go to 3 and repeat

    the_winner = my_population.fittest_organism()
    computation_time = time.time() - t0
    if config.verbose:
        print(the_winner)
        print(
            f'Number of Iterations:{iterations}\nTotal Time: {computation_time}\nAverage Fitness of final Population: {my_population.compute_average_fitness()}'
        )
    return iterations, computation_time, the_winner.fitness, my_population.compute_average_fitness(
    )