Beispiel #1
0
def main():
    target_string = "Genetic Algorithm"
    population_size = 100
    mutation_rate = 0.05
    genetic_algorithm = GeneticAlgorithm(target_string,
                                        population_size,
                                        mutation_rate)

    print ("")
    print ("+--------+")
    print ("|   GA   |")
    print ("+--------+")
    print ("Description: Implementation of a Genetic Algorithm which aims to produce")
    print ("the user specified target string. This implementation calculates each")
    print ("candidate's fitness based on the alphabetical distance between the candidate")
    print ("and the target. A candidate is selected as a parent with probabilities proportional")
    print ("to the candidate's fitness. Reproduction is implemented as a single-point")
    print ("crossover between pairs of parents. Mutation is done by randomly assigning")
    print ("new characters with uniform probability.")
    print ("")
    print ("Parameters")
    print ("----------")
    print ("Target String: '%s'" % target_string)
    print ("Population Size: %d" % population_size)
    print ("Mutation Rate: %s" % mutation_rate)
    print ("")

    genetic_algorithm.run(iterations=1000)
Beispiel #2
0
def greedy_evolver_test():
    from angular_evolver import edge_order_evolver as OE
    crossover = OE.OrderUniformCrossover()
    selection = OE.uniform_wheel_selection
    mutation = OE.EdgeOrderMutation()
    solver = OE.AngularMinSumGreedySolver()
    result_sol_func = lambda x: np.array([item.solution[1] for item in x])
    fitness = OE.AngularSolverFitness(
        solver.__class__.__name__,
        remote_computation=False,
        fitness_goal=OE.AngularSolverFitness.MIN_SUM,
        solver_params={"no_sol_return": True},
        custom_result_func=result_sol_func)
    termination = OE.IterationTerminationConditionMet(max_iter=200)
    callback = OE.update_callback
    graph = OE.create_circle_n_k(12, 3)
    init_pop = np.zeros(200, dtype=object)
    init_pop[:] = [OE.EdgeOrderGraphGenome(graph) for i in range(200)]

    from genetic_algorithm import GeneticAlgorithm
    ga = GeneticAlgorithm(genomes=init_pop,
                          selection=selection,
                          mutation=mutation,
                          fitness=fitness,
                          crossover=crossover,
                          termCon=termination,
                          callback=callback)
    last = ga.evolve()
    return last
Beispiel #3
0
def lambda_handler(list_elites_schedules, param):

    # Recupere tous les emplois du temps des fonctions Lambda precedentes
    all_elites = []
    for schedules_list in list_elites_schedules:
        for schedule in schedules_list:
            all_elites.append(schedule)

    # Tri l'ensemble des emplois du temps par ordre decroissant de fitness
    sorted_list = sorted(all_elites,
                         key=lambda schedule: schedule._fitness,
                         reverse=True)

    # Creation de la population avec les elites des populations precedentes
    data = Data()
    newPop = Population(size=param[0][0], data=data, schedules=sorted_list)
    algo = GeneticAlgorithm(data=data, param=param[0])

    # Evolution de la population en local sur les serveurs d'AWS
    for _ in range(param[0][6]):  # param[0][6]==NUMB_OF_GENERATION
        if (newPop.schedules[0]._fitness != 1.0):
            newPop = algo.evolve(population=newPop)

            for schedule in newPop.schedules:
                schedule._fitness = schedule.calculate_fitness()

            newPop.sort_by_fitness()

    # Recupere les elites pour les retourner
    elites = []
    for i in range(param[0][5]):  # param[0][5]==NUMB_OF_ELITES
        elites.append(newPop.schedules[i])

    return elites
