遗传算法 精英 python
时间: 2023-12-11 14:33:39 浏览: 41
遗传算法是一种基于自然选择和遗传学原理的优化算法,可以用于解决很多优化问题。其中精英遗传算法是一种改进的遗传算法,它保留了每一代中最秀的个体,以确保算法不会陷入局部最优解。下面是一个使用Python实现精英遗传算法的例子:
```python
import random
# 适应度函数,用于评估每个个体的适应度
def fitness(individual):
return sum(individual)
# 生成初始种群
def generate_population(size, chromosome_length):
population = []
for i in range(size):
individual = [random.randint(0, 1) for j in range(chromosome_length)]
population.append(individual)
return population
# 选择操作,使用锦标赛选择法
def selection(population, k):
tournament = random.sample(population, k)
return max(tournament, key=fitness)
# 交叉操作,使用单点交叉法
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 变异操作,使用随机翻转法
def mutation(individual, probability):
for i in range(len(individual)):
if random.random() < probability:
individual[i] = 1 - individual[i]
return individual
# 精英遗传算法主函数
def elitist_genetic_algorithm(population_size, chromosome_length, generations, selection_size, crossover_probability, mutation_probability):
population = generate_population(population_size, chromosome_length)
for i in range(generations):
# 选择精英个体
elites = sorted(population, key=fitness, reverse=True)[:selection_size]
# 选择新的种群
new_population = elites[:]
while len(new_population) < population_size:
# 选择父代
parent1 = selection(population, selection_size)
parent2 = selection(population, selection_size)
# 交叉操作
if random.random() < crossover_probability:
child1, child2 = crossover(parent1, parent2)
else:
child1, child2 = parent1, parent2
# 变异操作
child1 = mutation(child1, mutation_probability)
child2 = mutation(child2, mutation_probability)
# 添加子代到新的种群中
new_population.append(child1)
if len(new_population) < population_size:
new_population.append(child2)
population = new_population
# 返回最优解
return max(population, key=fitness)
# 示例
population_size = 100
chromosome_length = 10
generations = 100
selection_size = 10
crossover_probability = 0.8
mutation_probability = 0.1
result = elitist_genetic_algorithm(population_size, chromosome_length, generations, selection_size, crossover_probability, mutation_probability)
print(result)
```