用Python通过遗传算法求函数F(x)=xsin(10π*x)+2.0 x∈[-1,2]的最大值,并包含图像。
时间: 2023-10-08 20:11:39 浏览: 285
好的,我可以帮你解决这个问题。遗传算法是一种优化算法,可以用来求解复杂的函数问题。我们可以使用Python的遗传算法库DEAP来实现这个问题。
首先,需要安装DEAP库。可以使用以下命令进行安装:
```
pip install deap
```
接下来,我们需要定义问题的适应度函数。对于本问题,适应度函数为F(x)=xsin(10πx)+2.0,我们需要求的是这个函数的最大值。因此,适应度函数应该返回函数值的相反数(因为DEAP库的优化算法是寻找最小值)。
```python
import math
from deap import base, creator, tools
# 定义适应度函数
def evaluate(individual):
x = individual[0]
return -1 * (x * math.sin(10 * math.pi * x) + 2.0),
# 创建适应度函数适应度类
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
# 创建个体类
creator.create("Individual", list, fitness=creator.FitnessMax)
```
接下来,我们需要定义遗传算法的参数。这些参数包括种群大小、交叉率、变异率等。
```python
# 定义遗传算法参数
POPULATION_SIZE = 50
P_CROSSOVER = 0.9
P_MUTATION = 0.1
MAX_GENERATIONS = 50
HALL_OF_FAME_SIZE = 1
toolbox = base.Toolbox()
# 定义变量范围
toolbox.register("attr_float", random.uniform, -1, 2)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 定义交叉函数
toolbox.register("mate", tools.cxBlend, alpha=0.2)
# 定义变异函数
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("evaluate", evaluate)
```
现在我们可以开始遗传算法的主循环。在每一代中,我们使用选择、交叉和变异操作来生成新的种群,并使用适应度函数来评估每个个体的适应度。在每一代中,我们都会选择适应度最好的个体,并将其添加到名人堂中。
```python
import random
random.seed(42)
population = toolbox.population(n=POPULATION_SIZE)
hall_of_fame = tools.HallOfFame(HALL_OF_FAME_SIZE)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", tools.mean)
stats.register("min", tools.min)
logbook = tools.Logbook()
logbook.header = ["generation", "evaluations"] + stats.fields
for generation in range(MAX_GENERATIONS):
offspring = algorithms.varOr(population, toolbox, lambda_=POPULATION_SIZE, cxpb=P_CROSSOVER, mutpb=P_MUTATION)
fits = toolbox.map(toolbox.evaluate, offspring)
for fit, ind in zip(fits, offspring):
ind.fitness.values = fit
population = toolbox.select(offspring, k=len(population))
hall_of_fame.update(population)
record = stats.compile(population)
logbook.record(evaluations=len(population), generation=generation, **record)
print(logbook.stream)
best = hall_of_fame.items[0]
print("Best individual is", best, "with fitness", best.fitness.values[0])
```
最后,我们可以使用Matplotlib库绘制函数的图像和最优解的位置。
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 200)
y = x * np.sin(10 * np.pi * x) + 2.0
plt.plot(x, y)
plt.plot(best, best.fitness.values[0], 'go')
plt.show()
```
完整代码如下:
```python
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from deap import base, creator, tools, algorithms
# 定义适应度函数
def evaluate(individual):
x = individual[0]
return -1 * (x * math.sin(10 * math.pi * x) + 2.0),
# 创建适应度函数适应度类
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
# 创建个体类
creator.create("Individual", list, fitness=creator.FitnessMax)
# 定义遗传算法参数
POPULATION_SIZE = 50
P_CROSSOVER = 0.9
P_MUTATION = 0.1
MAX_GENERATIONS = 50
HALL_OF_FAME_SIZE = 1
toolbox = base.Toolbox()
# 定义变量范围
toolbox.register("attr_float", random.uniform, -1, 2)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 定义交叉函数
toolbox.register("mate", tools.cxBlend, alpha=0.2)
# 定义变异函数
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("evaluate", evaluate)
random.seed(42)
population = toolbox.population(n=POPULATION_SIZE)
hall_of_fame = tools.HallOfFame(HALL_OF_FAME_SIZE)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", tools.mean)
stats.register("min", tools.min)
logbook = tools.Logbook()
logbook.header = ["generation", "evaluations"] + stats.fields
for generation in range(MAX_GENERATIONS):
offspring = algorithms.varOr(population, toolbox, lambda_=POPULATION_SIZE, cxpb=P_CROSSOVER, mutpb=P_MUTATION)
fits = toolbox.map(toolbox.evaluate, offspring)
for fit, ind in zip(fits, offspring):
ind.fitness.values = fit
population = toolbox.select(offspring, k=len(population))
hall_of_fame.update(population)
record = stats.compile(population)
logbook.record(evaluations=len(population), generation=generation, **record)
print(logbook.stream)
best = hall_of_fame.items[0]
print("Best individual is", best, "with fitness", best.fitness.values[0])
# 绘制函数图像和最优解的位置
x = np.linspace(-1, 2, 200)
y = x * np.sin(10 * np.pi * x) + 2.0
plt.plot(x, y)
plt.plot(best, best.fitness.values[0], 'go')
plt.show()
```
阅读全文