def main():
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target
    n_clusters = 3
    pop_size = 100
    mutation_rate = 0.01
    crossover_rate = 0.85
    elitism_count = 3
    ga = GeneticAlgorithm(n_clusters, pop_size, mutation_rate, X,
                          crossover_rate, elitism_count)

    d1, y1 = datasets.make_blobs(n_samples=121, centers=3, n_features=5)
    d2, y2 = datasets.make_blobs([378, 233], 2)
    d3, y3 = datasets.make_blobs([220, 145, 56, 378, 117], 5)
    d4, y4 = datasets.make_blobs(100, 8)

    ga1 = GeneticAlgorithm(n_clusters, pop_size, mutation_rate, d1,
                           crossover_rate, elitism_count)
    ga2 = GeneticAlgorithm(n_clusters, pop_size, mutation_rate, d2,
                           crossover_rate, elitism_count)
    ga3 = GeneticAlgorithm(n_clusters, pop_size, mutation_rate, d3,
                           crossover_rate, elitism_count)
    ga4 = GeneticAlgorithm(n_clusters, pop_size, mutation_rate, d4,
                           crossover_rate, elitism_count)

    run_algo(ga, X, pop_size)
    run_algo(ga1, d1, pop_size)
    run_algo(ga2, d2, pop_size)
    run_algo(ga3, d3, pop_size)
    run_algo(ga4, d4, pop_size)
def main():
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    tokenize = MosesTokenizer('en')
    detokenize = MosesDetokenizer('en')

    def print_output(output):
        for _r in output:
            logger.info("%s: %s", detokenize(_r), str(_r.fitness.values))
        logger.info(" ")

    population_size = 25
    max_iter = 5
    crossover_prob = 0.2
    mutation_prob = 0.8
    ga_weights = weights

    generator = GeneticAlgorithm(population_size=population_size,
                                 max_iter=max_iter,
                                 crossover_prob=crossover_prob,
                                 mutation_prob=mutation_prob,
                                 weights=ga_weights)

    text = 'Suffering from Success'
    tokens = tokenize(text)
    pop, _, hof = generator.run(tokens)

    print_output(hof)

    tokenize.close()
    detokenize.close()
Beispiel #6
0
def process_task(config, task, session):
    # First init all callable classes
    try:
        mutation = _instantiate_callables(config.mutation_func, None)
        selection = _instantiate_callables(config.selection_func, None)
        crossover = _instantiate_callables(config.crossover_func, None)
        fitness = _instantiate_callables(config.fitness_func,
                                         config.fitness_func_initargs)
        if config.term_condition == 'IterationTerminationConditionMet' and not config.term_condition_initargs:
            term_con = IterationTerminationConditionMet(
                max_iter=config.generations)
        else:
            term_con = _instantiate_callables(config.term_condition,
                                              config.term_condition_initargs)
        if config.callback == 'SaveCallback' and config.callback_initargs is None:
            callback = SaveCallback(config.generations,
                                    config.population_amount, task, session)
        else:
            callback = _instantiate_callables(config.callback,
                                              config.callback_initargs)
        task.status = Task.STATUS_OPTIONS.PROCESSING
        if session:
            session.commit()
        # Now load population if provided, else generate it
        starting_generation, population = _load_population(
            config, task, session)

        if config.PreEvolveInteractive:
            print(
                "Config set up. To change the population just change the 'population' variable."
            )
            print("For other variables just refer to the locals.")
            embed()

        gen_algo = GeneticAlgorithm(
            genomes=population,
            selection=selection,
            mutation=mutation,
            fitness=fitness,
            crossover=crossover,
            callback=callback,
            termCon=term_con,
            elitism=config.elitism,
            mutationChance=config.mutation_chance_genome,
            mutationChanceGene=config.mutation_chance_gene)
        gen_algo.evolve(generation=starting_generation)
        task.status = Task.STATUS_OPTIONS.FINISHED
        if session:
            session.commit()
    except InterruptedError as e:
        task.status = task.STATUS_OPTIONS.INTERRUPTED
        if session:
            session.commit()
    except Exception as e:
        if session:
            task.status = Task.STATUS_OPTIONS.ERROR
            task.error_message = str(e)
            session.commit()
        print(e)
        raise e
