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)
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, :])
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)
def main(): if len(sys.argv) != 4 or sys.argv[1] not in ['1', '2', '3']: print( "Please, provide an execution mode as an argument (1, 2 or 3) and a number of generations and population size" ) print("Example: python3 optimal-pixel-plant.py 2 500 10") return execution_mode = int(sys.argv[1]) rulesManager = RulesManager(execution_mode) pop_size = int(sys.argv[3]) new_population = [] for i in range(pop_size): new_population.append(PixelPlant(rulesManager)) new_population[i].genRandom() num_generations = int(sys.argv[2]) fittestPixelPlant = None for gen in range(num_generations): print("Generation", gen + 1) fitness = ga.calc_pop_fitness(new_population) parents = ga.select_mating_pool(new_population, fitness, len(new_population) // 2) offspring_crossover = ga.crossover(parents, pop_size - len(parents)) ga.mutation(offspring_crossover) new_population[0:len(parents)] = parents new_population[len(parents):] = offspring_crossover print("Best result after generation", gen + 1, ":", parents[0].getScore()) fittestPixelPlant = parents[0] # Show fittest result img.showTree(fittestPixelPlant.toImage())
for generation in range(num_generations): print("Generation : ", generation) # Measuring the fitness of each chromosome in the population. fitness = Faculty_Fitness.cal_pop_fitness_hard(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. offspring_crossover = ga.crossover( parents, offspring_size=(pop_size[0] - parents.shape[0], num_weights)) print("Crossover") print(offspring_crossover) # Adding some variations to the offspring using mutation. offspring_mutation = ga.mutation(offspring_crossover, num_mutations=2) print("Mutation") print(offspring_mutation) # Creating the new population based on the parents and offspring.
print("Generation : ", generation) # converting the solutions from being vectors to matrices. pop_weights_mat = ga.vector_to_mat(pop_weights_vector, pop_weights_mat) # Measuring the fitness of each chromosome in the population. fitness = ANN.fitness(pop_weights_mat, data_inputs, data_outputs, activation="sigmoid") accuracies[generation] = fitness[0] print("Fitness") print(fitness) # Selecting the best parents in the population for mating. parents = ga.select_mating_pool(pop_weights_vector, fitness.copy(), num_parents_mating) print("Parents") print(parents) # Generating next generation using crossover. offspring_crossover = ga.crossover( parents, offspring_size=(pop_weights_vector.shape[0] - parents.shape[0], pop_weights_vector.shape[1])) print("Crossover") print(offspring_crossover) # Adding some variations to the offsrping using mutation. offspring_mutation = ga.mutation(offspring_crossover, mutation_percent=mutation_percent) print("Mutation")
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])
# Convert all individuals to vector instead of matrix population = [ann.weights_to_vec(individual) for individual in population] population = np.array(population) # Compute stats avg_targets.append(sum(targets) / float(len(targets))) best_targets.append(min(targets)) print("Best\t", best_targets[-1]) print("Worst\t", max(targets)) print("Mean\t", avg_targets[-1]) print("Variance", np.var(targets)) print() # Compute next generation parents = ga.select_mating_pool(population, targets, N_PARENTS) offspring = ga.crossover( parents, offspring_size=(population.shape[0] - parents.shape[0], population.shape[1])) offspring = ga.mutate(offspring, MUTATION_RATE) population[:N_PARENTS] = parents population[N_PARENTS:] = offspring # Put back into matrix form population = [ann.vec_to_mat(**ann_params, vec=vec) for vec in population] time_passed = time.time() - start print('Generation took {0:.4f} seconds.'.format(time_passed)) # Save population to disk with open("ga_population.csv", mode='w') as file:
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( parents, offspring_size=(pop_size[0] - parents.shape[0], num_weights)) print("Crossover") print(offspring_crossover) # Adding some variations to the offspring using mutation. # Default mutation number is 1. In this case, we use 2. offspring_mutation = ga.mutation(offspring_crossover, num_mutations=2) print("Mutation") print(offspring_mutation)
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()
'avg_fitness': avg_fitness, 'avg_games': avg_games, 'max_fitness': population[0].fitness, 'max_games': max_games_won }) print( f"Generation: {gen}, Avg Fitness: {avg_fitness}, Avg Games Won: {avg_games}, Max Fitness: {population[0].fitness}, Max Games Won: {max_games_won}" ) # Alter mutation intensity based on closeness to maximum solution (i.e. big mutations at start, small when nearing solution) current_mutation_delta = mutation_delta * (1 - (max_games_won / max_games)) #current_mutation_delta = mutation_delta * (1 - (gen / generations)) parents = ga.select_mating_pool(population, len(population) // 2) children = ga.crossover(parents, population_size - len(parents), 10, ga.intermediate_crossover, crossover_rate=0.5, extra_range=0.25) children = ga.mutate(children, mutation_rate, current_mutation_delta) population = np.append(parents, children) try: with open("500-smartgreedy.csv", 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_header) writer.writeheader() for data in dict_data:
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) # Generating next generation using crossover. offspring_crossover = ga.crossover( parents, offspring_size=(pop_size[0] - parents.shape[0], num_weights)) print("Crossover") print(offspring_crossover) # Adding some variations to the offspring using mutation. offspring_mutation = ga.mutation(offspring_crossover, num_mutations=2) print("Mutation") print(offspring_mutation) # Creating the new Chromosome based on the parents and offspring.
def start_ga(self, *args): best_outputs = [] best_outputs_fitness = [] if (self.pop_created == 0): print( "No Population Created Yet. Create the initial Population by Pressing the \"Initial Population\" " "Button in Order to Call the initialize_population() Method At First." ) self.num_attacks_Label.text = "Press \"Initial Population\"" return num_generations = numpy.uint16(self.num_generations_TextInput.text) num_parents_mating = numpy.uint8(self.num_solutions / 2) # print("Number of Parents Mating : ", num_parents_mating) for generation in range(num_generations): print("\n** Generation # = ", generation, " **\n") # print("\nOld 1D Population : \n", self.population_1D_vector) # Measuring the fitness of each chromosome in the population. population_fitness, total_num_attacks = self.fitness( self.population) print("\nFitness : \n", population_fitness) max_fitness = numpy.max(population_fitness) max_fitness_idx = numpy.where( population_fitness == max_fitness)[0][0] print("\nMax Fitness = ", max_fitness) best_outputs_fitness.append(max_fitness) best_outputs.append(self.population_1D_vector[max_fitness_idx, :]) # The best result in the current iteration. # print("\nBest Outputs/Interations : \n", best_outputs) if (max_fitness == float("inf")): print("Best solution found") self.num_attacks_Label.text = "Best Solution Found" print("\n1D Population : \n", self.population_1D_vector) print("\n** Best soltuion IDX = ", max_fitness_idx, " **\n") best_outputs_fitness_array = numpy.array(best_outputs_fitness) best_outputs_array = numpy.array(best_outputs) numpy.save("best_outputs_fitness.npy", best_outputs_fitness) numpy.save("best_outputs.npy", best_outputs) print("\n** Data Saved Successfully **\n") break # Selecting the best parents in the population for mating. parents = ga.select_mating_pool(self.population_1D_vector, population_fitness, num_parents_mating) # print("\nSelected Parents : \n", parents) # Generating next generation using crossover. offspring_crossover = ga.crossover( parents, offspring_size=(self.num_solutions - parents.shape[0], 8)) # print("\nCrossover : \n", offspring_crossover) # Adding some variations to the offspring using mutation. offspring_mutation = ga.mutation( offspring_crossover, num_mutations=numpy.uint8(self.num_mutations_TextInput.text)) # print("\nMutation : \n", offspring_mutation) # Creating the new population based on the parents and offspring. self.population_1D_vector[0:parents.shape[0], :] = parents self.population_1D_vector[ parents.shape[0]:, :] = offspring_mutation # Convert the 1D vector population into a 2D matrix form in order to calculate the fitness values of the new population. # print("\n**********************************\n") self.vector_to_matrix()
def simulation(num_generations, target, population, num_parents_mating, pop_size, laplace, title): plot_fitness = numpy.zeros(num_generations) return_gen_values = [] new_population = population for generation in range(num_generations): ## print("\n Generation: ", generation) # Measuring the fitness of each chromosome in the population. fitness = ga.calculate_pop_fitness(target, new_population) ## print("Best Fitness this Generation: ", numpy.amax(fitness)) # 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. new_population = ga.probabilistic(parents, offspring_size=(pop_size), laplace=laplace) nsize = int(numpy.size(parents) / pop_size[1]) ## print("parents: ", parents) if laplace == 0: probability_model = ga.probabilistic_model(nsize, parents) elif laplace == 1: probability_model = ga.probabilistic_model_laplace(nsize, parents) else: sys.exit("Your selection is not supported, exiting program") plot_fitness[generation] += numpy.amax(fitness) return_gen_values.append( [generation, parents, probability_model, numpy.amax(fitness)]) # Output the best possible Fitness # ∑ target ## print("\nTarget Fitness: ", numpy.sum(target)) # Getting the best solution after iterating finishing all generations. # At first, the fitness is calculated for each solution in the final generation. fitness = ga.calculate_pop_fitness(target, new_population) # Then return the index of that solution corresponding to the best fitness. # If more than one solution fits that criteria all found solutions will be presented best_match_idx = numpy.where(fitness == numpy.amax(fitness)) ## print("Best solution(s): \n", new_population[best_match_idx, :]) # quick and clean plot # title is defined by the option chosen at the start # ylabel reflects the Fitness values # xlabel reflects Generation # Plot thus shows the fitness for each generation #plt.plot(plot_fitness) #plt.title(title) #plt.ylabel("Fitness") #plt.xlabel("Generation") #plt.show() return_value = [] return_value.append(new_population) return_value.append(return_gen_values) return_value.append(numpy.sum(target)) return_value.append(new_population[best_match_idx, :]) return_value.append(plot_fitness) # calculation for the best fitness in the final population return_value.append(numpy.amax(plot_fitness)) ## print("Best solution fitness : ", fitness[best_match_idx].max()) return return_value
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) parentsY3 = ga.select_mating_pool(new_populationMasq, fitnessY3, num_parents_mating) parentsY4 = ga.select_mating_pool(new_populationMed, fitnessY4, num_parents_mating) parentsY5 = ga.select_mating_pool(new_populationTest, fitnessY5, num_parents_mating) parentsY6 = ga.select_mating_pool(new_populationVeh, fitnessY6, num_parents_mating) # Generating next generation using crossover. offspring_crossover = ga.crossover(
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) # Best solution bestng = ga.bestsolution(sol_per_pop, machine, power) iterationlistng.append(bestng) # cria uma lista com os melhores NGs print("IMprimindo poulation")