用遗传算法求xcosx+2的最大值的Python代码是什么
时间: 2024-11-03 20:23:56 浏览: 12
遗传算法是一种模拟自然选择过程的优化搜索算法,常用于解决复杂的全局优化问题。这里是一个简单的Python代码示例,使用DEAP库(Distributed Evolutionary Algorithms in Python)实现遗传算法来寻找`xcos(x)+2`函数的最大值。请注意,这只是一个基础的框架,并非最优解,因为实际应用可能需要更精细的调整和更多的迭代。
```python
import numpy as np
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 = individual[0]
return -np.cos(x) + 2,
toolbox = base.Toolbox()
# 初始化随机个体
toolbox.register("attr_float", lambda: np.random.uniform(-5, 5))
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 选择、交叉和变异操作
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
# 主循环
ngen = 1000 # 迭代次数
pop = toolbox.population(n=50)
hof = tools.HallOfFame(1) # 保存最佳解
for gen in range(ngen):
# 评估当前种群
fitnesses = list(map(eval_fitness, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
# 选择、交叉和变异
offspring = [toolbox.clone(ind) for ind in toolbox.select(pop, len(pop))]
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if np.random.rand() < 0.5:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if np.random.rand() < 0.2:
toolbox.mutate(mutant)
del mutant.fitness.values
# 把新个体加入到种群中
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(eval_fitness, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
pop[:] = offspring
# 保存最佳解
hof.update(pop)
best_solution = hof[0]
max_value = best_solution.fitness.values[0]
print(f"Best solution found: {best_solution[0]}, Max value of f(x): {max_value}")
阅读全文