コード例 #1
0
    def create_next_generation(self):
        parameters_list = [
            game.snake.brain.parameters for game in self.current_generation
        ]

        mating_pool = [
            ga.tournament_selection(parameters_list, self.fitness_list)
            for _ in range(len(parameters_list))
        ]

        nn_architecture = self.current_generation[0].snake.brain.architecture
        parent_chromosomes = [
            ga.flatten_parameters(brain, nn_architecture)
            for brain in mating_pool
        ]
        crossed_chromosomes = []
        for pair in range(0, len(parent_chromosomes), 2):
            for child in ga.crossover(parent_chromosomes[pair],
                                      parent_chromosomes[pair + 1],
                                      self.app.crossover_rate):
                child = ga.mutation(child, self.app.mutation_rate)
                crossed_chromosomes.append(child)

        # reshape parameters in the neural network architecture
        new_parameters = []
        for chromosome in crossed_chromosomes:
            new_parameters.append(
                ga.reshape_parameters(chromosome, nn_architecture))

        self.generation_number += 1
        self.current_generation = [
            Game(self.app.surface, parameters=parameters)
            for parameters in new_parameters
        ]
コード例 #2
0
ファイル: pcarmona.py プロジェクト: gsilvap/cevol
def generations(
        population, pop_size, fitness_func, prob_cross, prob_muta,
        select_parents, muta_method, cross_method, select_survivors,
        max_gener, sizes, max_size, bests_matrix, averages_matrix, current_generation, current_run):
    for gener in range(max_gener):
        mates = select_parents(population, pop_size, 3)
        offspring = crossover(mates, prob_cross, cross_method)
        offspring = mutation(offspring, prob_muta, muta_method)
        offspring = eval_pop(offspring, fitness_func, sizes, max_size)
        population = select_survivors(population, offspring)
        evaluate_generation(
            population, bests_matrix, averages_matrix, current_generation +gener , current_run)
    return population
コード例 #3
0
ファイル: pcarmona.py プロジェクト: gsilvap/cevol
def generations(population, pop_size, fitness_func, prob_cross, prob_muta,
                select_parents, muta_method, cross_method, select_survivors,
                max_gener, sizes, max_size, bests_matrix, averages_matrix,
                current_generation, current_run):
    for gener in range(max_gener):
        mates = select_parents(population, pop_size, 3)
        offspring = crossover(mates, prob_cross, cross_method)
        offspring = mutation(offspring, prob_muta, muta_method)
        offspring = eval_pop(offspring, fitness_func, sizes, max_size)
        population = select_survivors(population, offspring)
        evaluate_generation(population, bests_matrix, averages_matrix,
                            current_generation + gener, current_run)
    return population
コード例 #4
0
input('\n----- press ENTER to start ----- ')


population = GA.population(places, population_size, verbose)

for i in range(number_of_rouds):
    population = GA.selection_and_crossover(
        population,
        number_of_parents,
        lambda x: GA.hs_fitness(x, origin),
        verbose
    )
    population = GA.mutation(
        population,
        number_of_parents,
        probability_of_mutation,
        verbose
    )

route = GA.best_chromossome(
    population,
    lambda x: GA.hs_fitness(x, origin),
    verbose
)
GA.print_route(route, origin)

while len(route) > 1:
    total_remaining_distance = GA.hs_fitness(route, origin)
    recommendation = FUZZY.simulate(fuel_level, total_remaining_distance)
    fuel_level -= 10
    print('\nROUTE CALCULATED RISK:', recommendation)
コード例 #5
0
import genetic_algorithm

image_name = 'C:\\Users\\Dell\\Desktop\\My disk\\Sketches\\init7.jpg'
final_name = 'C:\\Users\\Dell\\Desktop\\My disk\\Sketches\\final7.jpg'
iterations_num = 30

genetic_algorithm.generate_init_pop(image_name)

print('End of initial population\'s generation')

