python单亲遗传算法代码
时间: 2024-02-29 20:50:29 浏览: 194
单亲遗传算法(Single Parent Genetic Algorithm)是一种基于遗传算法的优化算法,用于解决优化问题。下面是一个简单的Python单亲遗传算法的代码示例:
```python
import random
# 适应度函数,根据个体的染色体计算适应度值
def fitness(chromosome):
# 这里假设适应度函数为染色体中所有基因的和
return sum(chromosome)
# 单亲遗传算法
def single_parent_genetic_algorithm(population_size, chromosome_length, generations):
# 初始化种群
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
# 迭代进化
for _ in range(generations):
# 计算每个个体的适应度值
fitness_values = [fitness(chromosome) for chromosome in population]
# 选择最优个体作为父代
best_individual = population[fitness_values.index(max(fitness_values))]
# 生成新的子代种群
new_population = [best_individual] * population_size
# 变异操作,对子代种群进行随机变异
for i in range(1, population_size):
for j in range(chromosome_length):
if random.random() < 0.01: # 变异概率为0.01
new_population[i][j] = 1 - new_population[i][j]
# 更新种群
population = new_population
# 返回最优个体
best_individual = population[fitness_values.index(max(fitness_values))]
return best_individual
# 示例运行
population_size = 100
chromosome_length = 10
generations = 100
best_individual = single_parent_genetic_algorithm(population_size, chromosome_length, generations)
print("Best individual:", best_individual)
```
这段代码实现了一个简单的单亲遗传算法,其中包括适应度函数的定义、种群初始化、迭代进化、选择、变异等操作。在示例中,染色体是由0和1组成的二进制串,适应度函数为染色体中所有基因的和。算法通过迭代进化,不断选择最优个体作为父代,生成新的子代种群,并进行随机变异。最终返回最优个体。
阅读全文