遗传算法python实例
时间: 2023-10-26 22:08:10 浏览: 55
以下是一个遗传算法(Genetic Algorithm)的 Python 实例:
```python
import random
# 目标函数:计算染色体适应度
def fitness(chromosome):
return sum(chromosome)
# 交叉操作:单点交叉
def crossover(parent1, parent2):
point = random.randint(1, len(parent1)-1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
# 变异操作:单点变异
def mutation(chromosome):
point = random.randint(0, len(chromosome)-1)
new_gene = random.randint(0, 9)
chromosome[point] = new_gene
return chromosome
# 初始化种群
def init_population(pop_size, chromosome_size):
population = []
for i in range(pop_size):
chromosome = [random.randint(0, 9) for j in range(chromosome_size)]
population.append(chromosome)
return population
# 遗传算法主函数
def genetic_algorithm(pop_size, chromosome_size, generation):
population = init_population(pop_size, chromosome_size)
for i in range(generation):
# 计算适应度
fitness_list = [fitness(chromosome) for chromosome in population]
# 选择操作:轮盘赌选择
probability = [fitness / sum(fitness_list) for fitness in fitness_list]
roulette_wheel = [sum(probability[:i+1]) for i in range(pop_size)]
new_population = []
for j in range(pop_size):
r = random.uniform(0, 1)
for k in range(pop_size):
if r <= roulette_wheel[k]:
new_population.append(population[k])
break
# 交叉操作
for j in range(0, pop_size, 2):
parent1, parent2 = new_population[j], new_population[j+1]
child1, child2 = crossover(parent1, parent2)
new_population[j], new_population[j+1] = child1, child2
# 变异操作
for j in range(pop_size):
new_population[j] = mutation(new_population[j])
population = new_population
# 返回最佳个体
fitness_list = [fitness(chromosome) for chromosome in population]
best_chromosome = population[fitness_list.index(max(fitness_list))]
return best_chromosome
# 测试
best_chromosome = genetic_algorithm(pop_size=100, chromosome_size=10, generation=50)
print(best_chromosome)
```
这个实例是一个求解最大值问题的遗传算法,目标函数为染色体内各基因的和。其中包括了初始化种群、计算适应度、选择操作、交叉操作、变异操作等基本步骤。
阅读全文