for i in range(1, iterations_num + 1):
    genetic_algorithm.fitness_function()

    genetic_algorithm.selection_function()

    genetic_algorithm.crossover()

    genetic_algorithm.mutation()

    print('End of ' + str(i) + ' iteration')

result = genetic_algorithm.termination()

print('End of termination')

result.save_image(final_name)
コード例 #6
0
ファイル: main.py プロジェクト: jsorry0130/NewPacman
                    chromosome.fitness = pacman.evasion  # 적합도는 유령 회피 성공 수
                    wr.writerow([n_gen, i, pacman.evasion, EndT,
                                 score])  # csv 파일에 게임 결과 기록

                    if pgf.keyPressed('esc'):
                        n_gen = 0
                        break

                if pgf.keyPressed('esc'):
                    break

                # 유전 알고리즘을 이용한 진화 시작
                if best_chromosomes is not None:  # 퇴화 방지를 위해 이전 세대 상위 chromosome 까지 포함
                    chromosomes.extend(best_chromosomes)

                chromosomes.sort(key=lambda x: x.fitness,
                                 reverse=True)  # 적합도를 기준으로 내림차순 정렬

                print('===== Generaton #%s\tBest Fitness %s =====' %
                      (n_gen, chromosomes[0].fitness))  # 세대 끝, 최고 적합도 출력

                best_chromosomes = deepcopy(
                    chromosomes[:N_BEST])  # 상위 chromosome 4개 따로 저장

                ga.crossover(N_CHILDREN, best_chromosomes)  # crossover
                ga.mutation(N_POPULATION, N_BEST, N_CHILDREN, best_chromosomes,
                            PROB_MUTATION, chromosomes)  #mutation

                if pgf.keyPressed('esc'):
                    break
