def breed_loop(N, data, gdata, save_interval): ffts = [] min_errs = [] for n in range(N): # print("Generation:", n) errors, goal = gen.fit_all(data, gdata) new_data = np.zeros(np.shape(data)) for i in range(len(data)//2): if goal: print("Goal!") r = np.arange(len(errors)) i1, i2 = np.random.choice(r, 2, p=errors) cross1, cross2 = gen.crossover(data[i1], data[i2]) cross1, cross2 = gen.mutate(cross1, get_temp(n+1)), gen.mutate(cross2, get_temp(n+1)) # cross1, cross2 = gen.mutate(cross1, .5), gen.mutate(cross2, .5) new_data[i], new_data[i+(len(data)//2)] = cross1, cross2 if n % save_interval == 0 and i == 0: play_fft(cross1) data = new_data if n % 25 == 0: print(f'min error {np.amin(errors)}') min_errs.append(np.amin(errors)) return ffts, min_errs
def main(): pop_size = 1000 max_runs = 50 mutate_ratio = 0.2 # Which data set to use. mode = 1 random.seed() pop = [] # Create a random population of trees. for i in range(pop_size): pop.append(ExprTree(mode)) print "Population created." for tree in pop: print tree for i in range(max_runs): print "Beginning crossover " + str(i) + ":" # Crossover and mutate population. genetic.mutate(pop, mutate_ratio, mode) pop = genetic.crossover(pop, mode) print "Crossover " + str(i) + " complete."
def main(): map_size = 100 p_type = 10 # dont get when we will use it max_route_length = 150 population_size = 30 number_of_each_new_generation = 10 number_of_couples = int( (population_size - number_of_each_new_generation) / 2) probability = 0.05 the_map = initialize(p_type, map_size) population = create_starting_population(max_route_length, population_size, the_map) last_distance = 1000000000 for i in range(0, 100): scores = score_population(population, the_map) new_population = [] best = population[np.argmin(scores)] number_of_moves = len(best) distance = fitness(best, the_map) if distance != last_distance: print( 'Iteration %i: Best so far is %i steps for a distance of %f' % (i, number_of_moves, distance)) plot_best(the_map, best, i) for j in range(0, number_of_couples): new_route1, new_route2 = crossover( population[pick_breeder(scores)], population[pick_breeder(scores)]) new_population.extend([new_route1, new_route2]) # mutate the current members of new_population for j in range(0, len(new_population)): new_population[j] = mutate(new_population[j], probability, the_map) new_population.append(population[np.argmin(scores)]) while len(new_population) < population_size: new_population.append(create_new_member(max_route_length, the_map)) population = new_population[::] # copy a values
new_population) print('Generation calculation time : ', time.time() - calculation_time) best_outputs.append(np.max(fitness)) 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]
###################################################################### # GA Program #3: Simulates crossover events between 2 chromosomes ###################################################################### import sys, os sys.path.append(os.path.join(os.path.dirname(os.getcwd()), 'src')) import genetic as g c1 = g.Chromosome([0]*50, [1,2,3,4]) # integer chromosome c2 = g.Chromosome(['A']*50, ['A','B','C','D']) # alphabet chromosome print('INITIAL CHROMOSOMES ==================================') print('Integer chromosome sequence: ' + str(c1.sequence)) print('Alphabet chromosome sequence: ' + str(c2.sequence)) for x in range(10, 50, 10): print() (g1, g2) = g.crossover(c1, c2, x) print('Crossover at base ' + str(x)) print('Integer chromosome sequence: ' + str(g1.sequence)) print('Alphabet chromosome sequence: ' + str(g2.sequence))
###################################################################### # GA Program #3: Simulates crossover events between 2 chromosomes ###################################################################### import sys, os sys.path.append(os.path.join(os.path.dirname(os.getcwd()), 'copads')) import genetic as g c1 = g.Chromosome([0] * 50, [1, 2, 3, 4]) # integer chromosome c2 = g.Chromosome(['A'] * 50, ['A', 'B', 'C', 'D']) # alphabet chromosome print('INITIAL CHROMOSOMES ==================================') print('Integer chromosome sequence: ' + str(c1.sequence)) print('Alphabet chromosome sequence: ' + str(c2.sequence)) for x in range(10, 50, 10): print() (g1, g2) = g.crossover(c1, c2, x) print('Crossover at base ' + str(x)) print('Integer chromosome sequence: ' + str(g1.sequence)) print('Alphabet chromosome sequence: ' + str(g2.sequence))
list_fitness.append(fitness) list_objective.append(objective) list_inputs.append(pop_inputs.tolist()) list_other_metrics.append(other_metrics) # top performance ANN model in the population are selected for mating. 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
def crossover(i, j): return [frombin(i) for i in genetic.crossover(tobin(i), tobin(j))]
while iter < MAX_NUM_ITER: print('Generación Numero: ', iter) poblacionDecimal = genetic.poblacionEnDecimal(poblacion, ORDEN_MATRIZ, BITS_GEN) #print(poblacionDecimal) poblacionFit = genetic.poblacionFitness(poblacionDecimal, OBJETIVO) print('Fitness de la Poblacion: ', poblacionFit) poblacionEmparejada = genetic.generaParejas(poblacionFit, poblacion, N_BITS) #print(poblacionEmparejada) poblacionCruzada = genetic.crossover(PUNTOS_CROSSOVER, poblacionEmparejada) #print(poblacionCruzada) poblacionNueva = genetic.mutacion(FACTOR_MUTACION, NUM_BITS_MUTADOS, poblacionCruzada) #print(poblacionNueva) poblacion = poblacionNueva print('Mejor fitness: ', min(poblacionFit)) print('Peor fitness: ', max(poblacionFit)) promedio = sum(poblacionFit) / len(poblacionFit) print('Promedio: ', promedio) if min(poblacionFit) == 0: posicion = poblacionFit.index(min(poblacionFit))