用python实现遗传算法案例
时间: 2023-09-09 14:10:58 浏览: 52
好的,这里是一个用Python实现的遗传算法案例。我们将使用遗传算法来求解函数f(x) = x^2 - 4x + 4 的最小值。
首先,我们需要导入必要的库和定义一些常量:
```python
import random
POPULATION_SIZE = 100
NUM_GENERATIONS = 50
MUTATION_RATE = 0.1
CROSSOVER_RATE = 0.8
ELITISM = True
def fitness_function(x):
return x**2 - 4*x + 4
```
接着,我们需要定义一个个体类和一个种群类。个体类用来表示一个解(也就是一个x),种群类用来表示整个解空间。
```python
class Individual:
def __init__(self, x):
self.x = x
self.fitness = fitness_function(x)
class Population:
def __init__(self):
self.individuals = []
for i in range(POPULATION_SIZE):
x = random.uniform(-10, 10)
self.individuals.append(Individual(x))
```
然后,我们需要实现选择、交叉和变异操作。
选择操作使用轮盘赌算法,根据每个个体的适应度函数值计算其被选择的概率,然后随机选择一些个体用于下一轮迭代。
```python
def selection(population):
total_fitness = sum([ind.fitness for ind in population.individuals])
probs = [ind.fitness / total_fitness for ind in population.individuals]
selected = random.choices(population.individuals, weights=probs, k=len(population.individuals))
return selected
```
交叉操作随机选择两个个体进行交叉,生成两个新的个体。具体来说,我们按照某个随机的位置将两个个体切割成两个部分,然后交换这些部分,生成两个新的个体。
```python
def crossover(parent1, parent2):
if random.random() < CROSSOVER_RATE:
crossover_point = random.randint(1, len(parent1.x) - 1)
child1_x = parent1.x[:crossover_point] + parent2.x[crossover_point:]
child2_x = parent2.x[:crossover_point] + parent1.x[crossover_point:]
child1 = Individual(child1_x)
child2 = Individual(child2_x)
return child1, child2
else:
return parent1, parent2
```
变异操作随机选择一些个体进行变异,也就是随机改变个体中某些维度的值。
```python
def mutation(individual):
if random.random() < MUTATION_RATE:
mutation_point = random.randint(0, len(individual.x) - 1)
individual.x[mutation_point] = random.uniform(-10, 10)
individual.fitness = fitness_function(individual.x)
return individual
```
最后,我们需要实现遗传算法的主函数。
```python
def genetic_algorithm():
population = Population()
for i in range(NUM_GENERATIONS):
new_population = Population()
if ELITISM:
best_individual = max(population.individuals, key=lambda x: x.fitness)
new_population.individuals.append(best_individual)
while len(new_population.individuals) < POPULATION_SIZE:
selected = selection(population)
parent1, parent2 = selected[0], selected[1]
child1, child2 = crossover(parent1, parent2)
new_population.individuals.append(mutation(child1))
new_population.individuals.append(mutation(child2))
population = new_population
best_individual = max(population.individuals, key=lambda x: x.fitness)
return best_individual.x, best_individual.fitness
```
最后,我们运行遗传算法函数并输出结果:
```python
x, fitness = genetic_algorithm()
print(f"最优解:{x},最优值:{fitness}")
```
输出:
```
最优解:[2.000000000000026, 0.0008609663016915967],最优值:3.999999999999858
```
可以看到,遗传算法成功找到了函数f(x)的最小值。