コード例 #7
0
num_generations = 15
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("Best result : ",
          numpy.max(numpy.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(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))
コード例 #8
0
import variables
from genetic_algorithm import (crossover, fitness, get_initial_generation,
                               get_next_generation, get_total_distance,
                               mutation)
from utils import get_named_route, reached_stability
from variables import GENERATION_MAX

generation = get_initial_generation()

print('#gen\tmin\tavg')

for cnt in range(GENERATION_MAX):
    generation = fitness(generation)

    print(
        f'{cnt}\t{get_total_distance(generation[0])}\t{variables.avg_distance}'
    )

    if reached_stability(generation):
        break

    new_individuals = crossover(generation)
    new_individuals.extend(mutation(generation))

    if cnt != GENERATION_MAX - 1:
        generation = get_next_generation(generation, new_individuals)

print('best route:')
print(get_named_route(generation[0]))
print('with total distance:', get_total_distance(generation[0]))
コード例 #9
0
ファイル: algorithm.py プロジェクト: mangitngit/thesis
    def run(self):

        # przypisanie do tablicy gorup_of_melody wszystkich wygenerowanych linii melodyczbych
        for child in range(self.population):
            self.generation.append(Child(self.tacts_number, self.scale))
        for child in self.generation:
            self.group_of_melody.append(child.melody)

        self.plot_y_max = []
        self.plot_y_mean = []

        for iteration in range(self.iterations):
            self.next_generation = []
            self.valuation_probability = []

            # ocena wszystkich linii melodycznych
            self.valuation, self.valuation_probability, self.max_rate, self.medium_rate, self.final_music_argument, \
            self.final_music_value = rating_music(self.group_of_melody.copy(), self.final_music_argument,
                                                  self.final_music_value)
            self.plot_y_max.append(self.max_rate)
            self.plot_y_mean.append(self.medium_rate)

            for sub_iteration in range(self.population):
                self.melody = []

                # wybranie dwóch najlepiej przystosowanych osobników z zadanym prawdopodobieństwem
                self.cross_two_line_arg = []
                self.cross_two_line_arg = chosen_two(
                    self.valuation_probability.copy())

                # krzyżowanie
                flag = np.random.choice([0, 1],
                                        p=[(1 - self.crossing_probability),
                                           self.crossing_probability])
                if flag:
                    self.melody = crossing(
                        self.group_of_melody[
                            self.cross_two_line_arg[0]].copy(),
                        self.group_of_melody[
                            self.cross_two_line_arg[1]].copy(),
                        self.crossing_type)
                else:
                    x = np.random.choice(len(self.group_of_melody))
                    self.melody = self.group_of_melody[x].copy()

                # mutacja
                flag = np.random.choice([0, 1],
                                        p=[(1 - self.mutation_probability),
                                           self.mutation_probability])
                if flag:
                    self.melody = mutation(self.melody.copy(), self.scale,
                                           self.tacts_number).copy()

                # przypisanie do następnej generacji przetworzonej melodii
                self.next_generation.append(self.melody.copy())

            # zastąpienie starej generacji nową
            self.group_of_melody = self.next_generation.copy()

        # dodanie podkłądu do stworzonej linii
        back = []
        chord_progression = [self.tonika, self.subdominata, self.dominata]
        for chord in range(self.tacts_number):
            if chord % 2 == 0:
                back.append(chord_progression[int(chord / 2) % 3])
        back.append(self.tonika)

        # zapisanie wytworzonej muzyki
        self.save = SaveMIDI(self.tempo, self.instrument, self.background,
                             self.file_path)
        self.save.write_midi(self.final_music_argument)
        self.save.write_background(back)

        self.save.save_midi()

        # zapisywanie tabulatury
        for tact in self.final_music_argument:
            for note in tact:
                self.melody_to_tab.append(note)

        save_tab(self.melody_to_tab, self.file_path)

        # czyszczenie tablic
        self.scale = []
        self.generation = []
        self.next_generation = []
        self.melody = []
        self.group_of_melody = []
        self.valuation = []
        self.valuation_probability = []
        self.melody_to_tab = []
        self.victory_melody = []
        self.final_music_value = 0
        self.final_music_argument = []

        # wyświetlenie danych statystycznych
        if self.checkbox:
            plt.figure(1)
            plt.plot([x for x in range(self.iterations)], self.plot_y_max, 'r',
                     [x for x in range(self.iterations)], self.plot_y_mean,
                     'b')
            plt.title('Oceny utworów z funkcji przystosowania')
            plt.xlabel('Generacja')
            plt.ylabel('Ocena')
            red_patch = mpatches.Patch(color='red', label='Maksimum')
            blue_patch = mpatches.Patch(color='blue', label='Średnia')
            plt.legend(handles=[red_patch, blue_patch])

        print("Done")
コード例 #10
0
            # Selecting the best parents in the population for mating.
            parents1 = genetic_algorithm.select_mating_pool(
                stock_values, fit_population, index, num_parents_mating, T,
                lamda, alpha, epsilon, delta, gamma)
            parents2 = genetic_algorithm.select_mating_pool_unfit(
                stock_values, unfit_population, num_parents_mating, T,
                current_portofolio, starting_time, epsilon, delta, gamma)

            # Generating next generation using crossover.
            offspring_crossover_fit, offspring_crossover_unfit = genetic_algorithm.crossover(
                parents1, parents2, index, stock_values, T, lamda, alpha,
                epsilon, delta, gamma, current_portofolio, starting_time,
                Kappa)

            # Adding some variations to the offspring using mutation.
            offspring_mutation_fit = genetic_algorithm.mutation(
                offspring_crossover_fit, sigma, mutation_chance, Kappa)
            offspring_mutation_unfit = genetic_algorithm.reverse_mutation(
                offspring_crossover_unfit, sigma, mutation_chance)

            if generation % 5 == 0 and generation > 0:
                sigma = max(
                    0,
                    sigma * float((numpy.exp(
                        genetic_algorithm.gaussian_mutation(0, 1)))))

            # Creating the new population based on the parents and offspring.
            fit_population = genetic_algorithm.new_populations_fit(
                fit_population, offspring_mutation_fit, stock_values, index, T,
                current_portofolio, starting_time, lamda, alpha, epsilon,
                delta, gamma)