def iteration(self): """ 算法迭代主程序 :return: 最后迭代完成的排序,去重的种群 """ node_count = len(self.read_json()) pop = population(self.pop_size, self.individuals_num, node_count) node_dirt = self.read_json() func_obj = MinMax2(pop, node_dirt) for i in range(self.iterations_num): copy_pop = pop.copy() selection(pop, func_obj) crossover(pop, self.cross_probability) mutation(pop, self.mutation_probability, node_count - 1) origin_pop = pop temp_pop = vstack((copy_pop, origin_pop)) func_obj = MinMax2(temp_pop, node_dirt) pop = dominanceMain(temp_pop, func_obj) print("第 %d 次迭代" % i) # estimate(pop, func_obj) pop_node = array(list(set([tuple(sorted(t)) for t in pop]))) # 个体按数值大小排序, 去重 return pop_node
def genetic(f): N = 1000 x = 2 select_p = 0.5 mutate_chance = 0.01 inputs = list(range(6)) outputs = [f(x) for x in inputs] population = [generate() for i in range(N)] #results = [interpret(code)(x) for code in population] #pprint(results) while True: scores = [evaluate(code, inputs, outputs) for code in population] size = len(scores) selected_indices = list(sorted(range(size), key=lambda t : scores[t]))[:int(select_p * size)] selected = [population[i] for i in selected_indices] selected_scores = [scores[i] for i in selected_indices] if 0.0 in selected_scores: print('Selected:') pprint(selected[0]) break crossover(selected) mutated = [mutate(code) if random.random() < mutate_chance else code for code in selected] population = [generate() for i in range(N)]
def next_generation(self, mutation_setup): """ Swap current population with new individuals """ # matching individuals # sorted by fitness self.individuals.sort(key=lambda x: x.fitness) for i, m_individual in enumerate(self.individuals): if m_individual.paired_with != -1: continue # skip already matched individuals # for now: match next one m_try = i + 1 if i < len(self.individuals) else i - randint(1, 3) # safechecks if m_try < 0 or m_try >= len(self.individuals): continue if m_try == i: continue if self.individuals[m_try].paired_with != -1: continue # assign mate m_individual.paired_with = m_try self.individuals[m_try].paired_with = i # mutations for i, _ in enumerate(self.individuals): mutate(self.individuals[i].genome, mutation_setup) # crossing overs for i, _ in enumerate(self.individuals): if self.individuals[i].paired_with == -1: continue crossover(self.individuals[i].genome, events=1) # offspring new_individuals = [] for i, o_individual in enumerate(self.individuals): if o_individual.paired_with == -1: continue # skip lone individuals # probability of offspring dictated by fitness # algorithm: 100% for every full 1, probability # 0.1=10% for all other offspring_to_make = o_individual.fitness while offspring_to_make > 0.01: if offspring_to_make < 1: if randint(0, 100) > offspring_to_make * 100: break # under 1 -> no more offspring offspring_to_make -= 1 new_individuals.append( Individual(genome=Genome( cod_seqA=o_individual.genome.haploid(), cod_seqB=self.individuals[ o_individual.paired_with].genome.haploid(), ), )) # finish line self.individuals = new_individuals
def next_generation(previous_generation): next_generation = [] if (previous_generation == None): for _ in range(constant.mew): individual = Individual() #individual.set_fitness(classification_rate(individual.features) #print(str(individual.features)+" fitness: "+str(individual.fitness)) next_generation.append(individual) return next_generation #individuls retained from previous population individuals_to_retain = best_individuals(previous_generation, constant.retain_previous) for individual in individuals_to_retain: #print("retained"+str(individual.features)+" fitness: "+str(individual.fitness)) next_generation.append(individual) #crossover population #mating_pool=[] #for _ in range(constant.mating_pool_size): #to_mate=select_individual(previous_generation) #mating_pool.append(to_mate) for _ in range(constant.mew - constant.retain_previous): male = select_individual(previous_generation) #print("male selected for mating"+str(male.features)+" fitness: "+str(male.fitness)) female = select_individual(previous_generation) #print("female selected for mating"+str(female.features)+" fitness: "+str(female.fitness)) child = crossover(male, female) #print("after crossover"+str(child.features)+" fitness: "+str(child.fitness)) mutated_child = mutate(child) #print("after mutation"+str(mutated_child.features)+" fitness: "+str(mutated_child.fitness)) next_generation.append(mutated_child) return next_generation
def genetic(): ITERATIONS = 30 POP_SIZE = 40 CROSSOVER_RATE = 0.5 MUTATION_RATE = 0.01 TOURNAMENT_SIZE = 6 task = read('generatedTaskFile.csv') print("Here it goes...") population = init_population(task.numberOfObjects, POP_SIZE, task) i = 0 while i < ITERATIONS: print("New iteration") j = 0 new_population = Population(task) new_population.listOfIndividuals = [] while j < POP_SIZE: parent1 = tournament(population, TOURNAMENT_SIZE, task) parent2 = tournament(population, TOURNAMENT_SIZE, task) child = Individual() child.itemsTaken = crossover(parent1, parent2, CROSSOVER_RATE) mutate(child, MUTATION_RATE) new_population.addIndividualToPopulation(child) j += 1 population = new_population i += 1 return population.best()
def _aux(aux_params): number_of_variables = aux_params['number_of_variables'] previous_generations_top = [] for i in range(aux_params['iterations']): seed = aux_params['pool'] test_params = aux_params debug._format_output(['{a} Seed'.format(a=i)] + seed, number_of_variables) solved, pool = _is_solved(test_params, previous_generations_top) previous_generations_top.append(pool) if len(previous_generations_top) > 13: previous_generations_top.pop(0) if solved: return pool test_params['pool'] = reproduction.reproduce(test_params) debug._format_output(['reproduction'] + test_params['pool'], number_of_variables) test_params['pool'] = crossover.crossover(test_params) debug._format_output(['crossover'] + test_params['pool'], number_of_variables) test_params['pool'] = mutation.mutate_pool( test_params['pool'], test_params['mutation_probability']) debug._format_output(['mutated'] + test_params['pool'], number_of_variables) aux_params['pool'] = test_params['pool'] return previous_generations_top[-1]
def operate(gen_in, mu_in, lamb_da_in, boundary_in, gen, maxgen): crosser = np.random.randint(0, 7) lambda_gen = crossover(crosser, gen_in, mu_in, lamb_da_in, objective_function, BLX_alpha=0.5, SPX_epsilon=1, SBX_n=2, UNDX_sigma_xi=0.8, UNDX_sigma_eta=0.707, DE_K=0.5, DE_F=0.3) mutant = np.random.randint(0, 7) lambda_gen = mutate(mutant, lambda_gen, boundary_in, gen, objective_function, normal_sigma=0.5, uniform_pm=0.1, boundary_pm=0.1, maxgen=maxgen, b=5, cauchy_sigma=0.5, delta_max=20, n=2, DE_K=0.5, DE_F=0.3) fixme = np.random.randint(0, 2) return fix(fixme, lambda_gen, boundary_in)
def solve(self): """ This method solves the problem using NTGA algorithm """ generation_limit = int(config.get('run_config', 'generation_limit')) self.generate_initial_population() new_population = [] print("Generation limit:", str(generation_limit)) for i in range(generation_limit): print("generation: ", i) self.population = self.evaluate(self.population) self.non_dominated_set.adds(self.population) while len(new_population) < self.population_size: parents = self.selection() children = mutation(crossover(parents)) for child in children: count = 0 while (child in new_population) or children[0] == children[1]: count += 1 mutate(child) if count > 100: break new_population += children self.population = new_population new_population = [] return self.non_dominated_set
def genetic_algorithm(tournament_size=TOURNAMENT_SIZE, crossover_rate=CROSSOVER_RATE, mutation_rate=MUTATION_RATE, population_size=POPULATION_SIZE): task = read(input_file=OUTPUT_FILE) population = init_population(NUMBER_OF_ITEMS, population_size) best_ind = [] i = 0 new_pop_val = [] while i < ITERATIONS: # print(i) j = 0 new_pop_arr = [] while j < population_size: parent1 = population.tournament(tournament_size, task) parent2 = population.tournament(tournament_size, task) child = crossover(parent1, parent2, crossover_rate) mutated_child = mutate(child, mutation_rate) new_pop_arr.append(mutated_child) j += 1 population = Population(new_pop_arr) i += 1 best_from_pop = population.tournament(population_size, task) best_evaluated = best_from_pop.best_individual(task) new_pop_val.append(best_evaluated) return new_pop_val
def reproduce(population, fitness, mutation_rate): """ Generates next generation of population by probabilistically choosing mating pool based on fitness, then probabilistically reproducing molecules in the mating pool and randomly mutating the children :param population: list of RDKit molecules :param fitness: probability distribution of same length as population, returned by pop_fitness :param mutation_rate: hyperparameter determining the likelihood of mutations occuring :return: new_population """ mating_pool = [] for i in range(len(population)): mating_pool.append(np.random.choice(population, p=fitness)) new_population = [] for n in range(len(population)): parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) # print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B) new_child = co.crossover(parent_A, parent_B) # print new_child if new_child is not None: new_child = mu.mutate(new_child, mutation_rate) # print("after mutation",new_child) if new_child is not None: new_population.append(new_child) return new_population
def get_good_solution(task, crossover_rate=CROSSOVER_RATE, mutation_rate=MUTATION_RATE, tournament_size=TOURNAMENT_SIZE, population_size=POPULATION_SIZE): best_individuals_values = np.empty(MAX_ITERATIONS) population = init_population(task, population_size) outer_iterator = 0 best_individual = 0 best_individual_value = 0 global_best_individual = 0 global_best_individual_value = 0 print('Initial value of the knapsack =', population.individuals[0].evaluate()) while outer_iterator < MAX_ITERATIONS: inner_iterator = 0 new_population = Population() while inner_iterator < population_size: parent1 = tournament(population, tournament_size) parent2 = tournament(population, tournament_size) child = crossover(parent1, parent2, crossover_rate) mutate(child, mutation_rate) new_population.add_individual(child) inner_iterator += 1 best_individual = population.best_individual() best_individual_value = best_individual.evaluate() if best_individual_value >= global_best_individual_value: global_best_individual = best_individual global_best_individual_value = best_individual_value new_population.set_first_individual(global_best_individual) population = new_population best_individuals_values[outer_iterator] = global_best_individual_value outer_iterator += 1 return global_best_individual, best_individuals_values
def ga(parameters): statistic = [] population = [] n_progenitors = parameters["pop_size"] / 2 num_gen = parameters["number_generations"] #generate the initial population if parameters["load_population"] == 1: population = load_population() else: population = [(generate_ind(len(parameters["protein"])),0) for i in range(parameters["pop_size"])] #evaluate the quality of the initial population population = [(ind[0],evaluate_ind(parameters["protein"],ind)) for ind in population] population.sort(key=itemgetter(1)) # minimization while num_gen: #print parameters["number_generations"] - num_gen #calculate the population statistics average_quality = sum([ind[1] for ind in population])/ float(len(population)) best_quality = population[0][1] statistic.append((best_quality,average_quality)) #select n_progenitors using the stockastic universal selection if random() < parameters["xover_prob"]: parents = stockastic_universal_selection(population,n_progenitors) offsprings = [crossover(parameters["protein"],parents) for i in range(n_progenitors)] else: offsprings = population #apply individual mutations new_population = [] for ind in offsprings: new_ind = ind if random() < parameters["mut_prob"]: if parameters["mutation_type"] == "pull_moves": #print "pull_moves" new_ind = pull_moves_mutation(parameters["protein"],ind,parameters["mut_prob"]) else: #print "monte_carlo" new_ind = monte_carlo_mutation(parameters["protein"],ind) new_population.append(new_ind) new_population.sort(key=itemgetter(1)) elite_size = int(round((parameters["survivors_perc"]) * parameters["pop_size"])) survivors_size = int(parameters["pop_size"] - elite_size) #population to the next generation population = population[:elite_size] + new_population[:survivors_size] #evaluates and sorts the new population population = [(ind[0],evaluate_ind(parameters["protein"],ind)) for ind in population] population.sort(key=itemgetter(1)) # minimization #print population[0][0], population[0][1] num_gen -= 1 #print population[0][0], population[0][1] return statistic
def __evolve_genome(self, new_genome, new_genomes, elites): if random.uniform(0, 1) <= self.settings['CROSSOVER_ODDS']: second_parent = self.__choose_random_genome_by_elite(elites) while second_parent == new_genome: second_parent = self.__choose_random_genome_by_elite(elites) new_genome = crossover(new_genome, second_parent) elif random.uniform(0, 1) <= self.settings['MUTATION_ODDS']: random_mutation(new_genome) new_genome.fitness = 0 new_genomes.append(new_genome)
def reproduce(evaluations: List[Evaluation], nIndividual: int): #remap fitness minFitness = evaluations[0].score maxFitness = evaluations[0].score for ev in evaluations: if ev.score < minFitness: minFitness = ev.score if ev.score > maxFitness: maxFitness = ev.score for ev in evaluations: ev.score = (ev.score - minFitness) / (maxFitness - minFitness) #speciate speciesPool = speciate(evaluations, 7) #cull cullRate = 0.8 for species in speciesPool: cullNumber = math.floor(len(species.members) * cullRate) species.members.sort(reverse=True) species.members = species.members[:len(species.members) - cullNumber] #loop backwards and get rid of species lower than 2 individual for i in range(len(speciesPool) - 1, -1, -1): if (len(speciesPool[i].members) < 2): speciesPool.pop(i) #make babies offsprings = [] totalFitness = 0.0 for species in speciesPool: totalFitness += species.sharedFitness for species in speciesPool: offspringCount = int(species.sharedFitness / totalFitness * nIndividual) for i in range(offspringCount): parents = random.sample(species.members, 2) if parents[0].score > parents[1].score: offsprings.append( crossover.crossover(parents[0].individual, parents[1].individual)) else: offsprings.append( crossover.crossover(parents[1].individual, parents[0].individual)) return offsprings
def reproduce(mating_pool, population_size, mutation_rate): new_population = [] while len(new_population) < population_size: parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) new_child = co.crossover(parent_A, parent_B) if new_child != None: new_child = mu.mutate(new_child, mutation_rate) if new_child != None: new_population.append(new_child) return new_population
def GA(): population = generatePopulation.generate(20) fitness_of_Population = calculateFitness.fitness(population) for i in range(10000): selcted_population = selection.selection(population, fitness_of_Population) crossover_population = crossover.crossover(selcted_population) population = mutation.mutation(crossover_population) fitness = calculateFitness.fitness(population) print(max(fitness)) if max(fitness) == 24: break
def reproduce(mating_pool, mutation_rate): """ Args: mating_pool: list of RDKit Mol mutation_rate: rate of mutation Returns: """ parent_a = random.choice(mating_pool) parent_b = random.choice(mating_pool) new_child = co.crossover(parent_a, parent_b) if new_child is not None: new_child = mu.mutate(new_child, mutation_rate) return new_child
def reproduce(mating_pool, population_size, mutation_rate): new_population = [] while len(new_population) < population_size: parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) new_child = co.crossover(parent_A, parent_B) if new_child != None: mutated_child = mu.mutate(new_child, mutation_rate) if mutated_child != None: #print(','.join([Chem.MolToSmiles(mutated_child),Chem.MolToSmiles(new_child),Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)])) new_population.append(mutated_child) return new_population
def run(): # 初始化种群 population_init(encode, Num, Bit) for i in range(epoch): # 解码 decode = decode_function(encode, max, min, Bit) # 计算适应度(用直接以待求解的目标方程函数) y = val_function(decode) # 选择适应度提高的染色体进行复制 selection(encode, y) # 交叉基因 crossover(encode, CV, Bit) # 基因变异 mutation(encode, change, Bit) #解码 decode = decode_function(encode, max, min, Bit) # 新种群 y = val_function(decode) a = 100 - np.array(y).max() print(a) return a
def getChild(self): PROBABILITY_crossover = 0.75 if random.random() < PROBABILITY_crossover: parent1 = self.subpopulation[random.randrange( 0, len(self.subpopulation))] parent2 = self.subpopulation[random.randrange( 0, len(self.subpopulation))] child = crossover.crossover(parent1, parent2) return child else: child = deepcopy(self.subpopulation[random.randrange( 0, len(self.subpopulation))]) return child
def reproduce(mating_pool, population_size, mutation_rate): new_population = [] for n in range(population_size): parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) #print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B) new_child = co.crossover(parent_A, parent_B) #print new_child if new_child != None: new_child = mu.mutate(new_child, mutation_rate) #print "after mutation",new_child if new_child != None: new_population.append(new_child) return new_population
def get_best_from_population(population): result = np.empty(ITERATIONS) for i in range(ITERATIONS): new_population = Population() while new_population.population_size < POPULATION_SIZE: parent1 = tournament(population, TOURNAMENT_SIZE) parent2 = tournament(population, TOURNAMENT_SIZE) child = crossover(parent1, parent2, CROSSOVER_RATE) mutate(child, MUTATION_RATE) new_population.add_individual(child) print('.', end='') population = new_population result[i] = population.get_best_individual().evaluate() print('-', end='') return result
def headlessChickenMut(indiv, SCORES, F, T, scorefunc, scoreparams, maxheight): from population import Node, generateFull, generateGrow, functify height = getHeight(indiv) chicken, rooster = generateFull(F, T, Node(), height), generateGrow(F, T, Node(), height, maxheight) c1, c2 = crossover(indiv, chicken, maxheight) c3, c4 = crossover(indiv, rooster, maxheight) c5, c6 = crossover(chicken, rooster, maxheight) for c in [c1, c2, c3, c4, c5, c6]: if functify(c) not in SCORES: SCORES[functify(c)] = scorefunc(c, *scoreparams) return sorted([c1, c2, c3, c4, c5, c6], key=lambda f: SCORES[functify(c)], reverse=True) #if __name__ == "__main__": # print 'starting' # # from cPickle import load # n = load(open('testbed')) # # print GCP(n,7) # # print 'done'
def driver(G, W, k, MAX_GEN): n = len(G) P = [] for i in range(2*n): temp = range(n) random.shuffle(temp) P.append(tuple(temp)) for i in range(MAX_GEN): fitness = compute_fitness(G, W, k, P) fitness.sort(key=lambda tup: tup[1]) P = [fitness[j][0] for j in range(n)] P = crossover(P, k, n) fitness = compute_fitness(G, W, k, P) fitness.sort(key=lambda tup: tup[1]) p = fitness[0][0] return create_partitions(G, W, k, p)
def test_croisement(self, chrom1, chrom2): import crossover chrom3 = crossover.crossover(chrom1, chrom2) test_is_chromosome(self, chrom3, len(chrom1)) from1 = 0 from2 = 0 for x, a, b in zip(chrom3, chrom1, chrom2): self.assertTrue(x == a or x == b, "Gene generation is forbidden") if x == a: from1 += 1 if x == b: from2 += 1 self.assertTrue(from1 + from2 >= len(chrom3), "Gene generation is forbidden") self.assertNotEqual(chrom1, chrom3, "The chromosome is identical to one of its parents") self.assertNotEqual(chrom2, chrom3, "The chromosome is identical to one of its parents")
def run_GA(P, fitnessOp, mutationOp,VEL_POP, MAX_ITER, ERR_THRESHOLD): fitnessOp.evaluate(P) gen = 0 print "%5d. gen,\t error: %s" %(gen, fitnessOp.minError) while gen < MAX_ITER and fitnessOp.minError > ERR_THRESHOLD: gen += 1 new_P = Population(P.n,0) new_P.addIndividual(fitnessOp.bestIndividual) while new_P.populationSize <VEL_POP: parent1, parent2 = chooseParents(P, fitnessOp) child = crossover(parent1, parent2) mutationOp.mutate(child) new_P.addIndividual(child) P = new_P fitnessOp.evaluate(P) print "%5d. gen,\t error: %s" %(gen, fitnessOp.minError) return fitnessOp.bestIndividual
def form_children(population, c_s = None, c_f = None, s = None): '''Select a pair of parents and form children Args: population: The population selection pool. Returns: The resulting children ''' if c_s == None: c_s = parameters.cs if c_f == None: c_f = parameters.cf if s == None: s = parameters.s # import pdb; pdb.set_trace(); # parent_a = random.choice(population) # crowding_selection_group = random.sample(population, c_s) parent_a = population.sample(1).iloc[0] crowding_selection_group = population.sample(c_s) # import pdb; pdb.set_trace() # pool_values['decoded'].apply(lambda x: euclidean(x, peak)).idxmin() parent_b = crowding_selection_group.ix[ crowding_selection_group['decoded'].apply(lambda x: similarity(parent_a.decoded, x)).idxmin() ] # parent_b.orient('index') # parent_b = max(crowding_selection_group, key= lambda x: similarity(parent_a, x)) # import pdb; pdb.set_trace() child_a, child_b = crossover(parent_a, parent_b) child_a = mutation(child_a) child_b = mutation(child_b) return child_a, child_b
def run(self, generations): logging.debug('Running for %s generations', generations) # Compute initial payoffs (fitness evaluation) gen = 0 logging.debug('GEN %s', gen) (payoffs, mean_attendance) = population.simulate(gen, self._population, self._weeks) logging.info('Attendance for gen %s:\n%.4f\n', gen, (mean_attendance / self._lambda)) # Sort the initial population by payoffs (self._population, sorted_payoffs) = population.sorted_by_payoffs(self._population, payoffs) logging.info('Payoffs for gen %s:\n%s', gen, sorted_payoffs) for gen in range(1, generations): logging.debug('GEN %s', gen) new_pop = self._population.copy() # Select parents parents = selection.truncation(self._num_parents, new_pop) # Generate children by crossover children = crossover.crossover(parents) # Replace worst solutions in the population with children new_pop[-children.size:] = children # Mutation considering all individuals except the best new_pop[1:] = mutation.mutation(new_pop[1:], self._mutation_chance, self._mutation_rate) # Compute payoffs of new population (payoffs, mean_attendance) = population.simulate(gen, new_pop, self._weeks) logging.info('Attendance for gen %s:\n%.4f\n', gen, (mean_attendance / self._lambda)) # Sort the new population by payoffs (sorted_pop, sorted_payoffs) = population.sorted_by_payoffs(new_pop, payoffs) logging.info('Payoffs for gen %s:\n%s', gen, sorted_payoffs) self._population = sorted_pop assert self._population.size == self._lambda return mean_attendance / self._lambda
def test_crossover(self): parent1, parent2 = CHROMOSOME_1, CHROMOSOME_2 crossover_keys = [1, 2] leftover_keys = [3] copyp1 = copy.deepcopy(parent1) copyp2 = copy.deepcopy(parent2) parent1, parent2 = crosser.crossover(parent1, parent2, crossover_keys) first_part_p1 = True second_part_p1 = True first_part_p2 = True second_part_p2 = True # Parent1 check # before crossover point same as parent1 for i in crossover_keys: if parent1[i] != copyp2[i]: first_part_p1 = False # after crossover point same as parent2 for i in leftover_keys: if parent1[i] != copyp1[i]: second_part_p1 = False # Parent1 check # before crossover point same as parent1 for i in crossover_keys: if parent2[i] != copyp1[i]: first_part_p2 = False # after crossover point same as parent2 for i in leftover_keys: if parent2[i] != copyp2[i]: second_part_p2 = False self.assertTrue(first_part_p1) self.assertTrue(second_part_p1) self.assertTrue(first_part_p2) self.assertTrue(second_part_p2)
def non_greedy_selection(population, crossover_fnc, cmp_fnc): indices = four_indices(len(population)) parents = [population[indices[i]] for i in range(4)] parents.sort(lambda x,y : mtr.comparator(x,y,cmp_fnc)) winner1, winner2 = parents[0], parents[1] loser1, loser2 = parents[2], parents[3] # Fitness is measured before crossover is complete and automatically # cached in a tuple. child1 and child2 should be tuples now. child1, child2 = cvr.crossover(winner1, winner2, crossover_fnc) # Mutate (if the check passes) child1 = mut.mutation(child1) child2 = mut.mutation(child2) # Replace the losers from selection population[population.index(loser1)] = child1 population[population.index(loser2)] = child2 return population
def greedy_selection(population, crossover_fnc, cmp_fnc): indices = four_indices(len(population)) parents = [population[indices[i]] for i in range(4)] parents.sort(lambda x,y : mtr.comparator(x,y,cmp_fnc)) winner1, winner2 = parents[0], parents[1] # Fitness is measured before crossover is complete and automatically # cached in a tuple. child1 and child2 should be tuples now. child1, child2 = cvr.crossover(winner1, winner2, crossover_fnc) # Mutate (if the check passes) child1 = mut.mutation(child1) child2 = mut.mutation(child2) # Add the children, resort, remove the worst 2 population.append(child1) population.append(child2) population.sort(lambda x,y : mtr.comparator(x,y,cmp_fnc)) population = population[:-2] return population
def genetic_algorithm(): gs = [] k = 30 for i in range(k): gs.append(random_generation()) for _ in range(1000): gs1 = selection(gs, k) for i in range(0, len(gs1), 2): gs1[i], gs1[i + 1] = crossover(gs1[i], gs1[i + 1]) for i in range(len(gs1)): gs1[i] = mutation(gs1[i]) gs = gs1[:] gs.sort(key=lambda x: -fitness_function(x)) m = fitness_function(gs[0]) s = gs[0] if m == 243: print( "5 Best solution along with their fitnesses of the final population" ) print("Sudoku 1: Solution Found!!") printSudoku(s) print("Fitness Value: {}".format(fitness_function(gs[0]))) for j in range(1, 5): print("Sudoku {}:".format(j + 1)) printSudoku(gs[i]) print("Fitness Value: {}".format(fitness_function(gs[i]))) break else: print( "5 Best solution along with their fitnesses of the final population" ) for i in range(5): print("Sudoku {}:".format(i + 1)) printSudoku(gs[i]) print("Fitness Value: {}".format(fitness_function(gs[i]))) print('')
def solve(self): generation_limit = int(config.get('run_config', 'generation_limit')) self.generate_initial_population() new_population = [] for i in range(generation_limit): self.population = self.evaluate(self.population) self.non_dominated_set.adds(self.population) while len(new_population) < self.population_size: parents = self.selection() children = mutation(crossover(parents)) for child in children: while (child in new_population) or children[0] == children[1]: child.mutate() new_population += children self.population = new_population return self.non_dominated_set
def reproduce(mating_pool, population_size, mutation_rate): new_population = [] count = 0 while len(new_population) < population_size: parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) #print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B) new_child = co.crossover(parent_A, parent_B) #print new_child if new_child != None: new_child = mu.mutate(new_child, mutation_rate) #print "after mutation",new_child if new_child != None: mol = co.mol_OK(new_child) if mol != True: count += 1 else: new_population.append(new_child) else: count += 1 else: count += 1 return new_population, count
def genetic_algorithm(task, crossover_rate=CROSSOVER_RATE, mutation_rate=MUTATION_RATE, tournament_size=TOURNAMENT_SIZE, population_size=POPULATION_SIZE): best_individuals_values = np.empty(MAX_ITERATIONS) start_time = time.time() population = init_population(task, population_size) outer_iterator = 0 best_individual = 0 best_individual_value = 0 global_best_individual = 0 global_best_individual_value = 0 while outer_iterator < MAX_ITERATIONS: inner_iterator = 0 new_population = Population() while inner_iterator < population_size: parent1 = tournament(population, tournament_size) parent2 = tournament(population, tournament_size) child = crossover(parent1, parent2, crossover_rate) mutate(child, mutation_rate) new_population.add_individual(child) inner_iterator += 1 best_individual = population.best_individual() best_individual_value = best_individual.evaluate() if best_individual_value >= global_best_individual_value: global_best_individual = best_individual global_best_individual_value = best_individual_value new_population.set_first_individual(global_best_individual) population = new_population best_individuals_values[outer_iterator] = global_best_individual_value outer_iterator += 1 print("--- Genetic algorithm\'s execution time = %s seconds ---" % (time.time() - start_time)) print('Genetic algorithm\'s final result =', global_best_individual_value)
def nextGeneration(currentPopulation, cuisineScore, maxQtyToBeOrdered, noOfElite, mutationRate, graphPoints, answer): """ This function applies genetic operators over current generation to produce new generation currentPopulation -> current pool of chromosomes of current generation cuisineScore -> Object consisting of cuisine score as rated by the users noOfElite -> no of Elite chromosomes that are to be persisted in next generation mutationRate -> rate at which mutation is to take place returns new generation of chromosomes """ populationRanked = rankDishes(currentPopulation, cuisineScore, maxQtyToBeOrdered) graphPoints.append(populationRanked[0][1]) if(answer.fitness<populationRanked[0][1]): answer.ans = deepcopy(currentPopulation[populationRanked[0][0]]) answer.fitness = populationRanked[0][1] selectedPopulationPool = selection(populationRanked, noOfElite) populationAfterCrossover = crossover( selectedPopulationPool, currentPopulation, noOfElite) nextGen = mutatePopulation(populationAfterCrossover, noOfElite, mutationRate) return nextGen
j = i + 1 print "Run#: ", j print bestVal newGeneration=[] for j in range(populationLimit): fitnessVal = fitnessFunction.fitnessFunction(population[j],city) if fitnessVal < bestVal: bestVal = fitnessVal bestAns = population[j] for k in range(populationLimit): for l in range((k+1), populationLimit): # child = population[k] child = crossover.crossover(population[k],population[l],city) newGeneration.append(child) for member in newGeneration: member = mutation.mutate(member) for m in range(populationLimit): newGeneration.append(population[m]) population = top.top(populationLimit,newGeneration,city) print bestAns
next_ind_order = individual_order # エリート戦略 elite = fitness.index(max(fitness)) # 世代ごとの一番高い適応度とエリート番地 print(str(i + 1) + "世代目:" + str(maxinds_fit[i]) + "\tエリート番地:" + str(elite)) f.write(str(i + 1) + "," + str(max(fitness)) + "\n") next_ind_path[0] = individual_path[elite] next_ind_order[0] = individual_order[elite] for j in range(1 , 100): sel_num = rl.selection(fitness) newinds = [] newinds = co.crossover(individual_order[sel_num[0]] , individual_order[sel_num[1]]) next_ind_order[j] = newinds next_ind_path[j] = cv.convertOTP(next_ind_order[j]) individual_order = next_ind_order individual_path = next_ind_path print(np.array(individual_path).reshape(inds , len_dat)) print() f.close() #kame.path(individual_path , dat , fitness , len_dat)
next_path = np.array([0 for col in range(inds) for row in range(len_dat)]).reshape(inds, len_dat) next_order = np.array([0 for col in range(inds) for row in range(len_dat)]).reshape(inds, len_dat) # 順番に選択 for j in range(inds): j_path = individual_path[j] j_order = individual_order[j] # ランダム3つ select_path, select_order = sri.select(inds, individual_path, individual_order, j, len_dat) # 差分変異親 mutant_order = np.array(cm.mutant(select_order, S_factor)) # 交叉して子(Trial)の生成 trial_order = co.crossover(j_order, mutant_order) trial_path = cv.convertOTP(trial_order) # 親と子で競争 fitness[j], next_path[j], next_order[j] = ev.evaluation(dat, j_path, j_order, trial_path, trial_order) individual_path = next_path individual_order = next_order print(str(i + 1) + "世代目:" + str(max(fitness)) + "\n" + str(individual_path[fitness.index(max(fitness))])) f.write(str(i + 1) + "," + str(max(fitness)) + "\n") f.close() print(individual_path[fitness.index(max(fitness))])
if __name__ == '__main__': import init_pop import fitness import parent_selection import crossover sizes = array([5, 8, 4, 11, 6, 12]) max_size = 20 pop_size = 10 cromo_size = len(sizes) fitness_func = fitness.subset_fitness select_parents = parent_selection.tournament_sel initial_pop = init_pop.init_pop(pop_size, cromo_size, init_pop.cromo_bin) population = fitness.eval_pop(initial_pop, fitness_func, sizes, max_size) mates = select_parents(population,pop_size,3) prob_cross = 0.8 cross_method = crossover.one_point_cross, crossover.uniform_cross offspring = crossover.crossover(mates, prob_cross, cross_method[0]) offspring = fitness.eval_pop(offspring,fitness_func, sizes, max_size) select_survivors = survivors_steady_state population = select_survivors(population, offspring, 0.02) #[print (i) for i in offspring] print ("pop:") #[print (i) for i in population]