EA算法Python源程序
时间: 2024-09-07 13:03:36 浏览: 34
EA(Evolutionary Algorithm,进化算法)是一种模拟自然选择过程的计算优化技术,常用于解决复杂的搜索、优化问题,如遗传算法(GA)和粒子群优化(PSO)等。在Python中,有许多库支持这些算法,比如`deap`(Distributed Evolutionary Algorithms in Python)、`pyevolve`等。
下面是一个简单的遗传算法(GA)的Python基础代码示例,使用了`deap`库:
```python
import random
from deap import base, creator, tools
# 定义基因型和表现型
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
def evalOneMax(individual):
return sum(individual),
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=40)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evalOneMax)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
pop = toolbox.population(n=300)
for gen in range(50): # 进化50代
offspring = toolbox.select(pop, len(pop))
offspring = [toolbox.clone(ind) for ind in offspring]
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < 0.7:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if random.random() < 0.2:
toolbox.mutate(mutant)
del mutant.fitness.values
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
pop[:] = offspring
best_ind = tools.selBest(pop, k=1)[0]
print(f"Best individual: {best_ind}, Fitness: {best_ind.fitness.values[0]}")
阅读全文