精英保存策略的遗传算法代码
时间: 2023-07-02 20:04:35 浏览: 81
一种多精英保存策略的遗传算法
以下是一个简单的精英保存策略的遗传算法代码:
```python
import random
# 定义适应度函数
def fitness_function(individual):
return sum(individual)
# 定义遗传算法的主函数
def genetic_algorithm(population_size, gene_size, generations, elitism_rate, mutation_rate):
# 初始化种群
population = [[random.randint(0, 1) for j in range(gene_size)] for i in range(population_size)]
# 迭代进化
for i in range(generations):
# 计算适应度
fitness = [fitness_function(individual) for individual in population]
# 选择精英个体
elite_size = int(elitism_rate * population_size)
elite_index = sorted(range(len(fitness)), key=lambda k: fitness[k], reverse=True)[:elite_size]
elite_individuals = [population[i] for i in elite_index]
# 选择非精英个体
non_elite_individuals = [population[i] for i in range(population_size) if i not in elite_index]
# 交叉操作
offspring = []
while len(offspring) < population_size - elite_size:
parent1 = random.choice(non_elite_individuals)
parent2 = random.choice(non_elite_individuals)
offspring1 = parent1[:gene_size // 2] + parent2[gene_size // 2:]
offspring2 = parent2[:gene_size // 2] + parent1[gene_size // 2:]
offspring.append(offspring1)
offspring.append(offspring2)
# 变异操作
for individual in offspring:
for j in range(gene_size):
if random.random() < mutation_rate:
individual[j] = 1 - individual[j]
# 更新种群
population = elite_individuals + offspring
# 返回最优个体
fitness = [fitness_function(individual) for individual in population]
best_index = fitness.index(max(fitness))
return population[best_index]
```
其中,`population_size` 表示种群大小,`gene_size` 表示基因个数,`generations` 表示迭代次数,`elitism_rate` 表示精英保留率,`mutation_rate` 表示变异率。在主函数中,首先初始化种群,然后迭代进化。在每次迭代中,先计算适应度,然后选择精英个体和非精英个体。接着进行交叉和变异操作,生成新的后代个体。最后更新种群并返回最优个体。
阅读全文