Example #1
0
def reproduce(population):
    """Applies the evolutionary survival process to the population.

    A few select elites with the best reward (fitness) is automatically part of the next generation.
    From the population parents are selected to create offspring. The offspring will be part of
    the next generation. The parents will cease to exist unless they were part of the elite.
    Mutation is applied to the offspring, which has a chance of altering the chromosomes.

    Args:
        The population which is a list of the object Individual. The entire population just ran in
        the simulation and their reward (fitness) was stored.

    Returns:
        A new population which is a list of the object Individual. The new population is the next generation
        and consists of the elite from the previous population and offspring from the previous generation.
    """

    # Sort the population by its reward (fitness)
    population = sorted(population, key=lambda x: x.reward, reverse=True)
    total_remove = 94

    if judgement_day(population):
        new_population = [population[0]]

        for i in range(100 - len(new_population)):
            new_population.append(random_neural_network())

        return new_population

    # Elitism
    new_population = population[:(len(population) - total_remove)]

    # Selection, may be replaced by tournament_selection method
    parent_1, parent_2 = wheel_selection(total_remove, population)

    for i in range(int(total_remove / 2)):
        weight_1, weight_2 = uniform_crossover(parent_1[i].chromosome_1,
                                               parent_2[i].chromosome_1)
        bias_1, bias_2 = uniform_crossover(parent_1[i].chromosome_2,
                                           parent_2[i].chromosome_2)

        mutate(weight_1)
        mutate(weight_2)
        mutate(bias_1)
        mutate(bias_2)

        c1 = Individual()
        c2 = Individual()

        c1.chromosome_1 = weight_1
        c1.chromosome_2 = bias_1

        c2.chromosome_1 = weight_2
        c2.chromosome_2 = bias_2

        new_population.append(c1)
        new_population.append(c2)

    return new_population
def uniform_crossover_binary(p1, p2):
    """Translate the rules to binary and apply crossover.

    Arguments:
        p1: The chromosome of the first parent. Is a list of numbers.
        p2: The chromosome of the second parent. Is a list of numbers.

    Returns:
        Two new rule sets in base 10 value. Is two lists of numbers.
    """
    p1_binary = []
    p2_binary = []

    for rule_id in p1:
        p1_binary.append(list(map(int, format(rule_id, "#010b")[2:])))

    for rule_id in p2:
        p2_binary.append(list(map(int, format(rule_id, "#010b")[2:])))

    c1, c2 = uniform_crossover(p1_binary, p2_binary)

    for i in range(len(c1)):
        c1[i] = int("".join(str(x) for x in c1[i]), 2)

    for j in range(len(c2)):
        c2[j] = int("".join(str(x) for x in c2[j]), 2)

    return c1, c2
def reproduce(population):
    """Applies the evolutionary survival process to the population.

    A few select elites with the best reward (fitness) is automatically part of the next generation.
    From the population parents are selected to create offspring. The offspring will be part of
    the next generation. The parents will cease to exist unless they were part of the elite.
    Mutation is applied to the offspring, which has a chance of altering the chromosomes.

    Args:
        The population which is a list of the object Individual. The entire population just ran in
        the simulation and their reward (fitness) was stored.

    Returns:
        A new population which is a list of the object Individual. The new population is the next generation
        and consists of the elite from the previous population and offspring from the previous generation.
    """

    # Sort the population to find out which had the best performance
    population = sorted(population, key=lambda x: x.reward, reverse=True)
    total_remove = 94

    # Elitism
    new_population = population[:(len(population) - total_remove)]

    parent_1, parent_2 = wheel_selection(total_remove, population)

    for i in range(int(total_remove / 2)):

        if random_offspring(parent_1[i], parent_2[i]):
            individual_1, individual_2 = create_random_offspring()
        else:
            rule_1, rule_2 = uniform_crossover_binary(parent_1[i].chromosome_1,
                                                      parent_2[i].chromosome_1)
            range_1, range_2 = uniform_crossover(parent_1[i].chromosome_2,
                                                 parent_2[i].chromosome_2)

            mutate(rule_1)
            mutate(rule_2)

            ca_mutate(range_1)
            ca_mutate(range_2)

            individual_1 = Individual()
            individual_2 = Individual()

            individual_1.chromosome_1 = rule_1
            individual_2.chromosome_1 = rule_2

            individual_1.chromosome_2 = range_1
            individual_2.chromosome_2 = range_2

        new_population.append(individual_1)
        new_population.append(individual_2)

    return new_population
