Exemplo n.º 1
0
def random_selection(population, fitness_fn):
    """
    Compute fitness of each in population according to fitness_fn and add up
    the total. Then choose 2 from sequence based on percentage contribution to
    total fitness of population
    Return selected variable which holds two individuals that were chosen as
    the mother and the father
    """

    # Python sets are randomly ordered. Since we traverse the set twice, we
    # want to do it in the same order. So let's convert it temporarily to a
    # list.
    ordered_population = list(population)
    fitness = []
    sumFit = 0
    for i in ordered_population:
        fitAmount = fitness_fn_positive(i)
        sumFit += fitAmount
        for f in range(fitAmount):
            fitness.append(i)
    returnList = []
    for k in range(2):
        returnList.append(fitness[random.randint(0, sumFit - 1)])

    return returnList
def main():
    minimal_fitness = 28

    # Curly brackets also creates a set, if there isn't a colon to indicate a dictionary

    initial_population = get_initial_population(8, 8)

    initial_population = calculate_fitness(initial_population, fitness_fn_positive)

    fittest = genetic_algorithm(initial_population, fitness_fn_positive, minimal_fitness)
    print('Fittest Individual: ' + str(fittest) + " with fitness " + str(fitness_fn_positive(fittest)))
Exemplo n.º 3
0
def fitness_function(individual):
    '''
    Computes the decimal value of the individual
    Return the fitness level of the individual

    Explanation:
    enumerate(list) returns a list of pairs (position, element):

    enumerate((4, 6, 2, 8)) -> [(0, 4), (1, 6), (2, 2), (3, 8)]

    enumerate(reversed((1, 1, 0))) -> [(0, 0), (1, 1), (2, 1)]
    '''
    fitness = queens_fitness.fitness_fn_positive(individual)
    return fitness
Exemplo n.º 4
0
def fitness_function(individual):
    return (queens_fitness.fitness_fn_positive(individual))