给出遗传算法求解函数f(x,y)=x^2+y^2的最大值的代码
时间: 2024-10-25 16:14:56 浏览: 12
遗传算法是一种模拟自然选择和遗传机制的优化搜索算法,它通常用于解决复杂问题的全局最优解。下面是一个简单的Python代码示例,使用DEAP库(Distributed Evolutionary Algorithms in Python)实现遗传算法来寻找函数f(x, y) = x^2 + y^2的最大值。在这个例子中,我们将假设个体是由两个实数组成的列表,并且通过变异和交叉操作生成新一代。
```python
from deap import base, creator, tools
# 定义函数和种群
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
def eval_fitness(individual):
x, y = individual
return -abs(x**2 + y**2), # 因为我们要找最大值,所以取负值
toolbox = base.Toolbox()
# 初始化参数
toolbox.register("attr_float", random.uniform, -10.0, 10.0)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", eval_fitness)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
def main():
pop = toolbox.population(n=50)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", numpy.mean)
stats.register("std", numpy.std)
stats.register("min", numpy.min)
stats.register("max", numpy.max)
for gen in range(100): # 运行一定代数
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.5:
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
invalids = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalids)
for ind, fit in zip(invalids, fitnesses):
ind.fitness.values = fit
pop[:] = offspring
hof.update(pop)
print(f"Generation {gen+1}: Best individual {hof[0]}, Fitness: {-hof[0].fitness.values[0]:.4f}")
if __name__ == "__main__":
main()
```
阅读全文