编写一段求解函数最大值的遗传算法的python代码
时间: 2023-05-22 16:02:48 浏览: 143
以下是一段简单的遗传算法求解函数最大值的Python代码:
```python
import random
# 定义函数
def f(x):
return x * x + 3 * x - 4
# 定义参数
POPULATION_SIZE = 50
NUM_GENERATIONS = 1000
TOURNAMENT_SIZE = 3
MUTATION_RATE = 0.01
# 定义个体类
class Individual:
def __init__(self, x):
self.x = x
self.fitness = f(x)
def mutate(self):
if random.random() < MUTATION_RATE:
self.x += random.uniform(-1, 1)
self.fitness = f(self.x)
def __lt__(self, other):
return self.fitness > other.fitness
# 定义遗传算法类
class GeneticAlgorithm:
def __init__(self):
self.population = [Individual(random.uniform(-10, 10)) for _ in range(POPULATION_SIZE)]
def evolve(self):
for i in range(NUM_GENERATIONS):
self.selection()
self.crossover()
for individual in self.population:
individual.mutate()
return max(self.population)
def selection(self):
for i in range(POPULATION_SIZE):
tournament = random.sample(self.population, TOURNAMENT_SIZE)
winner = max(tournament)
self.population[i] = winner
def crossover(self):
for i in range(0, POPULATION_SIZE, 2):
parent1 = self.population[i]
parent2 = self.population[i+1]
child1_x = (parent1.x + parent2.x) / 2
child2_x = (parent1.x + parent2.x) / 2
child1 = Individual(child1_x)
child2 = Individual(child2_x)
self.population[i] = child1
self.population[i+1] = child2
# 运行遗传算法
ga = GeneticAlgorithm()
print(ga.evolve().x)
```
这段代码使用了遗传算法来求解函数 f(x) = x^2 + 3x - 4 的最大值。通过定义个体类和遗传算法类,我们可以轻松地实现遗传算法的各个过程,包括选择、交叉和变异。在主函数中,我们创建了一个遗传算法对象 ga,并调用它的 evolve 方法来运行遗传算法。最终,我们输出得到的最大值的 x 坐标。
阅读全文