Beispiel #7
0
def run():
    global SCHEDULE_NUMBER, CLASS_NO

    from data import Data
    from genetic_algorithm import GeneticAlgorithm
    from population import Population

    generation_number = 0
    data = Data()
    _genetic_algorithm = GeneticAlgorithm(data=data)
    _population = Population(size=POPULATION_SIZE, data=data).sort_by_fitness()

    print_data(data=data)
    print
    print

    print_population_schedules(population=_population,
                               generation_number=generation_number)
    print_schedule_as_table(data=data,
                            schedule=_population.schedules[0],
                            generation=generation_number)

    while _population.schedules[0].fitness != 1.0:
        generation_number += 1
        _population = _genetic_algorithm.evolve(
            population=_population).sort_by_fitness()

        print_population_schedules(population=_population,
                                   generation_number=generation_number)
        print_schedule_as_table(data=data,
                                schedule=_population.schedules[0],
                                generation=generation_number)
    def execDir(self):
        global pathh
        pat =pathh
        files = listdir(pathh)
        open("result_ag.csv", "w").close()
        print(1)
        print(pat)
        for f in files:
            l = pat + "/" + f
            print(f)
            j = self.InstanceReader2(f)
            print("hada",j)
            instance, n, C, w = self.InstanceReader(l)
            items = [Item(size=int(i)) for i in w]
            shuffle(items)
            thing = GeneticAlgorithm(C, items)
            # c, conf, time = self.AG(weight, C)
            start = timeit.default_timer()
            thing.run()
            print(6)
            stop = timeit.default_timer()
            time = stop - start
            c = thing.best_solution.num_bins
            print(9)
            resultatt = open("result_ag.csv", mode="a+")

            resultatt.write(f'{instance},{n},{C},{c},{j},{time * 1000}\n')  # Ecrire les resultats dans un fichier csv
            resultatt.close()
            print(0)
        self.loadData_mod_csv('./result_ag.csv')
Beispiel #9
0
    def setUp(self):
        # initializing variables for self.ga
        self.expected_input_size = 2
        self.expected_hidden_size = 5
        self.expected_output_size = 1
        self.population_size = 10
        self.selection_size = 2
        self.learning_rate = 1e-3
        self.epochs = 5
        self.generations = 2

        self.ga = GeneticAlgorithm(
            False,
            self.expected_input_size,
            self.expected_hidden_size,
            self.expected_output_size,
            self.population_size,
            self.selection_size,
            self.learning_rate,
            self.epochs,
            self.generations,
        )
        self.hga = GeneticAlgorithm(
            True,
            self.expected_input_size,
            self.expected_hidden_size,
            self.expected_output_size,
            self.population_size,
            self.selection_size,
            self.learning_rate,
            self.epochs,
            self.generations,
        )
        pass
Beispiel #10
0
def run(file, seed, population_size, mutation_rate, elitism_rate, output_file):
    instance = Instance.load(file)
    algorithm = GeneticAlgorithm(instance, 
                                seed,
                                population_size, 
                                mutation_rate, 
                                elitism_rate)
    start_time = time.time()
    first_solution, solution = algorithm.run()
    stop_time = time.time()
    print(f'Solution fitness: {solution[1]}')
    print(f'Execution time: {stop_time - start_time}')
    
    solution_edges = get_solution_edges(solution)

    output = {
        'parameters': {
            'instance': file,
            'seed': seed,
            'population-size': population_size,
            'mutation-rate': mutation_rate,
            'elitism-rate': elitism_rate
        },
        'first-solution-fitness': first_solution[1],
        'solution-fitness': solution[1],
        'execution-time': stop_time - start_time,
        'solution': solution_edges
    }

    with open(output_file, mode='w') as out_file:
        out_file.write(json.dumps(output, indent=2))        
