Example #1
0
def runGA(num_generations):
    # Inputs of the equation.
    equation_inputs = [4, -2, 3.5, 5, -11, -4.7]
    cost_history = []
    # Number of the weights we are looking to optimize.
    num_weights = 3
    """
    Genetic algorithm parameters:
        Mating pool size
        Population size
    """
    sol_per_pop = 8
    num_parents_mating = 4

    # Defining the population size.
    pop_size = (
        sol_per_pop, num_weights
    )  # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
    #Creating the initial population.
    new_population = numpy.random.uniform(low=-40.0, high=40.0, size=pop_size)
    print(new_population)

    for generation in range(num_generations):
        print("Generation : ", generation)
        # Measing the fitness of each chromosome in the population.
        fitness = ga.cal_pop_fitness(equation_inputs, new_population)

        # Selecting the best parents in the population for mating.
        parents = ga.select_mating_pool(new_population, fitness,
                                        num_parents_mating)

        # Generating next generation using crossover.
        offspring_crossover = ga.crossover(
            parents,
            offspring_size=(pop_size[0] - parents.shape[0], num_weights))

        # Adding some variations to the offsrping using mutation.
        offspring_mutation = ga.mutation(offspring_crossover)

        # Creating the new population based on the parents and offspring.
        new_population[0:parents.shape[0], :] = parents
        new_population[parents.shape[0]:, :] = offspring_mutation

        # The best result in the current iteration.
        print(new_population[0], new_population[1], new_population[2])
        temp1 = test.testga(new_population[0])
        temp2 = test.testga(new_population[1])
        temp3 = test.testga(new_population[2])
        # print(temp1, temp2, temp3)
        print("Best result : ", numpy.max([temp1, temp2, temp3]))

    # Getting the best solution after iterating finishing all generations.
    # At first, the fitness is calculated for each solution in the final generation.
    fitness = ga.cal_pop_fitness(equation_inputs, new_population)
    # Then return the index of that solution corresponding to the best fitness.
    best_match_idx = numpy.where(fitness == numpy.max(fitness))

    print("Best solution : ", new_population[best_match_idx, :])
Example #2
0
    def generation(self, i):
        # Measuring the fitness
        fitness = ga.cal_pop_fitness(self.population, self.this_grid, self.blocks)

        # Selecting the best parents in the population for mating.
        parents = ga.select_mating_pool(self.population, fitness, self.num_parents_mating)

        # Generating next generation using crossover.
        offspring_crossover = ga.crossover(parents, self.population, self.num_offspring)

        # Adding some variations to the offsrping using mutation.
        mutation_scale = (self.num_generations / ((self.num_generations - i)) + 1)
        offspring_mutation = ga.mutation(offspring_crossover, mutation_scale=mutation_scale)

        best_match_idx = np.argmax(fitness)
        best_fitness = fitness[best_match_idx]
        print(f'Generation {i} Best result : {max(fitness)}')
        if self.verbose:

            print('Average result : ', sum(fitness) / len(fitness))

            print('Best idx: ', best_match_idx)
            print('Best solution : ', self.population[best_match_idx])
            print('Best solution fitness : ', best_fitness)

        very_best = self.population[best_match_idx].squeeze().copy()

        # Creating the new population based on the parents and offspring.
        self.population[:parents.shape[0], :] = parents
        self.population[parents.shape[0]:, :] = offspring_mutation
        self.best_agents.append(very_best)
        return max(fitness)
Example #3
0
def test_cal_pop_fitness():
    pop = numpy.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 7], [-1, 3, 25, 2, 6],
                       [2, 3, 3, 5, 6], [2, 2, 4, -2, 6]])

    equation_inputs = numpy.array([2, 5, 8, 3, 1])

    result = numpy.array([53, 73, 225, 64, 46])

    assert (cal_pop_fitness(equation_inputs, pop) == result).all()
