def simulate(target: np.ndarray) -> None: """ Start main GA loop :param target: target image """ population = generate_population(POPULATION_SIZE, target.shape, default_color=BACKGROUND_COLOR) fitness = calculate_population_fitness(population, target) start = time() print("Started evolution") for step in range(4294967296): # 2^32 parents = select_breeding_pool(population, fitness, BREEDING_INDIVIDUALS) crossover = do_crossover(parents, BREEDING_INDIVIDUALS, target.shape, CROSSOVER_INDIVIDUALS) mutation = mutate(crossover, target.shape, CROSSOVER_INDIVIDUALS, LINE_LENGTH, target) population[0:parents.shape[0], :] = parents population[parents.shape[0]:, :] = mutation fitness = calculate_population_fitness(population, target) best_ind_index = np.argmin(fitness) best_ind = population[best_ind_index] cv2.imshow("Current-min", best_ind) cv2.waitKey(1) if step % 500 == 0: print('%.6d - %.6f seconds' % (step, (time() - start)), end='\t\t') print('Fitness -\t{}'.format(np.min(fitness))) best_ind_index = np.argmin(fitness) best_ind = population[best_ind_index] cv2.imwrite(f"./out/{step}-{fitness[best_ind_index]}.jpg", best_ind)
def run(self, niters, save=True): ''' run a random mutation hill climber args: niters: # of iterations ''' from utils import path start = time.time() self.fitness_hist = np.zeros(niters) for t in range(niters): # mutate the current best ordering by swapping a pair of points at random new_path = path(mutate(self.best_path.order), self.dmatrix, findShortest=self.findShortest) # compare to current best path and replace if better if new_path.f > self.best_fitness: self.best_path = new_path self.best_fitness = new_path.f self.best_path_length = new_path.d# self.best_path.calc_length() # log current best self.fitness_hist[t] = self.best_fitness if (t + 1) % 2000 == 0: print("\rRMHC run {}: {}/{} evaluations complete - best length = {}".format(self.run_idx, t + 1, niters, self.best_path_length), end="") sys.stdout.flush() end = time.time() print ('\nTotal time: {:.3f} min'.format((end-start)/60.0)) if save: s = 'short' if self.findShortest else 'long' path = self.log_dir + 'RMHC_{}evals_TSP{}_{}_run{}_'.format(niters, self.prob, s, self.run_idx) np.savetxt(path + 'fitness_hist.csv', self.fitness_hist, delimiter=',') np.savetxt(path + 'best_path.csv', self.best_path.order, delimiter=',') print ('\nSaved')
while (generation < MAX_ITERATION): selected_population = [] new_population = [] elitism_selecteds_size = POPULATION_SIZE - int( (POPULATION_SIZE * SELECTION_PERCENT) / 100) new_population.extend(get_bests(population, elitism_selecteds_size)) for i in range(int((POPULATION_SIZE * SELECTION_PERCENT) / 100)): selected_population.append(roulette_selection(population)) selected_population = zip( selected_population, selected_population[int(len(selected_population) / 2):]) for x in selected_population: sons = crossover(x[0].gene, x[1].gene) new_population.extend(sons) population_to_mutate = int((POPULATION_SIZE * MUTATION_PERCENT) / 100) for i in range(population_to_mutate): new_population[random.randint(0, POPULATION_SIZE - 1)] = mutate( new_population[random.randint(0, POPULATION_SIZE - 1)].gene) population = new_population best_solution = best(population).fitness generation += 1 print(best(population).gene)
def run(self, population_size=100, n_gens=1000, p_cross=0.7, p_mut=0.5, roulette=False): ''' run the algorithm for n_gens evaluations args: population_size: size of population n_gens: number of evaluations to run p_cross: the crossover probability p_mut: the mutation probability ''' population = [] # initialize each chromosome as a random permutation of the points (by index) for _ in range(population_size): population.append( path(np.random.permutation(self.N), self.dmatrix, findShortest=self.findShortest)) self.fitness_hist = [] self.best_path = None gen = 0 self.best_fit = max([x.f for x in population]) self.best_path_length = -1.0 * self.best_fit if self.findShortest else self.best_fit fitness_convergence = [] total_start = time.time() gen_start = time.time() while gen < n_gens: # population fitness fitness_raw = np.asarray([x.f for x in population]) # record population convergence cnum = -12.56 if self.prob == 1 else -30.0 fitness_convergence.append( sum(fitness_raw > cnum) / float(population_size)) # normalize fitness values to use as a valid probability dist fitness_norm = fitness_raw / np.sum(fitness_raw) gen_best_idx = np.argmax(fitness_raw) gen_best_fit = fitness_raw[gen_best_idx] gen_best_path = population[gen_best_idx] gen_best_length = -1.0 * gen_best_fit if self.findShortest else gen_best_fit gen_mean_fit = np.mean(fitness_raw) if gen_best_fit > self.best_fit: self.best_path = gen_best_path self.best_path_length = gen_best_length self.best_fit = gen_best_fit # repeat until population_size offspring have been created new_population = [gen_best_path] # elitism while (len(new_population) < population_size): if roulette: # roulette wheel selection: parent1_idx, parent2_idx = np.random.choice( np.arange(population_size), size=2, replace=True, p=fitness_norm) parent1, parent2 = population[parent1_idx], population[ parent2_idx] else: # tournament selection: k = 24 tourn1 = np.random.choice(np.arange(population_size), size=k, replace=False) tourn1 = [population[i] for i in tourn1] parent1 = max(tourn1, key=lambda p: p.f) tourn2 = np.random.choice(np.arange(population_size), size=k, replace=False) tourn2 = [population[i] for i in tourn2] parent2 = max(tourn2, key=lambda p: p.f) # crossover parents with probability p_cross do_cross = random.random() if do_cross < p_cross: child1o, child2o = cross_over(parent1.order, parent2.order) else: child1o, child2o = (parent1.order, parent2.order) # mutate offspring r1, r2 = np.random.rand(2) if r1 < p_mut: child1o = mutate(child1o) if r2 < p_mut: child2o = mutate(child2o) # add offspring to new population child1 = path(child1o, self.dmatrix, findShortest=self.findShortest) child2 = path(child1o, self.dmatrix, findShortest=self.findShortest) gen += 2 self.fitness_hist += [gen_best_fit, gen_best_fit] best_p = parent2 if parent2.f > parent1.f else parent1 best_c = child1 if child1.f > child2.f else child2 new_population.append(best_c) new_population.append(best_p) # break off if len(new_population) > population_size: new_population = new_population[:population_size] if gen % 100 == 0: gen_end = time.time() print( '\rGA run {} evaluation {:d}/{:d}: best fitness = {:.4f}, mean fitness = {:.9f},' .format(self.run_idx, gen, n_gens, gen_best_fit, gen_mean_fit) + ' overall best path = {:.3f}; {:.3f} secs/gen'.format( self.best_path_length, (gen_end - gen_start) / 100.0), end="") sys.stdout.flush() gen_start = time.time() population = new_population total_end = time.time() print('\nSaving results...') s = 'short' if self.findShortest else 'long' prefix = 'saved/GA2_{}evals_TSP{}_{}_run{}' np.savetxt(prefix.format(n_gens, self.prob, s, self.run_idx) + '_fitness_hist.csv', np.asarray(self.fitness_hist), delimiter=',') np.savetxt(prefix.format(n_gens, self.prob, s, self.run_idx) + '_best_path.csv', np.asarray(self.best_path.order), delimiter=',') np.savetxt(prefix.format(n_gens, self.prob, s, self.run_idx) + '_convergence.csv', np.asarray(fitness_convergence), delimiter=',') print('Done. \nTotal training time: {:.3f} min'.format( (total_end - total_start) / 60.0))
def mutate(cont): utils.mutate(cont, Player)
def mutate(cont): utils.mutate(cont, Car)
def mutate(self, bitErrRate): self.setNet(utils.mutate(self.neural_net.get_weights(), bitErrRate))
m2 = utils.tournament_selection(population, 50) child = utils.crossover(m1[0], m2[0]) child = [child, utils.calc_score(child, accept, reject)] new_pop.append(child) break except: pass for _ in range(100): new_pop.append(gen_individual(accept, reject)) for _ in range(100): while True: try: a = random.choice(population) b = utils.mutate(a[0]) b = [b, utils.calc_score(b, accept, reject)] new_pop.append(b) break except: pass population = new_pop[:] for tree in population: ii = utils.tree_to_regex(tree[0]) if tree[1] > best[1]: best = [ii, tree[1]] elif tree[1] == best[1]: if len(ii) < len(best[0]): best = [ii, tree[1]]
def mutate(cont): utils.mutate(cont, CustomObject)
parent2 = chromos[selected_chromos[1], :] rand = np.random.uniform(0, 1) xover_ch1 = np.zeros(num_of_customers, dtype=bool) xover_ch2 = np.zeros(num_of_customers, dtype=bool) mut_ch1 = np.zeros(num_of_customers, dtype=bool) mut_ch2 = np.zeros(num_of_customers, dtype=bool) is_xovered = False is_mutated = False if rand <= p_xover: xover_ch1, xover_ch2 = EGAUtils.xover(parent1, parent2) is_xovered = True if rand <= p_mutation: mut_ch1, mut_ch2 = EGAUtils.mutate(parent1, parent2) is_mutated = True number_of_worst_chromo_to_be_deleted = 0 if is_xovered: if EGAUtils.is_GAMCC_satisfied( df_customers=EGAUtils.get_dataframe_by_chromo( df_customer, xover_ch1), bank_required_reserve_ratio=bank_required_reserve_ratio, financial_institutions_deposit=financial_institutions_deposit): chromos = np.vstack((chromos, xover_ch1)) number_of_worst_chromo_to_be_deleted += 1 if EGAUtils.is_GAMCC_satisfied( df_customers=EGAUtils.get_dataframe_by_chromo( df_customer, xover_ch2), bank_required_reserve_ratio=bank_required_reserve_ratio,