Beispiel #11
0
def run_algorithm(data, labels, output_file, learner):
    """Runs the genetic algorithm"""
    fitness_calc = None
    if learner == 'SVM':
        fitness_calc = SVCFitnessCalc(data, labels)
    elif learner == 'DT':
        fitness_calc = DTFitnessCalc(data, labels)
    elif learner == 'MLP':
        fitness_calc = MLPFitnessCalc(data, labels)
    else:
        print 'Learner error'

    ga = GeneticAlgorithm(fitness_calc, learner)

    with open(output_file, 'a') as csvfile:
        out_writer = csv.writer(csvfile)
        out_writer.writerow(['time', 'generation', 'parameters', 'fitness'])

    try:

        start_time = time.time()
        pop = Population(size=50,
                         fit_calc=fitness_calc,
                         initialize=True,
                         indiv_type=learner)
        generation = 1
        fittest = pop.get_fittest()
        fitness = fittest.get_fitness()
        best_fitness = fitness

        params = fittest.get_params_str()
        cur_time = time.time() - start_time
        with open(output_file, 'a') as csvfile:
            out_writer = csv.writer(csvfile)
            out_writer.writerow([cur_time, generation, params, best_fitness])

        while fitness < fitness_calc.max_fitness:
            pop = ga.evolve_pop(pop)
            generation += 1
            fittest = pop.get_fittest()
            fitness = fittest.get_fitness()

            if fitness > best_fitness:
                best_fitness = fitness
                params = fittest.get_params_str()
                cur_time = time.time() - start_time
                with open(output_file, 'a') as csvfile:
                    out_writer = csv.writer(csvfile)
                    out_writer.writerow(
                        [cur_time, generation, params, best_fitness])

        sys.exit()

    except ZeroDivisionError, e:
        with open(output_file, 'a') as csvfile:
            out_writer = csv.writer(csvfile)
            out_writer.writerow(['ZeroDivisionError'])
            out_writer.writerow([e])
        sys.exit()
Beispiel #12
0
    def run(self):
        result1 = GeneticAlgorithm(self.bin_capacity, self.items,self.POPULATION_SIZE,self.MAX_GENERATIONS,self.MAX_NO_CHANGE,self.TOURNAMENT_SIZE,self.MUTATION_RATE,self.CROSSOVER_RATE)
        total_iterationsAG, stagnationAG = result1.run()

        result2 = TabuSearch(self.bin_capacity, self.items,self.MAX_COMBINATION_LENGTH,self.MAX_ITERATIONS,self.MAX_NO_CHANGE2)
        total_iterationsTB, stagnationTB, combinationTB = result2.run2(result1)

        return result1,result2,total_iterationsAG, stagnationAG, total_iterationsTB, stagnationTB, combinationTB
Beispiel #13
0
    def run(self):
        result1 = GeneticAlgorithm(self.bin_capacity, self.items, self.POPULATION_SIZE,self.MAX_GENERATIONS,self.MAX_NO_CHANGE,self.TOURNAMENT_SIZE,self.MUTATION_RATE,self.CROSSOVER_RATE)
        total_iterationsAG, stagnationAG = result1.run()

        sa = SA(self.alpha,self.bin_capacity, self.items,self.t_init, self.t_target, self.iter_nb)
        sa.run_for_hrh(result1.best_solution.generate_solution(self.items))

        return sa
Beispiel #14
0
def main():
    utils.delete_files()
    data = Data()
    if data.algorithm == Algorithm.GENETIC:
        algorithm = GeneticAlgorithm(data)
    else:
        algorithm = CSPAlgorithm(data)
    algorithm.run()
    print("Finished!")
