def run_genetic_algorithm(): generation = 0 bin_population = generate_population(X_train) for i in range(GENERATIONS): X_train_local, Y_train_local = get_ds_from_population( X_train, bin_population) sizes = get_sizes( bin_population ) # get the sizes of the new populations for the networks inputs nets = create_nn_array( sizes) # we create a list of neural networks with predefined size accuracy, max_acc, min_loss, BEST_CHROMOSOME = train( nets, X_train_local, Y_train_local, X_test, Y_test, bin_population) # we train EPOCHS number for each network first_candidate, second_candidate = selection(accuracy, bin_population) new_candidate = cross_over(first_candidate, second_candidate) new_candidate = mutation(new_candidate, p=0.01) bin_population = [new_candidate] bin_population += [ mutation(new_candidate, p=0.2) for i in range(POPULATION_SIZE - 1) ] generation += 1 accuracies.append(max_acc) losses.append(min_loss) print("Training on generation {}".format(generation))
def run_genetic_algorithm(): generation = 0 global population for i in range(200): print("Training generation {}".format(generation)) sizes = get_sizes( population ) # get the sizes of the new populations for the networks inputs nets = create_nn_array( sizes) # we create a list of neural networks with predefined size losses, BEST_CHROMOSOME, max_accuracy = train( nets, X_train, Y_train, X_test, Y_test, population) # we train EPOCHS number for each network losses = get_probab(losses) # we select the one with the smallest loss first_candidate, second_candidate = selection(losses) first_offspring, second_offspring = cross_over( population[first_candidate], population[second_candidate] ) # cross over between top 2 candidates first_offspring = mutation(first_offspring) # we mutate the result population = [first_offspring] population += [ mutation(first_offspring) for i in range(POPULATION_SIZE - 1) ] # create a population of individuals based on the best candidates population = check_population( sizes, population) # we make sure no inidividual is only 0's generation += 1 accuracies.append(max_accuracy) if BEST_CHROMOSOME: chromosomes.append(BEST_CHROMOSOME)
def reproduce(): int p1 = random.randint(0, MATING_POOL_SIZE) int p2 = random.randint(0, MATING_POOL_SIZE) ch1, ch2 = single_point_crossover(mating_pool[p1], mating_pool[p2]) #save children ch1 = mutation(ch1) ch2 = mutation(ch2) #save mutated children child_population.append([(ch1, find_fitness(ch1))]) child_population.append([(ch2, find_fitness(ch2))])
def test_roboticTravel(self): f = open("generations.txt", "w+") utilities.assignProbabilities(self.robots) x = 10 for i in range(x): utilities.roboticTravel(self.robots, self.floor) #utilities.printDetailedPositions(self.robots) distancePoints = utilities.distancePoint(self.robots) #utilities.printRobots(self.robots) utilities.writeInFile(self.robots, f) if (i == x - 1): utilities.printRobots(self.robots) self.robots = genetic.crossGen(distancePoints, self.robots) genetic.mutation(self.robots) f.close()
def test_mutation(self): population = np.array([[1, 0, 1], [1, 1, 1]]) prob_mut = 1.0 possible_values = [0, 1] np.testing.assert_equal( ga.mutation(population, prob_mut, possible_values), np.array([[0, 1, 0], [0, 0, 0]]))
def generate_population(): global population population = [] tmp = [generate_genome() for _ in range(POPULATION_SIZE)] for i in range(0, len(tmp)): tmp[i] = mutation(tmp[i]) population.append((tmp[i], find_fitness(tmp[i])))
def reproduce(): global ch11 global ch22 global mating_pool global child_cnt p1 = random.randint(0, MATING_POOL_SIZE - 1) p2 = random.randint(0, MATING_POOL_SIZE - 1) print("REPRODUCTION") print("Parent 1") print(mating_pool[p1]) print("Parent 2") print(mating_pool[p2]) # single_point_crossover(mating_pool[p1][0], mating_pool[p2][0]) cross_over(mating_pool[p1][0], mating_pool[p2][0]) ch1 = ch11 ch2 = ch22 print("CHILD: " + str(child_cnt)) print(ch1) ch1 = mutation(ch1) fitness_ch1 = find_fitness(ch1) print("MUTATED CHILD: " + str(child_cnt)) print((ch1, fitness_ch1)) child_cnt = child_cnt + 1 print("CHILD: " + str(child_cnt)) print(ch2) ch2 = mutation(ch2) fitness_ch2 = find_fitness(ch2) print("MUTATED CHILD: " + str(child_cnt)) print((ch2, fitness_ch2)) child_cnt = child_cnt + 1 # save children # print(type(ch1)) # print(ch1) # ch1 = mutation(ch1) # ch2 = mutation(ch2) # save mutated children child_population.append((ch1, fitness_ch1)) child_population.append((ch2, fitness_ch2))
def test_mutation(function1, function2): """Test mutation function""" population = [ [1523, 42, 0, 1, 1, 2045, 537, 1, 1, 2, 2, 0, 0], [1971, 117, 0, 1, 0, 1140, 1737, 1, 1, 2, 2, 0, 0], [882, 101, 1, 0, 0, 986, 644, 0, 1, 1, 5, 0, 0], [1529, 70, 1, 1, 1, 1462, 1834, 0, 0, 1, 1, 1, 0], ] expected_result = [[1523, 42, 0, 1, 1, 2045, 537, 1, 1, 2, 2, 0, 0], [1971, 117, 0, 1, 0, 1140, 1737, 1, 1, 2, 2, 0, 0], [882, 101, 1, 0, 0, 986, 644, 0, 1, 1, 5, 0, 0], [1529, 70, 1, 1, 1, 1462, 1834, 0, 0, 1, 1, 1, 0]] result = genetic.mutation(population) assert (result == expected_result)
print('Number of creatures with best fitness : ', (fitness == np.max(fitness)).sum()) # The best result in the current generation. print("Best result : ", best_outputs[-1]) # Selecting the best parents for mating. parents = genetic.select_mating_pool(new_population, fitness, n_parents) # Generating next generation. offspring_crossover = genetic.crossover( parents, offspring_size=(population_shape[0] - parents.shape[0], n_features)) # Adding some variations to the offspring using mutation. offspring_mutation = genetic.mutation(offspring_crossover, n_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 finishing all generations. # At first, the fitness is calculated for each solution in the final generation. fitness = genetic.pop_fitness(X_train, X_test, y_train, y_test, new_population) # Then return the index of that solution corresponding to the best fitness. best_match_idx = np.where(fitness == np.max(fitness))[0] best_match_idx = best_match_idx[0] best_solution = new_population[best_match_idx, :] best_solution_indices = np.flatnonzero(best_solution) best_solution_num_elements = best_solution_indices.shape[0]
def main(num_bars: int, num_notes: int, num_steps: int, pauses: bool, key: str, scale: str, root: int, population_size: int, num_mutations: int, mutation_probability: float, bpm: int): folder = str(int(datetime.now().timestamp())) population = [ generate_genome(num_bars * num_notes * BITS_PER_NOTE) for _ in range(population_size) ] s = Server().boot() population_id = 0 running = True while running: random.shuffle(population) population_fitness = [(genome, fitness(genome, s, num_bars, num_notes, num_steps, pauses, key, scale, root, bpm)) for genome in population] sorted_population_fitness = sorted(population_fitness, key=lambda e: e[1], reverse=True) population = [e[0] for e in sorted_population_fitness] next_generation = population[0:2] for j in range(int(len(population) / 2) - 1): def fitness_lookup(genome): for e in population_fitness: if e[0] == genome: return e[1] return 0 parents = selection_pair(population, fitness_lookup) offspring_a, offspring_b = single_point_crossover( parents[0], parents[1]) offspring_a = mutation(offspring_a, num=num_mutations, probability=mutation_probability) offspring_b = mutation(offspring_b, num=num_mutations, probability=mutation_probability) next_generation += [offspring_a, offspring_b] print(f"population {population_id} done") events = genome_to_events(population[0], num_bars, num_notes, num_steps, pauses, key, scale, root, bpm) for e in events: e.play() s.start() input("here is the no1 hit …") s.stop() for e in events: e.stop() time.sleep(1) events = genome_to_events(population[1], num_bars, num_notes, num_steps, pauses, key, scale, root, bpm) for e in events: e.play() s.start() input("here is the second best …") s.stop() for e in events: e.stop() time.sleep(1) print("saving population midi …") for i, genome in enumerate(population): save_genome_to_midi( f"{folder}/{population_id}/{scale}-{key}-{i}.mid", genome, num_bars, num_notes, num_steps, pauses, key, scale, root, bpm) print("done") running = input("continue? [Y/n]") != "n" population = next_generation population_id += 1
parents = genetic.mating_pool(pop_inputs, objective.copy(), num_parents_mating) print("Parents") print(parents) parents = numpy.asarray(parents) # Crossover to generate the next geenration of solutions offspring_crossover = genetic.crossover( parents, offspring_size=(int(num_parents_mating / 2), pop_inputs.shape[1])) print("Crossover") print(offspring_crossover) # Mutation for population variation offspring_mutation = genetic.mutation(offspring_crossover, sol_per_pop, num_parents_mating, mutation_percent=mutation_percent) print("Mutation") print(offspring_mutation) # New population for generation g+1 pop_inputs[0:len(offspring_crossover), :] = offspring_crossover pop_inputs[len(offspring_crossover):, :] = offspring_mutation print('NEW INPUTS :\n', pop_inputs) for x in range(len(list_inputs)): for y in range(len(list_inputs[0])): pre_list = list_inputs[x][y] for m in range(len(list_fitness[x][y])): pre_list.append(list_fitness[x][y][m])
# print('Best :' , sa.BS, ' Score : ', sa.B) # sa.B = 100000 # # print('--------') # sa.search('3') # print('Best :' , sa.BS, ' Score : ', sa.B) genetic = genetic.Genetic() genetic.problem = c genetic.generate_chromosome() while not genetic.end(): print('Spin : ', genetic.currentGen) genetic.evaluation_fitness() genetic.select_chromosome() genetic.cross_over() genetic.mutation() genetic.answer() c_time = genetic.bestG python_time = genetic.meanG new_time = genetic.worstG plt.savefig('result.pdf') fig = plt.figure(1) ax = plt.axes([0.1, 0.1, 0.8, 0.8]) setp(ax, 'frame_on', False) # Plot here ############################################## degree = np.arange(0, len(c_time))
def mutation(i): return frombin(genetic.mutation(tobin(i)))
if np.sum(np.array(list(need.values()))) != 0: print("running GA for ", need) #print("making init pop") header, init_pop = GA.make_initial_population( need, population_number) # print("header", header) # print("init_pop", init_pop) parents = copy.deepcopy(init_pop) for i in range(generation_number): header, parents = GA.selection(header, parents, population_number, G) # print("selection header", header) # print("selection parents", parents) new_generation = GA.cross_over(parents) # print("cross over", new_generation) new_generation = GA.mutation(new_generation, population_number) # print("mutation", new_generation) parents = copy.deepcopy(new_generation) # print(str(i/generation_number)+"% GA done; of "+str(index/_len_template)+"%.") # print("\n") #calculate fintness and select best answer fitness_score = [] for pop in new_generation: fitness_score.append(GA.fitness(pop, header, G)) # print("fitness_score", fitness_score) genetic_output = np.unique(np.sort(np.array( [[i, j] for i, j in zip( header, new_generation[fitness_score.index( max(fitness_score))])]),