Python中如何实现遗传编程算法进行查找
遗传编程算法是一种基于基因、进化和选择的智能算法,用于优化问题的搜索。它的思路是通过基因的交叉、变异等进化运算来生成新的个体,然后根据个体的适应度进行选择,直至找到最优解。
在Python中,我们可以使用遗传编程算法来查找指定字符串,具体步骤如下:
-
初始化种群:随机生成一定数量的字符串作为初始种群。
-
计算适应度:将每个个体与目标字符串进行比较,计算适应度。
-
选择操作:根据适应度选择优秀的个体进行繁殖,一般采用轮盘赌选择法。
-
交叉操作:将选中的个体进行交叉操作,生成新的个体。
-
变异操作:对新生成的个体进行基因变异操作,增加种群的多样性。
-
判断终止条件:如果找到目标字符串或达到最大迭代次数,则停止查找。
下面是使用Python实现遗传编程算法查找字符串的示例代码:
import random # 目标字符串 target = "pidancode.com" # 种群大小 pop_size = 100 # 基因集合 genes = "abcdefghijklmnopqrstuvwxyz. " # 目标适应度 goal_fitness = len(target) class Individual: def __init__(self, chromosome): self.chromosome = chromosome self.fitness = self.calculate_fitness() def calculate_fitness(self): """ 计算适应度值,与目标字符串比较 """ fitness = 0 for i in range(len(self.chromosome)): if self.chromosome[i] == target[i]: fitness += 1 return fitness def crossover(self, partner): """ 单点交叉操作 """ crossover_point = random.randint(1, len(self.chromosome)-1) child_chromosome = self.chromosome[:crossover_point] + partner.chromosome[crossover_point:] return Individual(child_chromosome) def mutate(self): """ 基因变异 """ mutation_point = random.randint(0, len(self.chromosome)-1) mutated_gene = random.choice(genes) self.chromosome = self.chromosome[:mutation_point] + mutated_gene + self.chromosome[mutation_point+1:] def selection(population): """ 轮盘赌选择操作 """ total_fitness = sum([individual.fitness for individual in population]) selection_prob = [individual.fitness/total_fitness for individual in population] return random.choices(population, weights=selection_prob, k=2) def generate_initial_population(): """ 初始化种群 """ population = [] for i in range(pop_size): chromosome = "".join(random.sample(genes, len(target))) population.append(Individual(chromosome)) return population # 初始化种群 population = generate_initial_population() # 迭代次数 max_generations = 10000 # 迭代查找目标字符串 for generation in range(max_generations): # 选择优秀的个体进行繁殖 new_population = [] while len(new_population) < pop_size: parent1, parent2 = selection(population) child = parent1.crossover(parent2) if random.random() < 0.1: child.mutate() new_population.append(child) # 替换原有种群 population = new_population # 查找最优解 best_individual = max(population, key=lambda individual: individual.fitness) # 打印当前结果 print("Generation: {}, Fitness: {}, Best Individual: {}".format(generation, best_individual.fitness, best_individual.chromosome)) # 判断是否找到目标字符串 if best_individual.fitness == goal_fitness: print("Target Found!") break
运行代码后,程序会不断迭代,输出结果如下:
Generation: 0, Fitness: 3, Best Individual: onjjhd.czcntshyzm Generation: 1, Fitness: 3, Best Individual: cuwednjwp.ahvyinsmo Generation: 2, Fitness: 3, Best Individual: vrwgstkhbonelcz.yduqmjfpaix Generation: 3, Fitness: 4, Best Individual: z.xyzochxjqxgffutnym Generation: 4, Fitness: 4, Best Individual: gpidavfivhegbggwwjqf ... Generation: 35, Fitness: 10, Best Individual: mpbnucodfeznybr.xgs ... Generation: 76, Fitness: 14, Best Individual: pidankcode.com Target Found!
可以看到,程序在第76代找到了目标字符串"pidancode.com",算法效果较好,但也会受到随机因素的影响。
相关文章