Beispiel #15
0
def single_test(steps, population_size, crossover_chance, mutation_chance, evaluate_number):
    sudoku = get_initial_sudoku()

    ga = GeneticAlgorithm(sudoku)

    solver = GeneticSolver(
        sudoku,
        steps = steps,
        population_size = population_size,
        crossover_chance = crossover_chance,
        mutation_chance = mutation_chance
        )

    population = solver.solve()

    population.sort(key=lambda ind: ga.fitness_function(ind))

    ind = ga.get_individual_from_indexed_list(population[-1:][0])

    sudoku.fill_missing(ind)

    print(sudoku)
    evaluation = sudoku.evaluate()
    print(evaluation)
    evaluate_number = evaluate_number + sudoku.evaluate()

    um, dois, tres, quatro, cinco, seis, sete, oito, nove = 0,0,0,0,0,0,0,0,0
    for i in sudoku.puzzle:
     if i == 1:
         um += 1
     elif i == 2:
         dois += 1
     elif i == 3:
         tres += 1
     elif i == 4:
         quatro += 1
     elif i == 5:
         cinco += 1
     elif i == 6:
         seis += 1
     elif i == 7:
         sete += 1
     elif i == 8:
         oito += 1
     elif i == 9:
         nove += 1

    print('\nUm', um)
    print('Dois', dois)
    print('Tres', tres)
    print('Quatro', quatro)
    print('Cinco', cinco)
    print('Seis', seis)
    print('Sete', sete)
    print('Oito', oito)
    print('Nove', nove)
    return evaluate_number
    def display(self):
        pygame.init()
        pygame.display.set_caption('MLCars2D')

        screen = pygame.display.set_mode(self.size)

        icon = pygame.image.load('resources/images/icon.png')
        pygame.display.set_icon(icon)

        self.game_objects_controller = GameObjectsController(
            self.window_width, self.window_height, screen, self)
        self.game_objects_controller.display_menu()
        self.game_objects_controller.number_of_cars = constants.CARS_NO
        self.game_objects_controller.initialize_track_with_random_cars()

        keyboardEvents = KeyboardEventHandler()

        iteration_number = 0
        self.genetic_algorithm = GeneticAlgorithm(
            38, self.game_objects_controller.number_of_cars, 40, 0.05)
        population = self.genetic_algorithm.perform_crossing_and_mutation()
        print(
            len(self.game_objects_controller.cars[0].neural_network.
                get_weight_list()))
        self.game_objects_controller.reinitialize_cars(population)

        clock = pygame.time.Clock()
        fps = constants.FPS

        simulation_length = 400

        while True:
            if self.game_objects_controller.play_action_frame_count % simulation_length == 0:
                distances = self.game_objects_controller.get_car_distances()
                population = self.perform_learning_iteration(
                    distances, population, self.genetic_algorithm,
                    iteration_number)

                print(sum(distances) / (len(distances)))

                self.game_objects_controller.update_stat_box()
                self.game_objects_controller.reinitialize_cars(population)

            keyboardEvents.reset()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONUP:
                    pass
                keyboardEvents.process_events(event)
                self.game_objects_controller.check_pressed_buttons(event)

            self.game_objects_controller.perform_action(keyboardEvents)

            pygame.display.flip()
            clock.tick(fps)
Beispiel #17
0
def genetic_iterations(graph,ite):
    nTournament = 6
    probability = 0.05
    nPopulation = 50
    nIterations = ite
    nElite = 10

    genetic = GeneticAlgorithm(
        nPopulation, nIterations, nElite, nTournament, probability, graph)
    solution = genetic.genetic_algorithm()
    return solution.fitness
Beispiel #18
0
def demonstrate_genetic_algorithm(pop_size, elite_size, rate, gens):
    print("\t\tGenetic Algorithm")
    print("Initial Population Size: {}".format(pop_size))
    print("Elite Size: {}".format(elite_size))
    print("Mutation Rate: {}".format(rate))
    print("Generations: {}".format(gens))
    ga = GeneticAlgorithm(graph, pop_size, elite_size, rate, gens)
    tour, t = ga.run()
    print("Shortest Tour: {}".format(tour[0]))
    print("Cost: {}".format(tour[1]))
    print("Number of Seconds Taken: {}\n".format(t))
Beispiel #19
0
def create_heatmap(problem_obj):
    """
    Creates de HeatMap.
    :param problem_obj:     a BitSequence, Phrase or Knapsack instance
    """
    limit_generation = 500
    mutation_rate = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5])
    population_size = np.arange(100, 750, 50)

    heatmap = np.zeros((mutation_rate.shape[0], population_size.shape[0]))

    for rate, i in zip(mutation_rate, range(mutation_rate.shape[0])):
        for size, j in zip(population_size, range(population_size.shape[0])):

            # Initialize the genetic algorithm
            genetic_algorithm = GeneticAlgorithm(
                population_size=size,
                fitness=problem_obj.fitness,
                generate_gene=problem_obj.generate_gene,
                generate_individual=problem_obj.generate_individual,
                mutation_rate=rate,
                condition_finish=problem_obj.condition_finish,
                max_generation=limit_generation)

            # Calculates how many generations the algorithm takes
            generations_data = genetic_algorithm.run_algorithm(verbose=False)

            # Puts the result in the HeatMap
            heatmap[i, j] = generations_data.shape[0]

    # Creates HeatMap
    sns.set()
    plt.figure(figsize=(10, 8))

    fig, ax = plt.subplots()

    sns.heatmap(heatmap,
                annot=True,
                annot_kws={'va': 'top'},
                ax=ax,
                vmin=0,
                vmax=limit_generation,
                fmt=".1f",
                linewidths=0.25,
                square=True,
                cbar=False,
                xticklabels=population_size,
                yticklabels=mutation_rate)

    plt.title('Population size v/s Mutation rate v/s Generation')
    plt.xlabel('Population size')
    plt.ylabel('Mutation rate')

    plt.show()
