def initialize_population(self, *args): self.num_solutions = 100 # print("Number of Solutions within the Population : ", self.num_solutions) self.reset_board_text() self.population_1D_vector = numpy.zeros(shape=(self.num_solutions, 8)) # Each solution is represented as a row in this array. If there are 5 rows, then there are 5 solutions. # Creating the initial population RANDOMLY as a set of 1D vectors. for solution_idx in range(self.num_solutions): initial_queens_y_indices = numpy.random.rand(8)*8 initial_queens_y_indices = initial_queens_y_indices.astype(numpy.uint8) self.population_1D_vector[solution_idx, :] = initial_queens_y_indices self.vector_to_matrix() # print("Population 1D Vectors : ", self.population_1D_vector) # print("Population 2D Matrices : ", self.population) self.pop_created = 1 # indicates that the initial population is created in order to enable drawing solutions on GUI. self.num_attacks_Label.text = "Initialized" self.ga_instance = pygad.GA(num_generations=200, num_parents_mating=50, fitness_func=fitness, num_genes=8, initial_population=self.population_1D_vector, mutation_percent_genes=0.01, mutation_type="random", mutation_num_genes=1, mutation_by_replacement=True, random_mutation_min_val=0.0, random_mutation_max_val=8.0, on_generation=on_gen_callback, delay_after_gen=0.2)
def obtenerSolucion(): global listaTotal, noLeGustaOrdenado, maxNoGustaIngredientesIni, maxNoGustaIngredientesFin, profundidadIngredientesIni, profundidadIngredientesFin mejorSol = [] ga_instance = pygad.GA( gene_type=int, init_range_low=0, init_range_high=2, num_generations=1000, num_parents_mating=2, fitness_func=scoreSolucion, sol_per_pop=8, num_genes=len(noLeGustaOrdenado), #initial_population=[1]*(len(listaTotal)), mutation_percent_genes=0.01, mutation_type="random", mutation_num_genes=3, mutation_by_replacement=True, random_mutation_min_val=0.0, random_mutation_max_val=1.0) ga_instance.run() solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Parameters of the best solution : {solution}".format( solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format( solution_fitness=solution_fitness)) print(solution) mejorSol = solution return mejorSol
def genetic_algorithm(function, Orders): fitness = 0 count = 0 Length = sum(Orders) def fitness_func(solution, solution_idx): fitness = 1.0 / function(solution) return fitness ga_instance = pygad.GA(num_generations=50, sol_per_pop=8, num_parents_mating=4, num_genes=Length, fitness_func=fitness_func) f = 128 while fitness < 1 / 1e-2 and count < f: ga_instance.run() res = ga_instance.best_solution() x, fitness, solution_idx = res count += 1 return x
def genetic_alg(cls, iteration_num, parent_num, fitness, number_of_solutions, num_genes, crossover_probability, mutation_probability, after_mutation_func): # initial_population is built by sol_per_pop and num_genes # num_genes = Number of genes in the solution / chromosome ga_instance = pygad.GA(num_generations=iteration_num, num_parents_mating=parent_num, fitness_func=fitness, sol_per_pop=number_of_solutions, num_genes=num_genes, gene_type=float, init_range_low=0.0, init_range_high=1.0, parent_selection_type="rws", keep_parents=0, crossover_type="single_point", crossover_probability=crossover_probability, mutation_type="random", mutation_probability=mutation_probability, mutation_by_replacement=False, random_mutation_min_val=0.0, random_mutation_max_val=1.0, on_mutation=after_mutation_func) ga_instance.run() solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Parameters of the best solution : {solution}".format(solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness)) print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx)) filename = 'genetic' ga_instance.save(filename=filename) loaded_ga_instance = pygad.load(filename=filename) return loaded_ga_instance.best_solution()
def prepare_GA(server_data): global keras_ga population_weights = server_data["population_weights"] model_json = server_data["model_json"] num_solutions = server_data["num_solutions"] model = tensorflow.keras.models.model_from_json(model_json) keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=num_solutions) keras_ga.population_weights = population_weights population_vectors = keras_ga.population_weights # To prepare the initial population, there are 2 ways: # 1) Prepare it yourself and pass it to the initial_population parameter. This way is useful when the user wants to start the genetic algorithm with a custom initial population. # 2) Assign valid integer values to the sol_per_pop and num_genes parameters. If the initial_population parameter exists, then the sol_per_pop and num_genes parameters are useless. initial_population = population_vectors.copy() num_parents_mating = 4 # Number of solutions to be selected as parents in the mating pool. num_generations = 50 # Number of generations. mutation_percent_genes = 5 # Percentage of genes to mutate. This parameter has no action if the parameter mutation_num_genes exists. ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, mutation_percent_genes=mutation_percent_genes) return ga_instance
def train_by_gann(): global data_inputs, data_outputs, keras_ga, model # pygad train # Create an instance of the pygad.kerasga.KerasGA class to build the initial population. keras_ga = pygad.kerasga.KerasGA( model=model, num_solutions=20) # Prepare the PyGAD parameters. Check the documentation for more information: https://pygad.readthedocs.io/en/latest/README_pygad_ReadTheDocs.html#pygad-ga-class num_generations = 50 # Number of generations. # Number of solutions to be selected as parents in the mating pool. num_parents_mating = 10 # Initial population of network weights. initial_population = keras_ga.population_weights parent_selection_type = "sus" # Type of parent selection. crossover_type = "scattered" # Type of the crossover operator. mutation_type = "scramble" # Type of the mutation operator. # Percentage of genes to mutate. This parameter has no action if the parameter mutation_num_genes exists. mutation_percent_genes = 50 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing. keep_parents = 5 # Create an instance of the pygad.GA class ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, parent_selection_type=parent_selection_type, crossover_type=crossover_type, mutation_type=mutation_type, mutation_percent_genes=mutation_percent_genes, keep_parents=keep_parents, on_generation=callback_generation) # Start the genetic algorithm evolution. ga_instance.run() # Returning the details of the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution() # Fetch the parameters of the best solution. best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution) model.set_weights(best_solution_weights) predictions = model.predict(data_inputs) # print("Predictions : \n", predictions) # Calculate the categorical crossentropy for the trained model. cce = tensorflow.keras.losses.CategoricalCrossentropy() mse = tensorflow.keras.losses.MeanSquaredError() print("Categorical Crossentropy : ", cce(data_outputs[0], predictions[0]).numpy()) print("MeanSquaredError : ", mse(data_outputs[1], predictions[1]).numpy()) # Calculate the classification accuracy for the trained model. ca = tensorflow.keras.metrics.CategoricalAccuracy() ca.update_state(data_outputs[0], predictions[0]) accuracy = ca.result().numpy() print("Accuracy : ", accuracy)
def fit(self): parameters = self.get_genetic_parameters() if os.path.exists(self.path['GA'] + '.pkl'): self.ga = pygad.load(self.path['GA']) self.ga.fitness_func = fitness_function_factory(self) else: self.ga = pygad.GA(**parameters) self.ga.path = self.path['GA'] if len(self.ga.solutions) < (self.ga.num_generations + 1) * self.ga.sol_per_pop: self.ga.run() return
def minimize(func_name): config = configparser.ConfigParser() config_name = os.path.join(project_dir, 'objective_function/config/scale.ini') config.read(config_name, encoding='utf-8') print(config.sections()) optimal_position_address_dir = os.path.join(project_dir, "objective_function/optimal_position") dim_list = eval(config.get(func_name, 'dim_list')) dim_regs = eval(config.get(func_name, 'dim_regs')) repeat = 30 values = np.zeros((repeat, len(dim_list))) seed = 0 random.seed(seed) np.random.seed(seed) def fitness_func(solution, solution_idx): # Calculating the fitness value of each solution in the current population. output = -function_dict[obj_name](solution) return output fitness_function = fitness_func for i in range(repeat): for j in range(len(dim_list)): num_genes = dim_size = dim_list[j] gene_space = [{'low': dim_regs[0], 'high': dim_regs[1]}] * dim_size if dim_list[j] == 20: sol_per_pop = 20 num_parents_mating = 5 else: sol_per_pop = 50 num_parents_mating = 7 budget = 100 * dim_size num_generations = int(budget // sol_per_pop) optimal_position_address = os.path.join(optimal_position_address_dir, func_name, "{}_{}.txt".format(func_name, dim_size)) set_optimal_position(optimal_position_address) ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_function, sol_per_pop=sol_per_pop, gene_space=gene_space, num_genes=num_genes) ga_instance.run() result = get_best_result() clear_epoch() print("finist repeat: {}, dim: {}, best f: {}".format(i, dim_size, result)) values[i, j] = result log_address = os.path.join(project_dir, 'pygad_exp/log/scale/') file_name = os.path.join(log_address, '{}.txt'.format(obj_name)) os.makedirs(log_address, exist_ok=True) np.savetxt(file_name, values) print(values)
def train(): num_generations = 10 sol_per_pop = 100 num_parents_mating = sol_per_pop * 2 // 3 num_genes = 4 init_range_low = 1 init_range_high = 30 parent_selection_type = "sss" keep_parents = sol_per_pop // 4 crossover_type = "single_point" mutation_type = "random" mutation_num_genes = 1 start = time.time() def on_generation(ga_instance): global seed seed += 100 np.random.seed(seed) print("Generation = {generation}".format( generation=ga_instance.generations_completed)) print(f"{time.time() - start}s passed") # print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1])) global pool pool = Pool(10) ga_instance = pygad.GA( num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_func, sol_per_pop=sol_per_pop, num_genes=num_genes, init_range_low=init_range_low, init_range_high=init_range_high, parent_selection_type=parent_selection_type, keep_parents=keep_parents, crossover_type=crossover_type, mutation_type=mutation_type, mutation_num_genes=mutation_num_genes, mutation_probability=0.3, on_generation=on_generation, random_mutation_min_val=-5, random_mutation_max_val=5, ) ga_instance.run() print(f"Best solution: {ga_instance.best_solution()}") print(f"{time.time() - start}s passed.") pool.close()
def run(self): ga_instance = pygad.GA(num_generations=9999, num_parents_mating=300, fitness_func=fitness_func, sol_per_pop=1000, num_genes=2, init_range_low=0.0, init_range_high=1.0, random_mutation_min_val=0.0, random_mutation_max_val=1.0, mutation_by_replacement=True, callback_generation=callback_generation, delay_after_gen=self.screen.char_anim_duration) ga_instance.run()
def get_res( num_iterations: int, num_slots: int, courses: List[TypedDict("Course", { "code": str, "semester": int })], ): mapping_variables.num_slots = num_slots mapping_variables.subject_to_year_map = { course["code"]: course["semester"] for course in courses } mapping_variables.num_subj = len(mapping_variables.subject_to_year_map) count = 1 for course_code in mapping_variables.subject_to_year_map.keys(): mapping_variables.subject_to_int_map[course_code] = count mapping_variables.int_to_subject_map[count] = course_code count += 1 print( mapping_variables.subject_to_int_map, mapping_variables.int_to_subject_map, mapping_variables.subject_to_year_map, ) x = mapping_variables.randomize_initialization() count1 = 0 ga_instance = pygad.GA( num_generations=num_iterations, num_parents_mating=8, initial_population=x, fitness_func=fitness_func, parent_selection_type="rank", keep_parents=8, crossover_type="uniform", mutation_type="swap", on_generation=on_gen, ) ga_instance.run() solution_values = [ mapping_variables.int_to_subject_map[i] for i in best_solution.tolist() ] print(solution_values) return solution_values
def run(self): ga_instance = pygad.GA(num_generations=20, sol_per_pop=10, num_parents_mating=5, num_genes=1, fitness_func=fitness_func, init_range_low=100.0, init_range_high=200.0, random_mutation_min_val=50.0, random_mutation_max_val=350.0, mutation_by_replacement=True, on_generation=on_generation, suppress_warnings=True) ga_instance.run()
def __init__(self, total, progress_bar=None, verbose=True): objective1 = deminf_data.Objective.from_name( '1_Bot_4_Sim', negate=True, type_of_transform='logarithm') genes_space = [] for l, r in zip(objective1.lower_bound, objective1.upper_bound): genes_space.append({'low': l, 'high': r}) def fitness_func(solution, solution_idx): fitness_func.count += 1 fitness_func.X.append(solution) y = objective1(solution) if len(fitness_func.Y_best) == 0: fitness_func.Y_best.append(y) else: fitness_func.Y_best.append(min(fitness_func.Y_best[-1], y)) progress_bar.update(1) if fitness_func.count == total: raise StopModel('nothing series, just stop of the model') return -y fitness_func.count = 0 fitness_func.X = [] fitness_func.Y_best = [] if verbose: if progress_bar is not None: fitness_func.progress_bar = progress_bar else: fitness_func.progress_bar = tqdm(total=total, desc='GeneticAlgorithm') self.fitness_function = fitness_func num_generations = 100 # Number of generations. num_genes = len(genes_space) sol_per_pop = 50 def callback_generation(ga_instance): pass # Creating an instance of the GA class inside the ga module. # Some parameters are initialized within the constructor. self.ga_instance = ga_instance = pygad.GA( num_generations=num_generations, num_parents_mating=5, fitness_func=self.fitness_function, sol_per_pop=sol_per_pop, num_genes=num_genes, gene_space=genes_space, on_generation=callback_generation)
def prepare_GA(server_data): global keras_ga population_weights = server_data["population_weights"] model_json = server_data["model_json"] num_solutions = server_data["num_solutions"] model = tensorflow.keras.models.model_from_json(model_json) keras_ga = pygad.kerasga.KerasGA(model=model, num_solutions=num_solutions) keras_ga.population_weights = population_weights ga_instance = pygad.GA(num_generations=150, num_parents_mating=4, initial_population=keras_ga.population_weights.copy(), fitness_func=fitness_func) return ga_instance
def prepare_GA(GANN_instance): # population does not hold the numerical weights of the network instead it holds a list of references to each last layer of each network (i.e. solution) in the population. A solution or a network can be used interchangeably. # If there is a population with 3 solutions (i.e. networks), then the population is a list with 3 elements. Each element is a reference to the last layer of each network. Using such a reference, all details of the network can be accessed. population_vectors = pygad.gann.population_as_vectors( population_networks=GANN_instance.population_networks) # To prepare the initial population, there are 2 ways: # 1) Prepare it yourself and pass it to the initial_population parameter. This way is useful when the user wants to start the genetic algorithm with a custom initial population. # 2) Assign valid integer values to the sol_per_pop and num_genes parameters. If the initial_population parameter exists, then the sol_per_pop and num_genes parameters are useless. initial_population = population_vectors.copy() num_parents_mating = 4 # Number of solutions to be selected as parents in the mating pool. num_generations = 500 # Number of generations. mutation_percent_genes = 5 # Percentage of genes to mutate. This parameter has no action if the parameter mutation_num_genes exists. parent_selection_type = "sss" # Type of parent selection. crossover_type = "single_point" # Type of the crossover operator. mutation_type = "random" # Type of the mutation operator. keep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing. init_range_low = -2 init_range_high = 5 ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, mutation_percent_genes=mutation_percent_genes, init_range_low=init_range_low, init_range_high=init_range_high, parent_selection_type=parent_selection_type, crossover_type=crossover_type, mutation_type=mutation_type, keep_parents=keep_parents, on_generation=callback_generation) return ga_instance
def run(self, sudoku): fitness_function = self.__fitness_function num_generations = 50 num_parents_mating = 4 sol_per_pop = 8 num_genes = len(self.__create_grid(sudoku)[0]) init_range_low = 1 init_range_high = 9 parent_selection_type = "sss" keep_parents = 1 crossover_type = "single_point" mutation_type = "random" mutation_percent_genes = 10 ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_function, sol_per_pop=sol_per_pop, num_genes=num_genes, init_range_low=init_range_low, init_range_high=init_range_high, parent_selection_type=parent_selection_type, keep_parents=keep_parents, crossover_type=crossover_type, mutation_type=mutation_type, mutation_percent_genes=mutation_percent_genes) ga_instance.run() solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Parameters of the best solution : {solution}".format( solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format( solution_fitness=solution_fitness))
def start_ga(self, *args): if (not ("pop_created" in vars(self)) or (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 ga_instance = pygad.GA(num_generations=500, num_parents_mating=5, fitness_func=fitness, num_genes=8, initial_population=self.population_1D_vector, mutation_percent_genes=0.01, mutation_type="random", mutation_num_genes=3, mutation_by_replacement=True, random_mutation_min_val=0.0, random_mutation_max_val=8.0, callback_generation=callback) ga_instance.run() ga_instance.plot_result()
hidden_units_gene_space, attention_type_gene_space, aggregator_type_gene_space, activate_function_gene_space, number_of_heads_gene_space ] num_genes = len(gene_space) mutation_type = "random" mutation_percent_genes = 10 trnr = trainer.Trainer(args) ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, gene_type=int, fitness_func=fitness_function, sol_per_pop=sol_per_pop, num_genes=num_genes, gene_space=gene_space, parent_selection_type=parent_selection_type, keep_parents=keep_parents, crossover_type=crossover_type, mutation_type=mutation_type, on_generation=callback_gen, mutation_percent_genes=mutation_percent_genes) ga_instance.run() ga_instance.plot_result() solution, solution_fitness, solution_idx = ga_instance.best_solution() with open(args.dataset + "_" + args.search_mode + args.submanager_log_file, "a") as file: # with open(f'{self.args.dataset}_{self.args.search_mode}_{self.args.format}_manager_result.txt', "a") as file: file.write("Parameters of the best solution : ") file.write(str(solution))
solution_fitness = 1.0 / abs_error return solution_fitness # Create a callback def callback_generation(ga_instance): print('Generation = {generation}'.format(generation=ga_instance.generations_completed)) print('Fitness = {fitness}'.format(fitness=ga_instance.best_solution()[1])) # Create an instance of the pygad.GA Class ga_instance = pygad.GA(num_generations=250, num_parents_mating=2, parent_selection_type='rank', fitness_func=fitness_func, # initial_population=kerasGA.population_weights, sol_per_pop=9, num_genes=9, init_range_low=0.01, init_range_high=10.00, crossover_type='single_point', mutation_type='random', mutation_num_genes=2, save_best_solutions=True, save_solutions=True, allow_duplicate_genes=True, stop_criteria='saturate_10', on_generation=callback_generation) # Run the Genetic algorithm ga_instance.run() # Plot the fitness value ga_instance.plot_fitness(title='Iteration vs. Fitness', xlabel='Generation', ylabel='Fitness', linewidth=4) # To get the details about the best solution found by PyGAD solution, solution_fitness, solution_idx = ga_instance.best_solution() print(f'Fitness value of the best solution = '
crossover_type = "single_point" # Type of the crossover operator. mutation_type = "random" # Type of the mutation operator. keep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing. init_range_low = -2 init_range_high = 5 ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, mutation_percent_genes=mutation_percent_genes, init_range_low=init_range_low, init_range_high=init_range_high, parent_selection_type=parent_selection_type, crossover_type=crossover_type, mutation_type=mutation_type, keep_parents=keep_parents, callback_generation=callback_generation) ga_instance.run() # After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations. ga_instance.plot_result() # Returning the details of the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Parameters of the best solution : {solution}".format(solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format(
mutation_percent_genes = 40 crossover_type = "two_points" mutation_type = "random" num_genes = len(dimensions) init_range_low = 0 init_range_high = max(cables_availability) ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_function, sol_per_pop=sol_per_pop, gene_type=int, num_genes=num_genes, init_range_low=init_range_low, init_range_high=init_range_high, parent_selection_type=parent_selection_type, K_tournament=k_tournament, keep_parents=keep_parents, crossover_type=crossover_type, mutation_type=mutation_type, on_generation=callback_gen, on_parents=on_parents, mutation_percent_genes=mutation_percent_genes) ga_instance.run() solution, solution_fitness, solution_idx = ga_instance.best_solution() covered_length = 0 number_of_cables = 0 nodes = 0
last_fitness = 0 def callback_generation(ga_instance): global last_fitness print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution()[1])) print("Change = {change}".format(change=ga_instance.best_solution()[1] - last_fitness)) last_fitness = ga_instance.best_solution()[1] # Создание экземпляра класса ga_instance = pygad.GA(num_generations=50, num_parents_mating=40, #20% популяции fitness_func=cal_fitness, sol_per_pop=200, num_genes=len(function_inputs), gene_type=np.int16, init_range_low=0, init_range_high=2, parent_selection_type=parent_selection_type, keep_parents=40, #20% популяции crossover_type=crossover_type, mutation_type=mutation_type, mutation_percent_genes=mutation_percent_genes, callback_generation=callback_generation) # Запуск GA для оптимизации параметров функции. ga_instance.run() # После завершения поколений отображаются некоторые графики, ga_instance.plot_result() # Возвращение лучшего решения.. solution, solution_fitness, solution_idx = ga_instance.best_solution()
num_parents_mating = 10 # Number of solutions to be selected as parents in the mating pool. sol_per_pop = 20 # Number of solutions in the population. num_genes = len(function_inputs) last_fitness = 0 def on_generation(ga_instance): global last_fitness print("Generation = {generation}".format(generation=ga_instance.generations_completed)) print("Fitness = {fitness}".format(fitness=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1])) print("Change = {change}".format(change=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] - last_fitness)) last_fitness = ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, sol_per_pop=sol_per_pop, num_genes=num_genes, fitness_func=fitness_func, on_generation=on_generation) # Running the GA to optimize the parameters of the function. ga_instance.run() ga_instance.plot_fitness() # Returning the details of the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness) print("Parameters of the best solution : {solution}".format(solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness)) print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx)) prediction = numpy.sum(numpy.array(function_inputs)*solution)
fitness=ga_instance.best_solution()[1])) if ga_instance.generations_completed % 500 == 0: matplotlib.pyplot.imsave( 'solution_' + str(ga_instance.generations_completed) + '.png', gari.chromosome2img(ga_instance.best_solution()[0], target_im.shape)) ga_instance = pygad.GA(num_generations=20000, num_parents_mating=10, fitness_func=fitness_fun, sol_per_pop=20, num_genes=target_im.size, init_range_low=0.0, init_range_high=1.0, mutation_percent_genes=0.01, mutation_type="random", mutation_by_replacement=True, random_mutation_min_val=0.0, random_mutation_max_val=1.0, callback_generation=callback) ga_instance.run() # After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations. ga_instance.plot_result() # Returning the details of the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Fitness value of the best solution = {solution_fitness}".format(
[1.5, 1.2, 1.7], [3.2, 2.9, 3.1]]) # Data outputs data_outputs = numpy.array([[0.1], [0.6], [1.3], [2.5]]) num_generations = 250 num_parents_mating = 5 initial_population = keras_ga.population_weights ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, initial_population=initial_population, fitness_func=fitness_func, on_generation=callback_generation) ga_instance.run() # After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations. ga_instance.plot_result(title="PyGAD & Keras - Iteration vs. Fitness", linewidth=4) # Returning the details of the best solution. solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness)) print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx)) # Fetch the parameters of the best solution. best_solution_weights = pygad.kerasga.model_weights_as_matrix(model=model, weights_vector=solution)
def get_model(init_pop_size=100, generations=1000, stop_if_fitness_reached=0.2, stop_if_stale_for=10): ancestors = [p.team for p in [Player.get_random() for _ in range(init_pop_size)]] population_fitness_table = None def fitness_function(soltion, solution_idx): return population_fitness_table[soltion] def on_start(ga_instance: pygad.GA): """ populate fitness table for this population :return: None """ nonlocal population_fitness_table population_fitness_table = calc_pop_fitness(ga_instance.population) def crossover_func1(parents: List[Player], offspring_size, ga_instance): """ Switches 1 axie with the other team :param parents: The selected parents. :param offspring_size: The size of the offspring as a tuple of 2 numbers: (the offspring size, number of genes) :param ga_instance: The instance from the pygad.GA class. This instance helps to retrieve any property like population, gene_type, gene_space, etc :return: a NumPy array of shape equal to the value passed to the second parameter """ mom, dad = parents children = [] while len(children) < offspring_size: index = sample(range(3), 1)[0] mom_team, dad_team = mom.team, dad.team mom_team[index], dad_team[index] = dad_team[index], mom_team[index] children.extend([Player(mom_team), Player(dad_team)]) return np.array(children[:offspring_size]) def crossover_func2(parents, offspring_size, ga_instance): """ Pairs each Axie with the corresponding axie of the other team :param parents: The selected parents. :param offspring_size: The size of the offspring as a tuple of 2 numbers: (the offspring size, number of genes) :param ga_instance: The instance from the pygad.GA class. This instance helps to retrieve any property like population, gene_type, gene_space, etc :return: a NumPy array of shape equal to the value passed to the second parameter """ mom, dad = parents children = [] while len(children) < offspring_size: children.append(Player([Axie.pair(mom.team[0], dad.team[0]), Axie.pair(mom.team[1], dad.team[1]), Axie.pair(mom.team[2], dad.team[2])])) return np.array(children[:offspring_size]) def mutation_func(offspring: Player, ga_instance): """ :param offspring: The offspring to be mutated. :param ga_instance: The instance from the pygad.GA class. This instance helps to retrieve any property like population, gene_type, gene_space, etc. :return: offspring """ to_mutate = sample(range(3), 1)[0] mutated = Axie.flip_single_gene(offspring.team[to_mutate]) if to_mutate == 0: return Player([mutated] + offspring.team[1:]) elif to_mutate == 1: return Player([offspring.team[0], mutated, offspring.team[2]]) elif to_mutate == 2: return Player(offspring.team[:-1] + [to_mutate]) print("Mutation function did not return anything") exit(-1) # not needed I think def parent_selection_func(fitness, num_parents, ga_instance): """ :param fitness: The fitness values of the current population. :param num_parents: The number of parents needed. :param ga_instance: The instance from the pygad.GA class. This instance helps to retrieve any property like population, gene_type, gene_space, etc. :return: 1. The selected parents as a NumPy array. Its shape is equal to (the number of selected parents, num_genes). Note that the number of selected parents is equal to the value assigned to the second input parameter 2. The indices of the selected parents inside the population. It is a 1D list with length equal to the number of selected parents """ ... return on_stop = [f'reach_{stop_if_fitness_reached}', f'saturate_{stop_if_stale_for}'] # TODO use adaptive mutation ga = pygad.GA(initial_population=np.array(ancestors), num_generations=generations, num_parents_mating=2, fitness_func=fitness_function, sol_per_pop=init_pop_size, on_start=on_start, parent_selection_type=pygad.GA.tournament_selection, crossover_type=crossover_func1, mutation_type=mutation_func, on_stop=on_stop) return ga
# define the parameters fitness_function = fitness_func num_generations = 200000 num_parents_mating = 4 sol_per_pop = 100 num_genes = len(function_inputs) mutation_percent_genes = 10 stop_criteria="saturate_50" ga_instance = pygad.GA(num_generations=num_generations, num_parents_mating=num_parents_mating, fitness_func=fitness_function, sol_per_pop=sol_per_pop, num_genes=num_genes, mutation_percent_genes=mutation_percent_genes, stop_criteria=stop_criteria) ga_instance.run() solution, solution_fitness, solution_idx = ga_instance.best_solution() print("Parameters of the best solution : {solution}".format(solution=solution)) print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness)) prediction = np.sum(np.array(function_inputs)*solution) print("Predicted output based on the best solution : {prediction}".format(prediction=prediction))
def on_crossover(ga_instance, offspring_crossover): print("on_crossover()") def on_mutation(ga_instance, offspring_mutation): print("on_mutation()") def on_generation(ga_instance): print("on_generation()") def on_stop(ga_instance, last_population_fitness): print("on_stop()") ga_instance = pygad.GA(num_generations=3, num_parents_mating=5, fitness_func=fitness_function, sol_per_pop=10, num_genes=len(function_inputs), on_start=on_start, on_fitness=on_fitness, on_parents=on_parents, on_crossover=on_crossover, on_mutation=on_mutation, on_generation=on_generation, on_stop=on_stop) ga_instance.run()
# The tiny value 0.00000001 is added to the denominator in case the average distance is 0. fitness = 1.0 / (numpy.sum(clusters_sum_dist) + 0.00000001) return fitness num_clusters = 3 feature_vector_length = data.shape[1] num_genes = num_clusters * feature_vector_length ga_instance = pygad.GA(num_generations=100, sol_per_pop=10, init_range_low=0, init_range_high=20, num_parents_mating=5, keep_parents=2, num_genes=num_genes, fitness_func=fitness_func, suppress_warnings=True) ga_instance.run() best_solution, best_solution_fitness, best_solution_idx = ga_instance.best_solution( ) print("Best solution is {bs}".format(bs=best_solution)) print( "Fitness of the best solution is {bsf}".format(bsf=best_solution_fitness)) print("Best solution found after {gen} generations".format( gen=ga_instance.best_solution_generation))
# Create a callback def callback_generation(ga_instance): print('Generation = {generation}'.format( generation=ga_instance.generations_completed)) print('Fitness = {fitness}'.format(fitness=ga_instance.best_solution()[1])) # Create an instance of the pygad.GA Class ga_instance = pygad.GA(num_generations=250, num_parents_mating=2, parent_selection_type='tournament', fitness_func=fitness_func, sol_per_pop=9, num_genes=9, init_range_low=0.01, init_range_high=10.00, crossover_type='two_points', mutation_type='swap', mutation_num_genes=1, save_best_solutions=True, save_solutions=True, allow_duplicate_genes=True, stop_criteria='saturate_10', on_generation=callback_generation) # Run the Genetic algorithm ga_instance.run() # Plot the fitness value ga_instance.plot_fitness(title='Iteration vs. Fitness', xlabel='Generation', ylabel='Fitness',