Example #4
0
def ga_pwr(ass_dim, pop, pmat, ngen):
    sol_per_pop = pop
    num_parents_mating = pmat

    # Defining the population size.
    pop_size = (
        sol_per_pop, ass_dim
    )  # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
    #Creating the initial population.
    new_population = np.random.randint(1, dim, size=pop_size)
    #    print(new_population)

    num_generations = ngen

    for generation in range(num_generations):
        #    print("Generation : ", generation)
        # Measing the fitness of each chromosome in the population.
        fitness = ga.cal_pop_fitness(rl1, new_population)

        # Selecting the best parents in the population for mating.
        parents = ga.select_mating_pool(new_population, fitness,
                                        num_parents_mating)

        # Generating next generation using crossover.
        offspring_crossover = ga.crossover(
            parents, offspring_size=(pop_size[0] - parents.shape[0], ass_dim))

        # Adding some variations to the offsrping using mutation.
        offspring_mutation = ga.mutation(offspring_crossover, dim, ass_dim)

        # Creating the new population based on the parents and offspring.
        new_population[0:parents.shape[0], :] = parents
        new_population[parents.shape[0]:, :] = offspring_mutation

        # The best result in the current iteration.
    #    print("Best result : ", np.max(np.sum(new_population*equation_inputs, axis=1)))

    # Getting the best solution after iterating finishing all generations.
    #At first, the fitness is calculated for each solution in the final generation.
    fitness = ga.cal_pop_fitness(rl1, new_population)
    # Then return the index of that solution corresponding to the best fitness.
    best_match_idx = np.where(fitness == np.max(fitness))
    res = np.max(fitness)
    return (res)
Example #5
0
print(new_population)
"""
new_population[0, :] = [2.4,  0.7, 8, -2,   5,   1.1]
new_population[1, :] = [-0.4, 2.7, 5, -1,   7,   0.1]
new_population[2, :] = [-1,   2,   2, -3,   2,   0.9]
new_population[3, :] = [4,    7,   12, 6.1, 1.4, -4]
new_population[4, :] = [3.1,  4,   0,  2.4, 4.8,  0]
new_population[5, :] = [-2,   3,   -7, 6,   3,    3]
"""

best_outputs = []
num_generations = 100
for generation in range(num_generations):
    #print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(equation_inputs, new_population)
    #print("Fitness")
    #print(fitness)

    best_outputs.append(
        numpy.max(numpy.sum(new_population * equation_inputs, axis=1)))
    # The best result in the current iteration.
    #print("Best result : ", numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)
    #print("Parents")
    #print(parents)

    # Generating next generation using crossover.
sol_per_pop = 8
num_parents_mating = 4

""" Defining the population size."""
pop_size = (sol_per_pop,num_weights)
"""Creating the initial population."""
new_population = np.random.uniform(low=-500, high=500, size=pop_size)
#print("POPULATION \n" , new_population)