Example #4
0
def michigan(population, N, p, trainingData):
    '''

    :param population: a fuzzy rule set
    :param N: number of iteration
    :param p: rate
    :return:
    '''
    pc = p[0]
    pm = p[1]

    # sort population
    population.rules.sort(key=lambda x: x.fitness, reverse=True)

    # child_set = []

    # for i in range(N):
    # child_set.append(p1)

    # P1 p2是rule
    p1, p2 = selection.binary_tournament_selection(population.rules)

    # c = copy.deepcopy(p1)

    cp1_rule = p1.rule
    cp2_rule = p2.rule

    if random.random() < pc:
        # crossover for rule
        child_rule = crossover.uniform_crossover(cp1_rule, cp2_rule)
    else:
        child_rule = [cp1_rule, cp2_rule][random.random() < 0.5]

    if random.random() < pm:
        child_rule = mutation.rule_mutation(child_rule)

    p1.rule = child_rule
    p1.Cq, p1.CFq = p1.getCqCFq(child_rule, trainingData)

    population.rules[-1] = p1

    return population
Example #5
0
def genetic_algorithm(k):
    """ Function that actually runs the Genetic Algorithm. 
  
    Keyword arguments: 
        k -- number of iterations to run the algorithm for 
  
    Returns: 
        best_log and avg_log -- Both contain k lists, each containing
            x integers, where x is the number of generations on that
            iteration, that represent the best and average fitness
            score for each generation, respectively
        pop_size_log -- List containing k integers, each being the
            size of the population on that iteration
    """
    
    best_log = []
    avg_log = []
    pop_size_log = []
    
    for iteration in range(0, k):
        # Lists that will hold the 
        gen_best_log = []
        gen_avg_log = []

        # Defining number of generations and probabilities
        gen_number = 25
        crossover_probability = 0.75
        mutation_probability = 0.0001

        # Starting population
        population, pop_size = utils.create_population(iteration)
        
        pop_size_log.append(pop_size)
        
        # Defining the size of the tournament's bracket
        # the k in k-way tournament
        tournament_bracket_size = round(pop_size/20)

        # Iterating through all generations
        for j in range(0, gen_number):
            
            # Calculating the fitness score for every
            # subject in the population and saving the
            # best and the average score
            pop_fitness, best, average = utils.calculate_pop_fitness(population) 

            gen_best_log.append(best)
            gen_avg_log.append(average)

            # Preventing the algorithm to go all the way through
            # during the last iteration, since that population
            # won't be recorded anyways
            if j == gen_number - 1:
                break
            
            # Calling the tournament, crossover and mutation function
            # and overwriting the current population with the new one
            population = tournament.k_way_tournament(population, pop_size, pop_fitness, tournament_bracket_size)
            population = crossover.uniform_crossover(population, pop_size, crossover_probability)
            population = mutation.mutation(population, mutation_probability)

        best_log.append(gen_best_log)
        avg_log.append(gen_avg_log)
    
    return best_log, avg_log, pop_size_log
Example #6
0
import statistics_module
import crossover
import parents_selector
import mutation

initial_population=horse.Horse.generate_population(10)
my_hipodrome=hipodrome.Hipodrome(7,7,3,4)
list_fitness=calculate_population_fitness(initial_population,my_hipodrome)
current_population_statistics=[]



for i in range(len(initial_population)):    
    horse=initial_population[i]
    horse_fitness=list_fitness[i]

    my_horse=statistics_module.FitnessStatistics(horse,horse_fitness)
    current_population_statistics.append(my_horse)

parents=parents_selector.select_candidates(current_population_statistics,2)



offspring=crossover.uniform_crossover(parents,10)
after_mutation_offsping=mutation.non_uniform_mutation(offspring)
second_population=horse.new_population_generator(after_mutation_offsping)

print(after_mutation_offsping)
print(second_population)