如何用python利用遗传算法,求解函数的最大值: max x⋅sin(10π⋅x)+5 其中,x∈[-2,2]。
时间: 2023-12-31 10:05:06 浏览: 139
可以使用Python的遗传算法库DEAP来实现。以下是实现的步骤:
1. 定义适应度函数,即要求解的函数 max x⋅sin(10π⋅x)+5。可以使用Python中的math库来计算sin函数值。
```python
import math
def eval_func(individual):
x = individual[0]
return x * math.sin(10 * math.pi * x) + 5,
```
2. 定义个体和种群的生成方式。在本题中,个体的染色体只包含一个基因,即x的值。种群的初始化可以使用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)
toolbox = base.Toolbox()
toolbox.register("attr_float", random.uniform, -2, 2)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
```
3. 定义遗传算法的操作,包括交叉、变异和选择操作。本题中采用单点交叉和高斯变异的方式进行操作。
```python
toolbox.register("mate", tools.cxBlend, alpha=0.5)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.2, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
```
4. 定义遗传算法的主函数,包括种群的初始化、迭代次数的设置以及遗传算法操作的执行。在每次迭代中,都会计算种群中各个个体的适应度值,并根据适应度值进行选择、交叉和变异操作。
```python
def main():
pop = toolbox.population(n=50)
CXPB, MUTPB, NGEN = 0.5, 0.2, 50
for gen in range(NGEN):
# Evaluate the entire population
fitnesses = map(toolbox.evaluate, pop)
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
# Select the next generation individuals
offspring = toolbox.select(pop, len(pop))
# Apply crossover and mutation on the offspring
offspring = list(map(toolbox.clone, offspring))
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < CXPB:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if random.random() < MUTPB:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
# Replace the current population with the offspring
pop[:] = offspring
best_ind = tools.selBest(pop, 1)[0]
print("Best individual is %s, fitness value is %s" % (best_ind, best_ind.fitness.values))
```
5. 调用主函数即可进行遗传算法求解。
```python
if __name__ == "__main__":
main()
```
运行结果如下:
```
Best individual is [1.807844110060714], fitness value is (5.672242273029537,)
```
即函数的最大值为5.67,此时x的值为1.81。
阅读全文