def make_ga_grid(data, hybrid): # init ga estimator = genetic_algorithm.GeneticAlgorithm() param_grid = { "hybrid": [hybrid], "input_size": [data.shape[1] - 1], "hidden_layer_size": HIDDEN_LAYER_SIZES, "output_size": OUTPUT_SIZE, "population_size": [5], "selection_size": [3], "learning_rate": LEARNING_RATES, "epochs": [5], "generations": [2], "cases": [["mse", "l2", "l1"]], "verbose": [0], # ****** REMEMBER TO TOGGLE VERBOSITY ****** } if hybrid is True: print("\n\n***** Training Hybrid GA *****\n\n") else: print("\n\n***** Training GA *****\n\n") return cross_validate_on_data(estimator, param_grid, data)
gridX = 100 gridY = 100 gridZ = 100 thickness = 5 occ_grid = None objectives = [] no_of_objectives = 5 obstacles_per_axis = 3 starting_point = Point(0,0,0) if __name__ == "__main__": # Create a 3D Occupancy Grid print '\033[94m Generating random occupancy grid and objectives... \033[0m' occ_grid, objectives, starting_point = mapPseudoRandomizer(gridX, gridY, gridZ, thickness, obstacles_per_axis, no_of_objectives) alg = ga.GeneticAlgorithm(500, 0.00001, 5, 2, 40) print '\033[94m Generating random initial solutions... \033[0m' paths = alg.initialRandomSolutions(starting_point, objectives) max_generations = 25000 # We should better wait for convergence for p in range(len(paths)): paths[p].fitness = alg.fitness(paths[p].points, occ_grid) max_p = max(paths, key=lambda x:x.fitness) max_f = 0 count = 0 for i in range(max_generations):
####################################################### ####################################################### save.create_directory(SAVING_DIRECTORY) save.create_directory(SCORE_DIRECTORY) save.create_directory(IMAGES_DIRECTORY) # == INIT GAME == pygame.init() # Initializing library screen = pygame.display.set_mode(SIZE_SCREEN) # Initializing screen FPSCLOCK = pygame.time.Clock() # Refreshing screen rate # == INIT NNA, GA AND POPULATION == neuralNetwork = nna.ArtificialNeuralNetwork(INPUTS_SIZE, HIDDEN_LAYER_SIZE, OUTPUTS_SIZE) geneticAlgorithm = ga.GeneticAlgorithm(CROSSOVER_PROBABILITY, MUTATION_PROBABILITY, MUTATION_P_STEP) performance_FF = [[], [], []] # best, mean, stdev population_in_all_epochs = [] population_array = [] for i in range(POPULATION_SIZE): population_array.append(neuralNetwork.initialize_random_weights()) population_in_all_epochs.append(population_array) def init_new_map(walls, init_position): environment = env.Environment(screen, COLOR_ENVIROMENT, walls) robot = rb.Robot(screen, 2 * ROBOT_RADIUS, MAX_VELOCITY, MAX_DISTANCE_SENSOR) robot.position = init_position
## # Texts used to build Corpus: # Alice’s Adventures in Wonderland, by Lewis Carroll # The Republic, by Plato # Siddhartha, by Herman Hesse ## ############################## texts = ['https://www.gutenberg.org/files/11/11-0.txt', 'http://www.gutenberg.org/cache/epub/1497/pg1497.txt', 'http://www.gutenberg.org/cache/epub/2500/pg2500.txt'] messages = ["fqjcb rwjwj vnjax bnkhj whxcq nawjv nfxdu mbvnu ujbbf nnc", "oczmz vmzor jocdi bnojv dhvod igdaz admno ojbzo rcvot jprvi oviyv aozmo cvooj ziejt dojig toczr dnzno jahvi fdiyv xcdzq zoczn zxjiy", "ejitp spawa qleji taiul rtwll rflrl laoat wsqqj atgac kthls iraoa twlpl qjatw jufrh lhuts qataq itats aittk stqfj cae", "iyhqz ewqin azqej shayz niqbe aheum hnmnj jaqii yuexq ayqkn jbeuq iihed yzhni ifnun sayiz yudhe sqshu qesqa iluym qkque aqaqm oejjs hqzyu jdzqa diesh niznj jayzy uiqhq vayzq shsnj jejjz nshna hnmyt isnae sqfun dqzew qiead zevqi zhnjq shqze udqai jrmtq uishq ifnun siiqa suoij qqfni syyle iszhn bhmei squih nimnx hsead shqmr udquq uaqeu iisqe jshnj oihyy snaxs hqihe lsilu ymhni tyz"] # initialize the corpus corp = Corpus(texts, is_url=True) # or alternatively, load the corpus from pickle files #corp = Corpus(load=True) for i, message in enumerate(messages): sec = time.time() model = GA.GeneticAlgorithm(message, corp, "./results/", "results" + str(i)) model.train(epochs=1e3) print("Time " + str(i) + ": " + str((time.time() - sec)))
from taems import TaemsTree import genetic_algorithm import tabu_search import simulated_annealing import ant_colony_optimization if __name__ == "__main__": [alternative, pt, rt, dt] = loader.load_file("./Input/", "alternative_1.txt") tree = TaemsTree.load_from_file("./Input/example_large.taems") test = 2 if test == 0: ga_solutions = [] ga = genetic_algorithm.GeneticAlgorithm(200, 0.1, 0.3) for i in range(1000): [best_sol, iteration] = ga.optimize(tree, alternative, pt, rt, dt, 50) print([i, best_sol.total_tardiness, iteration]) ga_solutions.append([best_sol, iteration]) f = open("Results/ga_results.txt", "w") for i in range(1000): f.write(str(ga_solutions[i][0].total_tardiness) + " " + str(ga_solutions[i][1]) + "\n") f.close() elif test == 1: tabu_solutions = [] tabu = tabu_search.TabuSearch(10) for i in range(1000): [best_sol, iteration] = tabu.optimize(tree, alternative, pt, rt, dt, 100)
LIM_m_y, LIM_M_y = -1, 1 if FITNESS_FUNCTION.__name__ == "Rosenbrock": LIM_m_x, LIM_M_x = -2, 2 LIM_m_y, LIM_M_y = -1, 3 else: # Rastrigin LIM_m_x, LIM_M_x = -5, 5 LIM_m_y, LIM_M_y = -5, 5 x_range_list = np.linspace(LIM_m_x, LIM_M_x, 200) y_range_list = np.linspace(LIM_m_y, LIM_M_y, 200) # === MAIN === Pi, Po, Z = 0, 1, 2 X, Y = 0, 1 # INITS geneticAlgorithm = ga.GeneticAlgorithm(FITNESS_FUNCTION, MUTATION_PROBABILITY, MUTATION_P_STEP) FF_results = [[], [], []] # best, media,stdev # INIT DATASET dataset = geneticAlgorithm.initialize_population(POPULATION_SIZE, x_range_list, y_range_list) plot.PlottingResults(dataset, x_range_list, y_range_list, FITNESS_FUNCTION) best, media, stdev = geneticAlgorithm.calculate_fitness(dataset) FF_results[0].append(best) FF_results[1].append(media) FF_results[2].append(stdev) copied_dataset = np.array(deepcopy(dataset)) for i in range(1, GENETIC_EPOCHS + 1): parents = geneticAlgorithm.select_parents(copied_dataset, PARENTS_NUMBER)
group = 500 jump = 250 start = 0 end = 0 while True: if start == 0: start = 1 else: start = start + jump if start >= len(path): break end = start + group if end >= len(path): end = len(path) - 1 gen_path = path[start:end].copy() gen = genetic_algorithm.GeneticAlgorithm(gen_path, df_cities, path[start-1], path[end-1], prime_cities) selected_path = gen.calculate() a = total_distance(df_cities, path[start - 1:end + 1], prime_cities) b = total_distance(df_cities, [path[start - 1]] + gen_path + [path[end]], prime_cities) print(a) print(b) if a > b: path[start:end] = selected_path if end == len(path) - 2: break print('Total distance genetic algorithm ' + "is {:,}".format(total_distance(df_cities, path, prime_cities))) path = opt2(df_cities, path, True, 3, prime_cities) print('Total distance with 2-opt ' + "is {:,}".format(total_distance(df_cities, path, prime_cities))) pd.DataFrame({'Path': path}).to_csv('path.csv', index=False)