Beispiel #20
0
def genetic_population(graph,pop):
    nTournament = 6
    probability = 0.05
    nPopulation = pop
    nIterations = 500
    nElite = 30

    genetic = GeneticAlgorithm(
        nPopulation, nIterations, nElite, nTournament, probability, graph)
    solution = genetic.genetic_algorithm()
    return solution.fitness
Beispiel #21
0
 def __init__(self, algo, calib_type, hp_grid, cv, scoring, n_iter=None):
     self.cv = cv
     self.algo = algo
     self.scoring = scoring
     self.hp_grid = hp_grid
     self.best_hp = {}
     if calib_type == 'GridSearch':
         self.hp_iterator = ParameterGrid(self.hp_grid)
     elif calib_type == 'RandomSearch':
         self.hp_iterator = ParameterSampler(self.hp_grid, n_iter)
     elif calib_type == 'GeneticAlgorithm':
         self.hp_iterator = GeneticAlgorithm(self.hp_grid, n_iter)
Beispiel #22
0
    def __init__(self,
                 inputs=7,
                 outputs=3,
                 hidden_layers=[],
                 population_size=20,
                 fittest_percent=0.2,
                 mutation_chance=0.05,
                 crossover_points=1,
                 screen_size=20,
                 delay=200,
                 box_width=20,
                 food_value=200,
                 moves_to_decrement=1,
                 score_decrement=2,
                 score_increment=2,
                 score_decrement_move=2,
                 turn_decrement_factor=1.5,
                 initial_score=100,
                 score_tracking=False,
                 save_to_file=False):

        self.population_size = population_size
        self.generation = 0
        self.current_individual_index = 0
        self.decrement_factor = turn_decrement_factor

        self.snake_list = []
        self.network_list = []
        self.fitness_list = np.zeros(self.population_size)

        # Recording best snake
        self.max_fitness = -np.inf
        self.max_fitness_network = None
        self.save_to_file = save_to_file

        self.algorithm = GeneticAlgorithm(fittest_percent, mutation_chance,
                                          crossover_points)
        for i in range(self.population_size):
            self.network_list.append(
                NeuralNetwork(inputs, outputs, hidden_layers))

        super().__init__(screen_size=screen_size,
                         delay=delay,
                         box_width=box_width,
                         human_player=False,
                         food_value=food_value,
                         moves_to_decrement=moves_to_decrement,
                         score_decrement=score_decrement,
                         score_increment=score_increment,
                         initial_score=initial_score,
                         score_tracking=score_tracking,
                         score_decrement_move=score_decrement_move,
                         turn_decrement_factor=turn_decrement_factor)
Beispiel #23
0
def natural_selection(dataset):
    ga = GeneticAlgorithm()
    neural_net_population = ga.create_initial_population()

    for i in range(Constants.num_generations - 1):
        print("Generation {}".format(i), '-' * 20)
        train_population(neural_net_population, dataset)
        avg_fitness = calculate_avg_fitness(neural_net_population)

        print('*' * 5, "Generation {}: {}".format(i, avg_fitness))
        neural_net_population = ga.evolution(neural_net_population)

    show_results(neural_net_population)
def run_genetic_algorithm(seconds, population_size, crossover, mutate):
    print('Running Genetic Algorithm for ' + str(seconds) + ' seconds...')
    print()

    ga = GeneticAlgorithm(states, seconds, population_size, crossover, mutate,
                          inc_support, dec_support)
    ga.run()
    print('Found optimal route with value of ' + str(ga.best_solution.value) +
          '.')
    print(
        str(ga.best_solution.calculate_real_value()) +
        ' electoral votes were collected.')
    ga.best_solution.print()
    print()
