帮我写一段实现遗传算法的python代码
时间: 2024-09-21 15:10:23 浏览: 45
遗传算法是一种模拟自然选择过程的优化搜索算法,它通过复制、变异和交叉操作来寻找最优解。下面是一个简单的Python实现遗传算法的框架示例:
```python
import random
# 定义问题域的个体表示(假设我们解决的是0-9间的整数加法)
class Individual:
def __init__(self):
self.genes = [random.randint(0, 9) for _ in range(10)] # 初始基因由随机数构成
def fitness(self): # 健康度函数,这里简单地设置为基因之和
return sum(self.genes)
# 初始化种群
def create_population(size):
return [Individual() for _ in range(size)]
# 配对选择
def selection(population):
fit_sum = sum(indiv.fitness() for indiv in population)
probabilities = [indiv.fitness() / fit_sum for indiv in population]
return random.choices(population, probabilities, k=len(population))
# 交叉操作
def crossover(parent1, parent2):
offspring = parent1.genes.copy()
crossover_point = random.randint(1, len(offspring)-1)
offspring[crossover_point:] = parent2.genes[crossover_point:]
return Individual(offspring)
# 变异操作
def mutation(individual, mutation_rate=0.1):
for i in range(len(individual.genes)):
if random.random() < mutation_rate:
individual.genes[i] = random.randint(0, 9)
return individual
# 主遗传循环
def genetic_algorithm(population_size, generations, crossover_rate, mutation_rate):
population = create_population(population_size)
for _ in range(generations):
parents = selection(population)
offspring = [crossover(parents[i], parents[(i+1)%population_size]) for i in range(0, len(parents), 2)]
offspring += [mutation(indiv) for indiv in offspring]
# 更新种群
population = [max(population, key=Individual.fitness) if random.random() > 0.5 else indiv for indiv in offspring]
best_individual = max(population, key=Individual.fitness)
return best_individual, best_individual.fitness()
# 调用遗传算法
best_solution, best_fitness = genetic_algorithm(100, 100, 0.8, 0.1)
print(f"最优解:{best_solution.genes}, 最优值:{best_fitness}")
阅读全文