""" Performing GA"""
best_outputs = []
num_generations = 100
for generation in range(num_generations):
    print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(function_inputs, new_population)
    print("Fitness")
    print(fitness)

    best_outputs.append(np.max(np.sum(new_population * function_inputs, axis=1)))
    # The best result in the current iteration.
    print("Best result : ", np.max(np.sum(new_population * function_inputs, axis=1)))

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)
    print("Parents")
    print(parents)

    # Generating next generation using crossover.
    offspring_crossover = ga.crossover(parents,
Example #7
0
sol_per_pop = 8
# Mating pool size:
num_parents_mating = 4

# Defining the population size.
pop_size = (sol_per_pop, num_weights)
# Creating the weight.
weight = numpy.random.uniform(low=-1.0, high=1.0, size=pop_size)
print(weight)

best_outputs = []
num_generations = 10
for generation in range(num_generations):
    print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(equation_inputs, weight)
    print("Fitness")
    print(fitness)

    best_outputs.append(numpy.max(numpy.sum(weight * equation_inputs, axis=1)))
    # The best result in the current iteration.
    print("Best result : ",
          numpy.max(numpy.sum(weight * equation_inputs, axis=1)))

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(weight, fitness, num_parents_mating)
    print("Parents")
    print(parents)

    # Generating next generation using crossover.
    offspring_crossover = ga.crossover(
def run_ga(file_name, sol_per_pop=8, num_parents_mating=4,):
    """
    The y=target is to maximize this equation:
        y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6
        where (x1,x2,x3,x4,x5,x6)= pizza slices
        What are the best values for the 6 weights w1 to w6?
        Weights can only be 0 (absent) and 1(included)
        We are going to use the genetic algorithm for the best possible values after a number of generations.
        Genetic algorithm parameters:
        Mating pool size
        Population size
    """
    try:
        f = open("data/" + file_name, "r")
        if f.mode == 'r':
            f1 = f.readlines()
            for row_index in range(0, 2):
                if row_index == 0:
                    max_val = int(f1[row_index].split(' ')[0])
                elif row_index == 1:
                    eq_inputs = [int(val) for val in f1[row_index].split()]
    except FileNotFoundError:
        print('Can not find the file')
    finally:
        f.close()

    # Number of the weights we are looking to optimize.
    num_weights = len(eq_inputs)

    # Defining the population size.
    pop_size = (sol_per_pop,
                num_weights)
    # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
    # Creating the initial population.
    new_population = numpy.random.randint(low=0, high=2, size=pop_size)
    if VERBOSE:
        print(new_population)

    best_outputs = []
    num_generations = 1000
    for generation in range(num_generations):
        if VERBOSE:
            print("Generation : ", generation)
        # Measuring the fitness of each chromosome in the population.
        fitness_val = ga.cal_pop_fitness(eq_inputs, new_population, max_val)
        if VERBOSE:
            print("Fitness")
            print(fitness_val)

        best_outputs.append(numpy.max(numpy.sum(new_population * eq_inputs, axis=1)))
        # The best result in the current iteration.
        if VERBOSE:
            print("Best result : ", numpy.max(numpy.sum(new_population * eq_inputs, axis=1)))

        # Selecting the best parents in the population for mating.
        parents = ga.select_mating_pool(new_population, fitness_val,
                                        num_parents_mating)
        if VERBOSE:
            print("Parents")
            print(parents)

        # Generating next generation using crossover.
        offspring_crossover = ga.crossover(parents,
                                           offspring_size=(pop_size[0] - parents.shape[0], num_weights))
        if VERBOSE:
            print("Crossover")
            print(offspring_crossover)

        # Adding some variations to the offspring using mutation.
        offspring_mutation = ga.mutation(offspring_crossover, num_mutations=2)
        if VERBOSE:
            print("Mutation")
            print(offspring_mutation)

        # Creating the new population based on the parents and offspring.
        new_population[0:parents.shape[0], :] = parents
        new_population[parents.shape[0]:, :] = offspring_mutation

    # Getting the best solution after iterating finishing all generations.
    # At first, the fitness is calculated for each solution in the final generation.
    fitness_val = ga.cal_pop_fitness(eq_inputs, new_population, max_val)
    # Then return the index of that solution corresponding to the best fitness.
    best_match_idx = numpy.where(fitness_val == numpy.max(fitness_val))

    best_match_idx = best_match_idx[0][0]
    if VERBOSE:
        print("Best solution : ", new_population[best_match_idx, :])
        print("Best solution fitness : ", fitness_val[best_match_idx])
        print('Max is %s', max_val)
        print('Pizza Slices are %s ', str(eq_inputs))
    return new_population[best_match_idx, :], fitness_val[best_match_idx], max_val, str(eq_inputs)

    if VIS:
        matplotlib.pyplot.plot(best_outputs)
        matplotlib.pyplot.xlabel("Iteration")
        matplotlib.pyplot.ylabel("Fitness")
        matplotlib.pyplot.show()
Example #9
0
        temp = matrix_b[i, 0]
        matrix_b[i, 0] = matrix_B[i, 0]
        matrix_B[i, 0] = temp
matrix_b = matrix_b * (-1)
new_population = numpy.concatenate((matrix_A, matrix_a, matrix_B, matrix_b),
                                   axis=1)
print(new_population)

num_generations = 40
price_previous = None

for generation in range(num_generations):
    print("Generation : ", (generation + 1))
    print("Initial generation : \n", (new_population))
    # Measing the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(p_naut, new_population, (generation + 1),
                                 price_previous)
    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)
    print("Selected parents to mate : \n", (parents))
    # Generating next generation using crossover.
    offspring_crossover = ga.crossover(
        parents, offspring_size=(pop_size[0] - parents.shape[0], num_coeff))
    print("After crossover offspring: \n", (offspring_crossover))
    # Adding some variations to the offsrping using mutation.
    offspring_mutation = ga.mutation(offspring_crossover)
    print("After mutation : \n", (offspring_mutation))
    # Creating the new population based on the parents and offspring.
    new_population[0:parents.shape[0], :] = parents
    new_population[parents.shape[0]:, :] = offspring_mutation
    print("New generation : \n", (new_population))