Beispiel #25
0
def _run_trials(parameters: Parameters, trials: int):
    results = np.empty(shape=(trials, ), dtype=bool)

    ga = GeneticAlgorithm(parameters)
    start_time = time.time()
    for i in range(trials):
        results[i] = ga.run()

    finish_time = time.time()

    average_time = (finish_time - start_time) / trials
    success_rate = np.count_nonzero(results) / trials

    return (average_time, success_rate)
def main(argv):
    # Variables for genetic algorithm
    number_of_generations = 30
    population_size = 100
    crossover_probability = 0.7
    mutation_probability = 0.1

    # Variables for neutral network
    number_of_hidden_layers = 3
    node_for_hidden_layer = 6

    # Variables for snake game
    draw = False
    board_size = 10

    log = False

    try:
        opts, args = getopt.getopt(argv, "hdLg:p:c:m:l:n:b:",
                                   ["generations=", "population=", "crossover=", "mutation=", "layers=",
                                    "nodes=", "board="])
    except getopt.GetoptError:
        print(
            'main.py -d (draw best run) -L (save every chromosome with its score to log file) -g <number_of_generations> -p <population_size> -c <crossover_probability>\
 -m <mutation_probability> -l <number_of_hidden_layers> -n <nodes_for_hidden_layer> -b <board_size>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(
                'main.py -d (draw best run) -L (save every chromosome with its score to log file) -g <number_of_generations> -p <population_size> -c <crossover_probability>\
 -m <mutation_probability> -l <number_of_hidden_layers> -n <nodes_for_hidden_layer> -b <board_size>')
            sys.exit()
        elif opt == '-d':
            draw = True
        elif opt == '-L':
            log = True
        elif opt in ("-g", "--generations"):
            number_of_generations = int(arg)
        elif opt in ("-p", "--population"):
            population_size = int(arg)
        elif opt in ("-c", "--crossover"):
            crossover_probability = float(arg)
        elif opt in ("-m", "--mutation"):
            mutation_probability = float(arg)
        elif opt in ("-l", "--layers"):
            number_of_hidden_layers = int(arg)
        elif opt in ("-n", "--nodes"):
            node_for_hidden_layer = int(arg)
        elif opt in ("-b", "--board"):
            board_size = int(arg)

    print(number_of_generations, population_size, crossover_probability, mutation_probability, number_of_hidden_layers,
          node_for_hidden_layer, board_size)

    genetic_algorithm = GeneticAlgorithm(population_size, number_of_generations, crossover_probability,
                                         mutation_probability, board_size, draw, log)
    genetic_algorithm.number_of_hidden_layers = number_of_hidden_layers
    genetic_algorithm.node_for_hidden_layer = node_for_hidden_layer
    genetic_algorithm.init_population()
    genetic_algorithm.evolve()
    def main_show_maze(self, pop, cross, mut, max_generation, elitismo):
        # vars
        solution = False
        generation = 0
        mut = float(mut)
        cross = float(cross)
        elitismo = True if str(elitismo) == '1' else False
        # Cria a população
        ##########################################3
        population = Population(tamPop=int(pop))
        population.create_random_population()

        # Cria o algoritmo genetico
        algoritmo = GeneticAlgorithm(crossover=cross, mutation=mut, elitismo=elitismo)

        while solution == False and generation<=int(max_generation):
            generation += 1

            population = algoritmo.create_new_generation(current_population=population)
            best_specimen = population.getSpeciemen(0)
            # Reseta a tela e mostra o caminho do melhor cromossomo
            ######################################################################
            if generation % 10 == 0:
                self.env.reset()
                self.env.after(100, self.show_path_on_maze(best_specimen=best_specimen))

            solution = algoritmo.get_solution(best_specimen.genetic_code)
            conteudo = '\nCódigo={} \nFitness={} \nGeração={}\nRota=[{}]'.format(best_specimen.genetic_code, best_specimen.fitness, generation,best_specimen.route)

            self.env.delete()
            self.env.escreve(conteudo)
            print(best_specimen.genetic_code, best_specimen.fitness, best_specimen.route, generation)


        if solution == True:
            conteudo = 'Solução ótima!!' \
                       '\nCódigo={} ' \
                       '\nFitness={} ' \
                       '\nGeração={}'.format(best_specimen.genetic_code,
                                             best_specimen.fitness, generation)
            self.env.delete()
            self.env.escreve(conteudo)
            print(best_specimen.genetic_code, best_specimen.fitness, best_specimen.route, generation)

            i = 0
            while i <= 10:
                i+=1
                self.env.reset()
                self.env.after(100, self.show_path_on_maze(best_specimen=best_specimen))
