用Python写遗传平衡和遗传漂变的计算机模拟:每个群体的大小分别选取10,20,50, 100,1000,10000;遗传的代数分别选取1、2、3、5、10,50,100,500,1000。
时间: 2024-06-13 09:08:33 浏览: 74
以下是Python实现遗传平衡和遗传漂变的计算机模拟的代码,其中包括了不同群体大小和遗传代数的情况:
```python
import random
# 定义遗传算法的参数
pop_sizes = [10, 20, 50, 100, 1000, 10000] # 种群规模
gens = [1, 2, 3, 5, 10, 50, 100, 500, 1000] # 进化代数
pc = 0.8 # 交叉率
pr = 0.25 # 反转率
pm = 0.4 # 变异率
# 定义适应度函数
def fitness(chromosome):
return sum(chromosome)
# 定义交叉操作
def crossover(parent1, parent2):
child1 = parent1.copy()
child2 = parent2.copy()
if random.random() < pc:
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 mutation(chromosome):
mutated_chromosome = chromosome.copy()
for i in range(len(chromosome)):
if random.random() < pm:
mutated_chromosome[i] = 1 - chromosome[i]
return mutated_chromosome
# 定义反转操作
def inversion(chromosome):
inverted_chromosome = chromosome.copy()
if random.random() < pr:
inversion_point1 = random.randint(0, len(chromosome) - 1)
inversion_point2 = random.randint(0, len(chromosome) - 1)
if inversion_point1 > inversion_point2:
inversion_point1, inversion_point2 = inversion_point2, inversion_point1
inverted_chromosome[inversion_point1:inversion_point2+1] = reversed(inverted_chromosome[inversion_point1:inversion_point2+1])
return inverted_chromosome
# 定义遗传算法函数
def genetic_algorithm(pop_size, gen):
# 初始化种群
population = [[random.randint(0, 1) for _ in range(10)] for _ in range(pop_size)]
# 进化
for _ in range(gen):
# 计算适应度值
fitness_values = [fitness(chromosome) for chromosome in population]
# 选择操作
selected_population = []
for _ in range(pop_size):
parent1 = population[random.randint(0, pop_size - 1)]
parent2 = population[random.randint(0, pop_size - 1)]
if fitness(parent1) > fitness(parent2):
selected_population.append(parent1)
else:
selected_population.append(parent2)
# 交叉操作
new_population = []
for i in range(0, pop_size, 2):
child1, child2 = crossover(selected_population[i], selected_population[i+1])
new_population.append(child1)
new_population.append(child2)
# 变异操作
new_population = [mutation(chromosome) for chromosome in new_population]
# 反转操作
new_population = [inversion(chromosome) for chromosome in new_population]
# 更新种群
population = new_population
# 返回最优解
return max(population, key=fitness)
# 输出不同群体大小和遗传代数的情况下的最优解
for pop_size in pop_sizes:
for gen in gens:
print(f"Population size: {pop_size}, Generations: {gen}")
print(f"Best solution: {genetic_algorithm(pop_size, gen)}")
print("--------------------------------------------------")
```
阅读全文