import numpy
import ga
equation_inputs = [4, -2, 3.5, 5, -11, -4.7]
num_wts = 6
#CREATING INITIAL POPULATION
sol_per_pop = 8
pop_size = (sol_per_pop, num_wts)  #8*6
new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)  #8*6
#STARTING GA
num_generations = 50
num_parents_mating = 4
for generation in range(num_generations):
    print('Generation ::', generation + 1)
    # 1. Measuring the fitness of each chromosome
    fitness = ga.cal_pop_fitness(equation_inputs,
                                 new_population)  #1*8 since we have taken
    # 8 solution per population i.e 8 chromosomes(solution) so 8 fitness values
    # are generated

    # 2. Selecting the best parents in the population for mating
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)  #4*6
    # since we choose 4 parents and each parents i.e chromosome have 6 genes so 4*6

    #-----------MATING---TO----GENERATE----OFFSPRING-------------#

    # 3. Generating next generation using crossover
    offspring_size = (pop_size[0] - parents.shape[0], num_wts)  #4*6
    offspring_crossover = ga.crossover(parents, offspring_size)

    # 4. Adding some variations to the offsrping using mutation
Example #11
0
print(new_Chromosome)
"""
new_Chromosome[0, :] = [12,  05,  23,  08]
new_Chromosome[1, :] = [02,  21,  18,  03]
new_Chromosome[2, :] = [10,  04,  13,  14]
new_Chromosome[3, :] = [20,  01,  10,  06]
new_Chromosome[4, :] = [01,  04,  13,  19]
new_Chromosome[5, :] = [20,  05,  17,  01]
"""

best_outputs = []
num_generations = 1000
for generation in range(num_generations):
    print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the Chromosome.
    fitness = ga.cal_pop_fitness(equation_inputs, new_Chromosome)
    print("Fitness")
    print(fitness)

    best_outputs.append(
        numpy.max(numpy.sum(new_Chromosome * equation_inputs, axis=1)))
    # The best result in the current iteration.
    print("Best result : ",
          numpy.max(numpy.sum(new_Chromosome * equation_inputs, axis=1)))

    # Selecting the best parents in theChromosomen for mating.
    parents = ga.select_mating_pool(new_Chromosome, fitness,
                                    num_parents_mating)
    print("Parents")
    print(parents)
Example #12
0
num_parents_mating = 4  # Number of parents inside the mating pool.
num_mutations = 3  # Number of elements to mutate.

# Defining the population shape.
pop_shape = (sol_per_pop, num_feature_elements)

# Creating the initial population.
new_population = numpy.random.randint(low=0, high=2, size=pop_shape)
print(new_population.shape)

best_outputs = []
num_generations = 100
for generation in range(num_generations):
    print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(new_population, data_inputs, data_outputs,
                                 train_indices, test_indices)

    best_outputs.append(numpy.max(fitness))
    # The best result in the current iteration.
    print("Best result : ", best_outputs[-1])

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)

    # Generating next generation using crossover.
    offspring_crossover = ga.crossover(
        parents,
        offspring_size=(pop_shape[0] - parents.shape[0], num_feature_elements))

    # Adding some variations to the offspring using mutation.
Example #13
0
num_parents_mating = 6

# Defining the population size.
pop_size = (
    sol_per_pop, ass_dim
)  # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
#Creating the initial population.
new_population = np.random.randint(1, ass_type_dim, size=pop_size)
print(new_population)

num_generations = 20

for generation in range(num_generations):
    print("Generation : ", generation)
    # Measing the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(rl1, new_population)

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)

    # Generating next generation using crossover.
    offspring_crossover = ga.crossover(
        parents, offspring_size=(pop_size[0] - parents.shape[0], ass_dim))

    # Adding some variations to the offsrping using mutation.
    offspring_mutation = ga.mutation(offspring_crossover, ass_type_dim,
                                     ass_dim)

    # Creating the new population based on the parents and offspring.
    new_population[0:parents.shape[0], :] = parents
Example #14
0
print(new_population)
new_populationMasq = numpy.random.uniform(low=4.0, high=100.0, size=pop_size)
print(new_population)
new_populationMed = numpy.random.uniform(low=4.0, high=100.0, size=pop_size)
print(new_population)
new_populationTest = numpy.random.uniform(low=4.0, high=100.0, size=pop_size)
print(new_population)
new_populationVeh = numpy.random.uniform(low=4.0, high=100.0, size=pop_size)
print(new_population)

