遗传算法求函数f(x)=xsin(10π*x)+2.0,x∈[-1,2]的最大值python代码
时间: 2024-11-22 10:45:16 浏览: 11
遗传算法是一种模拟自然选择过程的优化搜索算法,常用于解决复杂的全局优化问题。下面是一个简单的Python代码示例,使用DEAP库(Distributed Evolutionary Algorithms in Python)实现遗传算法来寻找函数 `f(x) = x * sin(10 * π * x) + 2.0` 的最大值,给定范围是 `x ∈ [-1, 2]`:
```python
from deap import base, creator, tools
import numpy as np
# 定义问题
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
def eval_fitness(individual):
x = individual[0]
return -abs(x * np.sin(10 * np.pi * x) + 2.0),
toolbox = base.Toolbox()
# 初始化参数
toolbox.register("attr_float", np.random.uniform, low=-1.0, high=2.0)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
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=0.1, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
# 运行遗传算法
POP_SIZE = 100
NGEN = 1000
pop = toolbox.population(n=POP_SIZE)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)
for gen in range(NGEN):
offspring = tools.selTournamentDCD(pop, len(pop)) # 辛普森抽样选择
offspring = [toolbox.clone(ind) for ind in offspring]
# 变异和交叉操作
for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
if np.random.rand() < 0.7: # 随机选择交叉概率
toolbox.mate(ind1, ind2)
del ind1.fitness.values
del ind2.fitness.values
for ind in offspring:
if np.random.rand() < 0.2: # 随机变异
toolbox.mutate(ind)
del ind.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
pop, hof = tools.sortNondominated(pop, hof, k=1) # 排序并保留最佳解
best_solution = hof[0]
best_fitness = best_solution.fitness.values[0]
print(f"最优解:{best_solution}[{best_fitness}], 函数值:{best_fitness}")
阅读全文