python遗传算法程序
时间: 2024-09-13 17:00:30 浏览: 52
Python是一种非常适合实现遗传算法的语言,因为其语法简洁,库丰富。下面是一个基本的Python遗传算法程序框架,它会解决一个简单的函数优化问题:
```python
import random
import numpy as np
# 定义适应度函数 (这里假设我们要最小化一个简单的一维函数)
def fitness_function(x):
return x**2 # 示例:二次函数
# 遗传算法参数
pop_size = 50 # 种群规模
num_generations = 100 # 迭代次数
mutation_rate = 0.01 # 变异率
crossover_probability = 0.9 # 交叉概率
# 初始化种群
population = [np.random.uniform(-10, 10) for _ in range(pop_size)]
# 辅助函数:选择、交叉和变异
def selection(population, fitness):
return random.choices(population, weights=fitness, k=len(population))
def crossover(parents):
offspring = []
for i in range(len(parents)//2): # 半双倍交叉
if random.random() < crossover_probability:
point = random.randint(1, len(parents[0])-1)
child1 = parents[i][:point] + parents[i+1][point:]
child2 = parents[i+1][:point] + parents[i][point:]
else:
child1 = parents[i]
child2 = parents[i+1]
offspring.append(child1)
offspring.append(child2)
return offspring
def mutate(individual):
if random.random() < mutation_rate:
individual[random.randint(0, len(individual)-1)] += random.uniform(-0.5, 0.5)
return individual
# 主遗传算法循环
best_solution = None
best_fitness = float('inf')
for generation in range(num_generations):
# 计算适应度
population_fitness = [fitness_function(ind) for ind in population]
# 更新种群
new_population = selection(population, population_fitness)
new_population = crossover(new_population)
new_population = [mutate(ind) for ind in new_population]
# 保存当前最佳解
current_best = min(new_population, key=fitness_function)
if fitness_function(current_best) < best_fitness:
best_solution = current_best
best_fitness = fitness_function(current_best)
population = new_population
print("Best solution found:", best_solution, "with a fitness of", best_fitness)
```
阅读全文