num_generations = 5
for generation in range(num_generations):
    print("Generation : ", generation)

    # Measing the fitness of each chromosome in the population. for each variables or optim axes
    fitness = ga.cal_pop_fitness(equation_inputs, new_population)
    #fitnessY1 = ga.cal_pop_fitness(equation_inputs, new_population)
    fitnessY1 = ga.cal_pop_fitness(equation_inputsLits, new_populationLits)
    fitnessY2 = ga.cal_pop_fitness(equation_inputsResp, new_populationResp)
    fitnessY3 = ga.cal_pop_fitness(equation_inputsMasq, new_populationMasq)
    fitnessY4 = ga.cal_pop_fitness(equation_inputsMed, new_populationMed)
    fitnessY5 = ga.cal_pop_fitness(equation_inputsTest, new_populationTest)
    fitnessY6 = ga.cal_pop_fitness(equation_inputsVeh, new_populationVeh)

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)
    parentsY1 = ga.select_mating_pool(new_populationLits, fitnessY1,
                                      num_parents_mating)
    parentsY2 = ga.select_mating_pool(new_populationResp, fitnessY2,
                                      num_parents_mating)
Example #15
0
new_population = numpy.random.uniform(low=-10.0, high=10.0, size=pop_size)

for i in range(11):
    new_population[0, i] = overfit_wt[i]

print("this is the new population when overfit guy is just added",
      new_population.tolist())

num_generations = 10

for generation in range(num_generations):
    print("Generation : ", generation)

    # Measing the fitness of each chromosome in the population.

    fitness = ga.cal_pop_fitness(new_population)

    # Selecting the best parents in the population for mating.
    parents = ga.select_mating_pool(new_population, fitness,
                                    num_parents_mating)

    print("Parents allowed to mate in this generation: ", parents)

    # Generating next generation using crossover.
    # offspring_crossover = ga.crossover(parents,
    #                                    offspring_size=(pop_size[0]-parents.shape[0], num_weights))
    offspring_crossover = ga.crossover(parents,
                                       offspring_size=(num_children_to_take,
                                                       num_weights))

    print("offsprings crossover length:", len(offspring_crossover))
Example #16
0
def calW(qx, qy, num_generations):
    # Inputs of the equation.
    equation_inputs = [4, -2, 3.5, 5, -11, -4.7]

    # Number of the weights we are looking to optimize.
    num_weights = 6
    """
    Genetic algorithm parameters:
        Mating pool size
        Population size
    """
    sol_per_pop = 8
    num_parents_mating = 4

    # Defining the population size.
    pop_size = (
        sol_per_pop, num_weights
    )  # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
    #Creating the initial population.
    new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)
    #print(new_population)

    #my graph

    for generation in range(num_generations):
        time.sleep(1)
        print("Generation : ", generation)
        # Measing the fitness of each chromosome in the population.
        fitness = ga.cal_pop_fitness(equation_inputs, new_population)

        # Selecting the best parents in the population for mating.
        parents = ga.select_mating_pool(new_population, fitness,
                                        num_parents_mating)

        # Generating next generation using crossover.
        offspring_crossover = ga.crossover(
            parents,
            offspring_size=(pop_size[0] - parents.shape[0], num_weights))

        # Adding some variations to the offsrping using mutation.
        offspring_mutation = ga.mutation(offspring_crossover)

        # Creating the new population based on the parents and offspring.
        new_population[0:parents.shape[0], :] = parents
        new_population[parents.shape[0]:, :] = offspring_mutation

        # The best result in the current iteration.
        br = numpy.max(numpy.sum(new_population * equation_inputs, axis=1))
        ##print("Best result : ",br )

        qx.put(generation)
        qy.put(br)

    # Getting the best solution after iterating finishing all generations.
    #At first, the fitness is calculated for each solution in the final generation.
    fitness = ga.cal_pop_fitness(equation_inputs, new_population)
    # Then return the index of that solution corresponding to the best fitness.
    best_match_idx = numpy.where(fitness == numpy.max(fitness))

    print("Best solution : ", new_population[best_match_idx, :])
    print("Best solution fitness : ", fitness[best_match_idx])
    sol_per_pop.append(new_population)

for i in range(len(sol_per_pop)):
    print(sol_per_pop[i])

i = 1
j = 1
print(pop_size)
print(sol_per_pop[i][j])

best_outputs = []
num_generations = 100
for generation in range(num_generations):
    print("Generation : ", generation)
    # Measuring the fitness of each chromosome in the population.
    fitness = ga.cal_pop_fitness(sol_per_pop, machine, power)
    print("Fitness")
    print(fitness)

    # Selecting the best parents in the population for mating.
    bestparents = ga.select_mating_pool(fitness, sol_per_pop)
    print(bestparents)

    # Generating next generation using crossover.
    ga.crossover(
        sol_per_pop, power, population, machine
    )  # atualiza a sol_per_pop com os melhores pais e os filhos gerados

    # Adding some variations to the offspring using mutation.
    ga.mutation(sol_per_pop, machine)