def evolve(self): # create a new population new_population = Population(self.helper, pop=self.POPULATION_SIZE, tour=self.TOURNAMENT_SIZE, cross=self.CROSSOVER_RATE, mut=self.MUTATION_INVERSION_RATE) # the best fitting solution go to the next population automatically (ELITISM) best_fit = ga.get_best_fitness(self.chromosomes, self.helper) elit_chromosome = Chromosome() elit_chromosome.path = list(best_fit.path) elit_chromosome.trucks_used = list(best_fit.trucks_used) new_population.chromosomes.append(elit_chromosome) elit_unchanged = Chromosome() elit_unchanged.path = list(best_fit.path) elit_unchanged.trucks_used = list(best_fit.trucks_used) # crossover for _ in range((self.POPULATION_SIZE - 2) / 2): #print 'generating child ' + str(i) # must select parent 1 using TOURNAMENT SELECTION parent_1 = ga.tournament_selection(self.chromosomes, self.helper, self.TOURNAMENT_SIZE) # must select parent 2 using TOURNAMENT SELECTION parent_2 = ga.tournament_selection(self.chromosomes, self.helper, self.TOURNAMENT_SIZE) # crossover these chomosomes child = ga.crossover(parent_1, parent_2, self.helper, self.CROSSOVER_RATE) child.fitness = None # reset the fitness (it was calculated in the tournament and yet can mutate) child.deposit_distance = None new_population.chromosomes.append(child) child2 = ga.crossover(parent_2, parent_1, self.helper, self.CROSSOVER_RATE) child2.fitness = None # reset the fitness (it was calculated in the tournament and yet can mutate) child2.deposit_distance = None new_population.chromosomes.append(child2) # mutate ga.mutate(new_population.chromosomes, self.helper, self.MUTATION_INVERSION_RATE) # insert one unchanged elit (to keep the best if its the case) new_population.chromosomes.append(elit_unchanged) if len(new_population.chromosomes) != self.POPULATION_SIZE: print 'POPULATION WITH DFF SIZE' return new_population
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 generate(population, fitness): mutation = 0.1 new_population = [] sort_population = sortPopulation(population,total_clashes,n_queens) new_population = [x[0] for x in sort_population[:5000]] for i in range(len(new_population)): child = crossover(random.choice(new_population[:5000]),random.choice(new_population[:5000])) if random.random() < mutation: child = mutate(child) new_population.append(child) if fitness(child,total_clashes) == total_clashes: break new_population = sortPopulation(new_population,total_clashes,n_queens) return [x[0] for x in new_population]
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())
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()
line1 = live_plotter_xy(gen, fun, line1) if generation > 1: fit = np.concatenate([old_fitness, fitness]) index_selection = sorted(range(len(fit)), key=lambda k: fit[k]) #index_selection = np.argsort(np.concatenate(fitness,old_fitness)) pop = np.concatenate((old_population, new_population)) new_population = pop[index_selection[0:sol_per_pop], :] if generation % 1000 == 0: print("generation", generation, "with value=", np.min(fitness)) old_fitness[0:] = fitness[0:] # 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, n_cross_point, offspring_size=(int(parents.shape[0] / 2), genes * nr_bit_num)) # Adding some variations to the offspring using mutation. offspring_mutation = ga.mutation( pop_size[0] - offspring_crossover.shape[0], new_population, n_mut_point) # Creating the new population based on the parents and offspring. old_population = new_population new_population[0:int(parents.shape[0] / 2), :] = offspring_crossover new_population[int(parents.shape[0] / 2):, :] = offspring_mutation # The best result in the current iteration. # Getting the best solution after iterating finishing all generations. #At first, the fitness is calculated for each solution in the final generation. fitness = ga.foxholes(new_population, genes, nr_bit_num)
def mesh_perday(agent_active, week, ga_param, enc_dec, days, dim): options_days = [i for i in combinations(range(len(days) - 1), 3)] options_cap = np.random.randint(agent_active.shape[0], size=(5 * agent_active.shape[0], int(agent_active.shape[0] / 2))) lower_bounds = [0, 0] upper_bounds = [len(options_days) - 1, options_cap.shape[0]] t1_start = process_time() pop_size = ga_param[0] crossover_rate = ga_param[1] mutation_rate = ga_param[2] no_generations = ga_param[3] #300000000000 step_size = (upper_bounds[1] - lower_bounds[1]) * 0.001 #ga_param[4] rate = ga_param[5] computing_time = 30 # Each variable correspond to an agent no_variables = 2 # Initial population of genetic algoritm pop = np.zeros((pop_size, no_variables)) for s in range(pop_size): for h in range(no_variables): pop[s, h] = np.random.uniform(lower_bounds[h], upper_bounds[h]) extended_pop = np.zeros( (pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate, pop.shape[1])) A = [] a = 2 g = 0 #global_best = np.zeros((no_generations+1,no_variables)) global_best = pop[0] k = 0 # Evolution and new generation into the population while g <= no_generations: for i in range(no_generations): # crossover, mutation, fitness and local search function offspring1 = ga.crossover(pop, crossover_rate) offspring2 = ga.mutation(pop, mutation_rate) [fitness, ag1, ag2] = objective.objtv_day_functn(pop, options_days, options_cap, week, agent_active, enc_dec, dim) offspring3 = ga.local_search(pop, fitness, lower_bounds, upper_bounds, step_size, rate) step_size = step_size * 0.98 if step_size < (upper_bounds[1] - lower_bounds[1]) * 0.001: step_size = (upper_bounds[1] - lower_bounds[1]) * 0.001 # Put into the previous population the new generations extended_pop[0:pop_size] = pop extended_pop[pop_size:pop_size + crossover_rate] = offspring1 extended_pop[pop_size + crossover_rate:pop_size + crossover_rate + mutation_rate] = offspring2 extended_pop[pop_size + crossover_rate + mutation_rate:pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate] = offspring3 [fitness, ag1, ag2] = objective.objtv_day_functn(extended_pop, options_days, options_cap, week, agent_active, enc_dec, dim) pop = ga.selection(extended_pop, fitness, pop_size) print("Generation: ", g, ", current fitness value: ", min(fitness)) # Find the local minimum (local solution) #index = np.argmin(fitness) #current_best = extended_pop[index] #global_best[g]=current_best A.append(min(fitness)) g += 1 if i >= a: if sum(abs(np.diff(A[g - a:g]))) <= 0.005: index = np.argmin(fitness) current_best = extended_pop[index] pop = np.zeros((pop_size, no_variables)) for s in range(pop_size): #(pop_size - 1): for h in range(no_variables): pop[s, h] = np.random.uniform(lower_bounds[h], upper_bounds[h]) pop[pop_size - 1:pop_size] = current_best step_size = (upper_bounds[1] - lower_bounds[1]) * 0.02 global_best = np.vstack((global_best, current_best)) #k +=1 break # t1_stop = process_time() # time_elapsed = t1_stop - t1_start # if time_elapsed >= computing_time: # break # if time_elapsed >= computing_time: # break # Find the global minimum (global solution) [fitness, ag1, ag2] = objective.objtv_day_functn(global_best, options_days, options_cap, week, agent_active, enc_dec, dim) index = np.argmin(fitness) print("Best solution = ", np.ceil(global_best[index])) print("Best fitness value= ", min(fitness)) best = np.ceil(global_best[index]) #dife = diff[index] prog1 = ag1[index] prog2 = ag2[index] options_cap2 = {x for x in range(agent_active.shape[0])} options_cap2.difference_update(options_cap[int(best[1])]) training = enc_dec[5] rostrng1 = np.asarray(dim) rostrng2 = np.asarray(dim) for j in options_cap[int(best[1])]: for y in training: rostrng1[:][j][rostrng1[:][j] == y] = 1 for k in options_cap2: for z in training: rostrng2[:][k][rostrng2[:][k] == z] = 1 options_days2 = {x for x in range(len(week) - 1)} options_days2.difference_update(options_days[int(best[0])]) rostrng1_dict = {} rostrng2_dict = {} for rostrn in range(len(dim)): rostrng1_dict[rostrn] = rostrng1[rostrn] rostrng2_dict[rostrn] = rostrng2[rostrn] rostrng_total = {} for i in options_days[int(best[0])]: rostrng_total[i] = rostrng1_dict for p in options_days2: rostrng_total[p] = rostrng2_dict return rostrng_total
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: writer = csv.writer(file, delimiter=',') for i in population: writer.writerow([i])
def test_crossover(self): c1 = [1, 2, 3, 4, 2, 6] c2 = [6, 5, 3, 4, 2, 6] child = crossover(c1, c2) assert child[2:] == [3, 4, 2, 6]
'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: writer.writerow(data) except IOError: print("I/O error")
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()
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])
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 offspring_mutation = ga.mutation(offspring_crossover) # we successfully produced 4 offspring from the 4 selected parents and #we are ready to create the new population of the next generation #----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("The best value::", (numpy.max(numpy.dot(new_population, equation_inputs))))
optimal_ga = [] optimal_ls = [] for generation in range(num_generations): if len(population) == 1: break # print("Generation {} ".format(generation)) num_parents=min(num_parents, len(population) // 2) best_steps=ga.cal_fitness(population) parents=ga.generate_parents(ms_board, population, num_parents) parents_size=len(parents) offsprings_size=int(comb(parents_size,2)) offsprings=ga.crossover(parents, offsprings_size) #ga.mutation(offsprings,len(ms_board), len(ms_board[0])) # Create new population population=parents+offsprings ga.remove_redundant_clicks(population, all_uncovered_neighbors) # print('population = {}'.format(population)) # print('population shape = {}'.format(shape_of_population(population))) optimal_ga.extend(shape_of_population(population)) # best_steps=min(min(map(len, population)), best_steps) if best_steps < min(map(len, population)):
fitness = ga.popFitness(pop_exp, train_data) # Escolhendo os individuos para crossover pela roleta chromo_crossover = [] for i in range(len(pop_exp)): chromo1 = np.random.randint(low=0, high=len(pop_exp)) chromo2 = np.random.randint(low=0, high=len(pop_exp)) if (fitness[chromo1] >= fitness[chromo2]): chromo_crossover.append(pop_num[chromo2]) else: chromo_crossover.append(pop_num[chromo1]) # Crossover #print(chromo_crossover) for i in range(0, len(chromo_crossover) - 1, 2): temp1, temp2 = ga.crossover(chromo_crossover[i], chromo_crossover[i + 1], crossover_rate) chromo_crossover[i], chromo_crossover[i + 1] = temp1, temp2 #print(chromo_crossover) # Mutação new_pop_num = ga.popMutation(chromo_crossover, mutation_rate) pop_num = new_pop_num.copy() #print(new_pop_num) if len(pop_num) > 0: print('Generation: ', str(generation)) print(pop_num, pop_exp) print('Média fitness: ' + str(sum(fitness) / len(fitness)) + '\n\n') generation += 1 if min(fitness) < min_fitness: min_fitness = min(fitness)
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. offspring_mutation = ga.mutation(offspring_crossover, num_mutations=num_mutations) # 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 = ga.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices) # Then return the index of that solution corresponding to the best fitness.
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 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)
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( parents, offspring_size=(pop_size[0] - parents.shape[0], num_weights)) offspring_crossoverY1 = ga.crossover( parentsY1, offspring_size=(pop_size[0] - parentsY1.shape[0], num_weights)) offspring_crossoverY2 = ga.crossover( parentsY2, offspring_size=(pop_size[0] - parentsY2.shape[0], num_weights)) offspring_crossoverY3 = ga.crossover( parentsY3, offspring_size=(pop_size[0] - parentsY3.shape[0], num_weights)) offspring_crossoverY4 = ga.crossover( parentsY4, offspring_size=(pop_size[0] - parentsY4.shape[0], num_weights)) offspring_crossoverY5 = ga.crossover( parentsY5, offspring_size=(pop_size[0] - parentsY5.shape[0], num_weights))
def mesh_fds(agent_active, week, ga_param, enc_dec, rostrng_total, bounds_fds, novelties_aux_fds, new_nov_agent): fds_day = 1 if all([np.isnan(x) for x in agent_active[:, 3]]): fds_day = 0 if fds_day == 1: training = enc_dec[5][0] agent_sun = list(np.where(agent_active[:, 3] == 1)[0]) sat_train = set() for y in rostrng_total[5]: if training in rostrng_total[5][y]: sat_train.add(y) # try: # agent_sun = random.sample(sun,math.ceil(np.amax(week[6]))+8) # except: # agent_sun = list(sun.copy()) active_agent = {x for x in range(agent_active.shape[0])} agent_sat = list(np.where(agent_active[:, 3] == 2)[0]) sat_train.difference_update(agent_sun) agent_fds = [agent_sat, agent_sun] upp_bods = bounds_fds[1] low_bods_sat = np.zeros((1, len(agent_sat))) upp_bods_sat = np.zeros((1, len(agent_sat))) sat_nov = np.zeros((1, len(agent_sat)), dtype='O') count_sat = 0 for p in agent_sat: upp_bods_sat[0][count_sat] = upp_bods[p] sat_nov[0][count_sat] = new_nov_agent[p] count_sat += 1 low_bods_sun = np.zeros((1, len(agent_sun))) upp_bods_sun = np.zeros((1, len(agent_sun))) sun_nov = np.zeros((1, len(agent_sun)), dtype='O') count_sun = 0 for o in agent_sun: upp_bods_sun[0][count_sun] = upp_bods[o] sun_nov[0][count_sun] = new_nov_agent[o] count_sun += 1 upper_bounds_total = [upp_bods_sat[0], upp_bods_sun[0]] lower_bounds_total = [low_bods_sat[0], low_bods_sun[0]] new_nov = [sat_nov[0], sun_nov[0]] if fds_day == 0: upper_bounds_total = [bounds_fds[1]] lower_bounds_total = [bounds_fds[0]] new_nov = [new_nov_agent] agent_fds = [[x for x in range(agent_active.shape[0])]] pop_size = ga_param[0] crossover_rate = ga_param[1] mutation_rate = ga_param[2] no_generations = ga_param[3] step_size = ga_param[4] rate = ga_param[5] # Each variable correspond to an agent for k in range(5, 6 + fds_day): no_variables = len(agent_fds[k - 5]) upper_bounds = upper_bounds_total[k - 5] lower_bounds = lower_bounds_total[k - 5] nov_agent = new_nov[k - 5] # Initial population of genetic algoritm pop = np.zeros((pop_size, no_variables)) for s in range(pop_size): for h in range(no_variables): pop[s, h] = np.random.random_integers(lower_bounds[h], upper_bounds[h]) extended_pop = np.zeros((pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate, pop.shape[1])) g = 0 global_best = np.zeros((no_generations + 1, no_variables)) # Evolution and new generation into the population while g <= no_generations: # crossover, mutation, fitness and local search function offspring1 = ga.crossover(pop, crossover_rate) offspring2 = ga.mutation(pop, mutation_rate) [fitness, diff, ag, dim] = objective.objtv_gen_functn(pop, novelties_aux_fds, week[k - 5], nov_agent, enc_dec) offspring3 = ga.local_search(pop, fitness, lower_bounds, upper_bounds, step_size, rate) step_size = step_size * 0.98 if step_size < 1: step_size = 1 # Put into the previous population the new generations extended_pop[0:pop_size] = pop extended_pop[pop_size:pop_size + crossover_rate] = offspring1 extended_pop[pop_size + crossover_rate:pop_size + crossover_rate + mutation_rate] = offspring2 extended_pop[pop_size + crossover_rate + mutation_rate:pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate] = offspring3 [fitness, diff, ag, dim] = objective.objtv_gen_functn(extended_pop, novelties_aux_fds, week[k - 5], nov_agent, enc_dec) pop = ga.selection(extended_pop, fitness, pop_size) print("Generation: ", g, ", current fitness value: ", min(fitness)) # Find the local minimum (local solution) index = np.argmin(fitness) current_best = extended_pop[index] global_best[g] = current_best g += 1 # Find the global minimum (global solution) [fitness, diff, ag, dim] = objective.objtv_gen_functn(global_best, novelties_aux_fds, week[k - 5], nov_agent, enc_dec) index = np.argmin(fitness) print("Best solution = ", np.ceil(global_best[index])) print("Best fitness value= ", min(fitness)) best = np.ceil(global_best[index]) #dife = diff[index] prog = ag[index] nes = np.ceil(week[k]) # Plot the global solution plt.plot(prog, label="A. Programados") plt.plot(nes, label="A. Necesarios + 15%") plt.plot(nes / 1.15, label="A. Necesarios") plt.plot(nes / (1.15 * 1.1333333), label="Llamadas") plt.grid() plt.legend() plt.axis('equal') plt.xlabel('Bloque de tiempo') plt.ylabel('No asesores') plt.title('´programacion fds {}'.format(k - 5)) plt.show() dim = [] count_static = 0 for j in range(best.shape[0]): if nov_agent[j] == 'NO': assign = novelties_aux_fds[0][int(best[j])] dim.append(assign) elif nov_agent[j] == 'AM': assign = novelties_aux_fds[1][int(best[j])] dim.append(assign) elif nov_agent[j] == 'PM': assign = novelties_aux_fds[2][int(best[j])] dim.append(assign) elif nov_agent[j] == 'MAMA': assign = novelties_aux_fds[3][int(best[j])] dim.append(assign) elif nov_agent[j] == 'SEDE': assign = novelties_aux_fds[4][int(best[j])] dim.append(assign) elif nov_agent[j] == 'ESPECIAL': assign = novelties_aux_fds[5][int(best[j])] dim.append(assign) else: assign = novelties_aux_fds[6][count_static][int(best[j])] dim.append(assign) count_static += 1 rostrng = np.asarray(dim) rostrng_dict = {} if fds_day == 1: if k == 5: training = enc_dec[5] sat_no_train = active_agent.difference(sat_train) count_train = 0 for h in agent_sat: if h in sat_no_train: for y in training: rostrng[:][count_train][rostrng[:][count_train] == y] = 1 count_train += 1 for rostrn in range(len(dim)): rostrng_dict[agent_sat[rostrn]] = rostrng[rostrn] elif k == 6: training = enc_dec[5] for h in range(len(agent_sun)): for y in training: rostrng[:][h][rostrng[:][h] == y] = 1 for rostrn in range(len(dim)): rostrng_dict[agent_sun[rostrn]] = rostrng[rostrn] if fds_day == 0: for rostrn in range(len(dim)): rostrng_dict[agent_fds[0][rostrn]] = rostrng[rostrn] rostrng_total[k] = rostrng_dict return rostrng_total # def aux_cap(lunch_key,best,agent_active,week,bounds_Rtg,aux_cap,ga_param,novelties): # # Initial population of genetic algoritm # pop = np.zeros((pop_size,no_variables)) # for s in range(pop_size): # for h in range(no_variables): # pop[s,h] = np.random.random_integers(lower_bounds[h],upper_bounds[h]) # extended_pop = np.zeros((pop_size+crossover_rate+mutation_rate+2*no_variables*rate,pop.shape[1])) # g = 0 # global_best = np.zeros((no_generations+1,no_variables)) # # Evolution and new generation into the population # while g <= no_generations: # # crossover, mutation, fitness and local search function # offspring1 = ga.crossover(pop, crossover_rate) # offspring2 = ga.mutation(pop, mutation_rate) # [fitness,diff,ag,dim] = objective.objfun_aux_cap(pop,aux_cap,week[0],agent_active,lunch_key,best,novelties) # offspring3 = ga.local_search(pop, fitness, lower_bounds, upper_bounds, step_size, rate) # step_size = step_size*0.98 # if step_size<1: # step_size = 1 # # Put into the previous population the new generations # extended_pop[0:pop_size] = pop # extended_pop[pop_size:pop_size+crossover_rate] = offspring1 # extended_pop[pop_size+crossover_rate:pop_size+crossover_rate+mutation_rate]=offspring2 # extended_pop[pop_size+crossover_rate+mutation_rate:pop_size+crossover_rate+mutation_rate+2*no_variables*rate]=offspring3 # [fitness,diff,ag,dim] = objective.objfun_aux_cap(extended_pop,aux_cap,week[0],agent_active,lunch_key,best,novelties) # pop = ga.selection(extended_pop, fitness, pop_size) # print("Generation: ", g, ", current fitness value: ", min(fitness)) # # Find the local minimum (local solution) # index = np.argmin(fitness) # current_best = extended_pop[index] # global_best[g]=current_best # g +=1 # # Find the global minimum (global solution) # [fitness,diff,ag,dim] = objective.objfun_aux_cap(global_best,aux_cap,week[0],agent_active,lunch_key,best,novelties) # index = np.argmin(fitness) # print("Best solution = ", global_best[index]) # print("Best fitness value= ", min(fitness)) # best = np.ceil(global_best[index]) # #dife = diff[index] # prog = ag[index] # nes = np.ceil(week[0]) # return [best,prog,nes,dim] ### ------------------------------------------------------------------------------- ## Database Connection ### ------------------------------------------------------------------------------- # # Connect to the database "retencionfija_malla" # db = mysql.connector.connect( # host="localhost", # user="******", # password="", # database="retencionfija_malla" # ) # # Select into the database, all the information of agents active or work in home # cursor = db.cursor() # cursor.execute("SELECT name_ag FROM agent INNER JOIN state ON fk_idstate = idstate WHERE state_info='CONEXIÓN REMOTA' OR state_info='ACTIVO'") # state_db = cursor.fetchall() # state_db = np.array(state_db) #no_variables = state_db.shape[0] ### ------------------------------------------------------------------------------- ## steps of the GA ## -------------------------------------------------------------------------------- # a = 5 # if i >= a: # if sum(abs(np.diff(A[g-a:g])))<=0.05: # index = np.argmin(fitness) # current_best = extended_pop[index] # # pop = np.zeros((pop_size, no_variables)) # # for s in range(pop_size): # # for h in range(no_variables): # # pop[s,h]=np.random.uniform(lower_bounds[h],upper_bounds[h]) # step_size = 5 # global_best[k]=current_best # k +=1 # break # minim = {} # for t in range(dife.shape[0]-3): # if (dife[t] > 0 and dife[t+1] > 0 and dife[t+2] > 0 and dife[t+3] > 0): # minim[t]= np.min([dife[t], dife[t+1], dife[t+2], dife[t+3]]) # ### Plot about the evolution of the population # fig = plt.figure() # ax = fig.add_subplot() # fig.show() # plt.title('Evolutionary process of the objetive function value') # plt.xlabel('Iteration') # plt.ylabel('objetive function') # ax.plot(A,color='r') # fig.canvas.draw() # ax.set_xlim(left=max(0,g-no_generations),right = g+3) # plt.show()
def mesh_general(agent_active, maximum, bounds, novelties_aux_cap, ga_param, enc_dec): lower_bounds = bounds[0] upper_bounds = bounds[1] pop_size = ga_param[0] crossover_rate = ga_param[1] mutation_rate = ga_param[2] no_generations = ga_param[3] step_size = ga_param[4] rate = ga_param[5] # Each variable correspond to an agent no_variables = agent_active.shape[0] # Initial population of genetic algoritm pop = np.zeros((pop_size, no_variables)) for s in range(pop_size): for h in range(no_variables): pop[s, h] = np.random.random_integers(lower_bounds[h], upper_bounds[h]) extended_pop = np.zeros( (pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate, pop.shape[1])) g = 0 global_best = np.zeros((no_generations + 1, no_variables)) # Evolution and new generation into the population while g <= no_generations: # crossover, mutation, fitness and local search function offspring1 = ga.crossover(pop, crossover_rate) offspring2 = ga.mutation(pop, mutation_rate) [fitness, diff, ag, dim] = objective.objtv_gen_functn(pop, novelties_aux_cap, maximum, agent_active, enc_dec) offspring3 = ga.local_search(pop, fitness, lower_bounds, upper_bounds, step_size, rate) step_size = step_size * 0.98 if step_size < 1: step_size = 1 # Put into the previous population the new generations extended_pop[0:pop_size] = pop extended_pop[pop_size:pop_size + crossover_rate] = offspring1 extended_pop[pop_size + crossover_rate:pop_size + crossover_rate + mutation_rate] = offspring2 extended_pop[pop_size + crossover_rate + mutation_rate:pop_size + crossover_rate + mutation_rate + 2 * no_variables * rate] = offspring3 [fitness, diff, ag, dim] = objective.objtv_gen_functn(extended_pop, novelties_aux_cap, maximum, agent_active, enc_dec) pop = ga.selection(extended_pop, fitness, pop_size) print("Generation: ", g, ", current fitness value: ", min(fitness)) # Find the local minimum (local solution) index = np.argmin(fitness) current_best = extended_pop[index] global_best[g] = current_best g += 1 # Find the global minimum (global solution) [fitness, diff, ag, dim] = objective.objtv_gen_functn(global_best, novelties_aux_cap, maximum, agent_active, enc_dec) index = np.argmin(fitness) print("Best solution = ", np.ceil(global_best[index])) print("Best fitness value= ", min(fitness)) best = np.ceil(global_best[index]) #dife = diff[index] prog = ag[index] nes = np.ceil(maximum) dim = [] count_static = 0 for j in range(best.shape[0]): if agent_active[j] == 'NO': assign = novelties_aux_cap[0][int(best[j])] dim.append(assign) elif agent_active[j] == 'AM': assign = novelties_aux_cap[1][int(best[j])] dim.append(assign) elif agent_active[j] == 'PM': assign = novelties_aux_cap[2][int(best[j])] dim.append(assign) elif agent_active[j] == 'MAMA': assign = novelties_aux_cap[3][int(best[j])] dim.append(assign) elif agent_active[j] == 'SEDE': assign = novelties_aux_cap[4][int(best[j])] dim.append(assign) elif agent_active[j] == 'ESPECIAL': assign = novelties_aux_cap[5][int(best[j])] dim.append(assign) else: assign = novelties_aux_cap[6][count_static][int(best[j])] dim.append(assign) count_static += 1 # Plot the global solution plt.plot(prog, label="A. Programados") plt.plot(nes, label="A. Necesarios + 15%") plt.plot(nes / 1.15, label="A. Necesarios") plt.plot(nes / (1.15 * 1.1333333), label="Llamadas") plt.grid() plt.legend() plt.axis('equal') plt.xlabel('Bloque de tiempo') plt.ylabel('No asesores') plt.title('programacion maxima entre semana') plt.show() return [best, prog, nes, dim]
# 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)) print("offspring crossover is as follows -", offspring_crossover) # Adding some variations to the offsrping using mutation. offspring_mutation = ga.mutation(offspring_crossover) print("Offspring_mutation is as follows - ", 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 new_population = ga.create_new_pop(parents, offspring_mutation, num_parents_to_take, num_children_to_take)
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") print(offspring_mutation) # Creating the new population based on the parents and offspring. pop_weights_vector[0:parents.shape[0], :] = parents pop_weights_vector[parents.shape[0]:, :] = offspring_mutation pop_weights_mat = ga.vector_to_mat(pop_weights_vector, pop_weights_mat)
k = 1 # Number of Generations Global_fitness = [] for i in range(k): # Evaluate Fitness fitness = ga.fitness(equation_inputs, new_population) Global_fitness.append(max(fitness)) print('Fitness:\n', fitness.transpose(), '\n') # Select Best Fitness parents = ga.select_parents(new_population, fitness, num_parents) print('Parents Selected:\n', parents, '\n') # Crossover offspring_cross = ga.crossover(parents, num_kromo) print('crossover:\n', offspring_cross, '\n') # Mutation mut_prob = 0.4 offspring_mut = ga.mutation(offspring_cross, span, mut_prob) print('Mutation:\n', offspring_mut, '\n') # Pop new_population = np.concatenate((parents, offspring_mut)) print('Generation ', i, ':\n', new_population) #print(Global_fitness) plt.plot(Global_fitness, 'b--')
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") print(sol_per_pop) print("Tempo de execução %s seconds " % (time.time() - start_time)) # importing the required module import matplotlib.pyplot as plt
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. 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 = Faculty_Fitness.cal_pop_fitness_hard(equation_inputs, 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)) price_previous = ga.price(p_naut, new_population, generation + 1) fitness = ga.cal_pop_fitness(p_naut, new_population, generation + 2, price_previous) max_fitness_idx = numpy.where(fitness == numpy.min(fitness)) max_fitness_idx = max_fitness_idx[0][0] print("Best result : ", new_population[max_fitness_idx, :])