关于遗传算法的python代码
时间: 2023-07-23 07:11:06 浏览: 60
以下是一个简单的遗传算法的Python代码示例,用于求解一个简单的优化问题(最大化函数):
```python
import random
# 定义适应度函数(目标函数)
def fitness_function(x):
return x**2
# 初始化种群
def initialize_population(population_size, chromosome_length):
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
return population
# 选择操作(轮盘赌选择)
def selection(population, fitness_values):
total_fitness = sum(fitness_values)
probabilities = [fitness / total_fitness for fitness in fitness_values]
selected_indices = random.choices(range(len(population)), probabilities, k=len(population))
selected_population = [population[i] for i in selected_indices]
return selected_population
# 交叉操作(单点交叉)
def crossover(parent1, parent2):
crossover_point = random.randint(0, len(parent1) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 变异操作(位翻转变异)
def mutation(chromosome, mutation_rate):
mutated_chromosome = chromosome.copy()
for i in range(len(mutated_chromosome)):
if random.random() < mutation_rate:
mutated_chromosome[i] = 1 - mutated_chromosome[i]
return mutated_chromosome
# 遗传算法主函数
def genetic_algorithm(population_size, chromosome_length, generations, mutation_rate):
population = initialize_population(population_size, chromosome_length)
for _ in range(generations):
fitness_values = [fitness_function(chromosome) for chromosome in population]
selected_population = selection(population, fitness_values)
new_population = []
while len(new_population) < population_size:
parent1, parent2 = random.sample(selected_population, 2)
child1, child2 = crossover(parent1, parent2)
mutated_child1 = mutation(child1, mutation_rate)
mutated_child2 = mutation(child2, mutation_rate)
new_population.extend([mutated_child1, mutated_child2])
population = new_population
best_chromosome = max(population, key=fitness_function)
best_fitness = fitness_function(best_chromosome)
return best_chromosome, best_fitness
# 测试
population_size = 50
chromosome_length = 10
generations = 100
mutation_rate = 0.01
best_chromosome, best_fitness = genetic_algorithm(population_size, chromosome_length, generations, mutation_rate)
print("Best Chromosome:", best_chromosome)
print("Best Fitness:", best_fitness)
```
这是一个简单的遗传算法实现,用于最大化函数`x^2`。你可以根据具体问题的需求进行适应度函数、初始化种群、选择、交叉、变异等部分的定制。