生成一个简单的遗传算法代码Python
时间: 2023-08-06 22:05:24 浏览: 44
好的,以下是一个简单的遗传算法代码 Python 实现:
```python
import random
# 初始化种群
def init_population(population_size, chromosome_length):
population = []
for i in range(population_size):
chromosome = [random.randint(0, 1) for j in range(chromosome_length)]
population.append(chromosome)
return population
# 计算适应度
def fitness(chromosome):
return sum(chromosome)
# 选择
def selection(population):
fitness_list = [fitness(chromosome) for chromosome in population]
total_fitness = sum(fitness_list)
selection_probabilities = [fitness / total_fitness for fitness in fitness_list]
cum_prob = 0
for i in range(len(selection_probabilities)):
cum_prob += selection_probabilities[i]
selection_probabilities[i] = cum_prob
new_population = []
for i in range(len(population)):
r = random.uniform(0, 1)
index = 0
while selection_probabilities[index] < r:
index += 1
new_population.append(population[index])
return new_population
# 交叉
def crossover(parent1, parent2):
crossover_point = random.randint(0, len(parent1) - 1)
child1 = parent1[0:crossover_point] + parent2[crossover_point:]
child2 = parent2[0:crossover_point] + parent1[crossover_point:]
return child1, child2
# 变异
def mutation(chromosome, mutation_rate):
for i in range(len(chromosome)):
if random.uniform(0, 1) < mutation_rate:
chromosome[i] = 1 - chromosome[i]
return chromosome
# 遗传算法主函数
def genetic_algorithm(population_size, chromosome_length, max_generations, mutation_rate):
population = init_population(population_size, chromosome_length)
best_fitness = 0
best_chromosome = []
for generation in range(max_generations):
population = selection(population)
new_population = []
for i in range(int(population_size / 2)):
parent1 = population[random.randint(0, population_size - 1)]
parent2 = population[random.randint(0, population_size - 1)]
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
new_population.append(child1)
new_population.append(child2)
population = new_population
for chromosome in population:
chromosome_fitness = fitness(chromosome)
if chromosome_fitness > best_fitness:
best_fitness = chromosome_fitness
best_chromosome = chromosome
print("Generation:", generation + 1, "Best Fitness:", best_fitness, "Best Chromosome:", best_chromosome)
# 运行遗传算法
genetic_algorithm(population_size=50, chromosome_length=10, max_generations=100, mutation_rate=0.01)
```
这个遗传算法代码实现了一个简单的 0-1 背包问题,种群大小为 50,染色体长度为 10,最大迭代次数为 100,变异率为 0.01。你可以根据自己的需求修改这些参数。