Beispiel #28
0
class CrossVal():
    """ Cross Validation general class for GridSearch, RandomSearch, and GeneticAlgorithm
        GridSearch 
    Performs an Exhaustive Search for optimal hyperparameters inside a cross validation process
        RandomSearch 
    Performs a Random Search for optimal hyperparameters inside a cross validation process
        GeneticAlgorithm
        NOT CODED YET
    """
    def __init__(self, algo, calib_type, hp_grid, cv, scoring, n_iter=None):
        self.cv = cv
        self.algo = algo
        self.scoring = scoring
        self.hp_grid = hp_grid
        self.best_hp = {}
        if calib_type == 'GridSearch':
            self.hp_iterator = ParameterGrid(self.hp_grid)
        elif calib_type == 'RandomSearch':
            self.hp_iterator = ParameterSampler(self.hp_grid, n_iter)
        elif calib_type == 'GeneticAlgorithm':
            self.hp_iterator = GeneticAlgorithm(self.hp_grid, n_iter)

    def compute_cv(self, X, Y):
        """ Function that operate the cross validation
        Let us notive that this code is similar for the three different cross validation
        However the iterator that will yield the tested parameters differs
        """
        best_score = -np.Inf
        for hp in self.hp_iterator:
            self.algo.set_hyperparams(**hp)
            score = []
            for train, test in self.cv.split(X, Y):
                self.algo.fit(X.iloc[train], Y.iloc[train])
                pred_values = self.algo.predict(
                    X.iloc[test]
                )  # Be careful not to stock predicted values in the algo, since it is only temporary internal results
                self.algo.compute_outputs(Y.iloc[test], pred_values,
                                          self.scoring)
                score.append(getattr(self.algo, self.scoring))
                self.algo.reset_outputs(
                )  # For safety, it is currently needed, please do not change without rethinking the code
            score_mean = np.mean(score)
            if isinstance(self.hp_iterator,
                          GeneticAlgorithm) == 'GenericAlgorithm':
                self.hp_iterator.update_score(score_mean)
            if score_mean > best_score:
                best_score = score_mean
                self.best_hp = hp
        return self
    def run_genetic_algorithm_parallel(self, i):
        validated_data = copy.copy(self.data[list(
            self.valid_attributes.columns)])
        validated_data[self.response] = self.response_data.values

        ga = GeneticAlgorithm(data=validated_data,
                              response=self.response,
                              attributes=list(self.valid_attributes.columns),
                              evaluation=self.evaluation,
                              seed=i,
                              one_out=self.one_out,
                              model_config=self.model_config,
                              **self.ga_config["config"])
        ga.execute(**self.ga_config["mutate_config"])
        return ga.best_models.s_heap
Beispiel #30
0
    def __init__(self, m=25.0, c=25.0, RedStd=5.0, randomseed=250192):
        """
		Instantiates the class by synthetically generating data.
		"""
        GeneticAlgorithm.__init__(self,
                                  nParams=2,
                                  nPop=100,
                                  nGen=1000,
                                  p_m=0.05)

        self.X = np.linspace(-10, 10, 25)
        self.delta = np.random.uniform(low=-1 * RedStd,
                                       high=RedStd,
                                       size=len(self.X))
        self.Y = (m * self.X + c) + self.delta
Beispiel #31
0
def genetic(graph):
    cached.clear()
    start = time.time()
    nTournament = 6
    probability = 0.05
    nPopulation = 100
    nIterations = 500
    nElite = 30

    genetic = GeneticAlgorithm(
        nPopulation, nIterations, nElite, nTournament, probability, graph)
    solution = genetic.genetic_algorithm()
    end = time.time()
    duration = end - start
    return duration
Beispiel #32
0
from genetic_algorithm import GeneticAlgorithm

GA = GeneticAlgorithm()
GA.run()