遗传算法python代码
时间: 2023-11-08 13:58:56 浏览: 67
遗传算法代码(Python)
这里是一个简单的遗传算法 Python 代码示例:
```
import random
def fitness(candidate):
# 返回候选解的适应度值
# 这里只是一个简单的示例
return sum(candidate)
def generate_candidate(length):
# 生成一个随机的候选解
return [random.randint(0, 1) for _ in range(length)]
def mutate(candidate, mutation_rate):
# 对候选解进行突变
for i in range(len(candidate)):
if random.random() < mutation_rate:
candidate[i] = 1 - candidate[i]
return candidate
def crossover(parent1, parent2):
# 对两个父代候选解进行交叉
crossover_point = random.randint(1, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
def genetic_algorithm(population_size, mutation_rate, generations, selection_size):
# 生成初始种群
population = [generate_candidate(10) for _ in range(population_size)]
for i in range(generations):
# 计算每个候选解的适应度值
fitness_scores = [fitness(candidate) for candidate in population]
# 选择最适应的候选解
selected_candidates = [population[i] for i in sorted(range(len(fitness_scores)), key=lambda x: fitness_scores[x], reverse=True)[:selection_size]]
# 生成下一代候选解
children = []
while len(children) < population_size - selection_size:
# 随机选择两个父代候选解
parent1 = random.choice(selected_candidates)
parent2 = random.choice(selected_candidates)
# 交叉生成两个子代候选解
child1, child2 = crossover(parent1, parent2)
# 对子代候选解进行突变
child1 = mutate(child1, mutation_rate)
child2 = mutate(child2, mutation_rate)
# 将子代候选解加入下一代种群
children.append(child1)
if len(children) < population_size - selection_size:
children.append(child2)
# 将最适应的候选解加入下一代种群
population = selected_candidates + children
# 返回最终最适应的候选解
return max(population, key=fitness)
```
这是一个基本的遗传算法实现,可以根据需要进行修改和扩展。
阅读全文