遗传算法python实例
时间: 2023-10-21 10:28:33 浏览: 56
遗传算法实例(python实现)
遗传算法是一种优化算法,用于解决复杂问题,其原理基于进化论中的自然选择和遗传机制。下面是一个简单的遗传算法 Python 实例,用于求解函数 f(x)=x^2 在 [-10,10] 区间内的最大值:
```python
import random
# 定义适应度函数
def fitness(x):
return x**2
# 初始化种群
def init_population(pop_size, chromo_size):
population = []
for i in range(pop_size):
chromosome = [random.randint(0, 1) for j in range(chromo_size)]
population.append(chromosome)
return population
# 选择操作
def selection(population):
fitness_values = [fitness(chromosome) for chromosome in population]
total_fitness = sum(fitness_values)
probabilities = [fitness_value / total_fitness for fitness_value in fitness_values]
cum_probabilities = [sum(probabilities[:i+1]) for i in range(len(probabilities))]
selected_population = []
for i in range(len(population)):
r = random.random()
for j in range(len(cum_probabilities)):
if r <= cum_probabilities[j]:
selected_population.append(population[j])
break
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):
for i in range(len(chromosome)):
if random.random() < mutation_rate:
chromosome[i] = 1 - chromosome[i]
return chromosome
# 遗传算法主程序
def genetic_algorithm(pop_size, chromo_size, max_generation, mutation_rate):
population = init_population(pop_size, chromo_size)
for generation in range(max_generation):
selected_population = selection(population)
new_population = []
for i in range(pop_size//2):
parent1, parent2 = selected_population[2*i], selected_population[2*i+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
fitness_values = [fitness(chromosome) for chromosome in population]
max_fitness_index = fitness_values.index(max(fitness_values))
return population[max_fitness_index]
# 设置参数并运行遗传算法
pop_size = 100
chromo_size = 10
max_generation = 100
mutation_rate = 0.01
result = genetic_algorithm(pop_size, chromo_size, max_generation, mutation_rate)
print('x:', int(''.join(map(str, result)), 2))
print('f(x):', fitness(result))
```
此代码中实现了遗传算法的主要步骤:初始化种群、选择、交叉和变异。其中,适应度函数 fitness(x) 中计算了 x^2 的值,init_population() 中初始化了二进制编码的染色体,selection() 中使用了轮盘赌算法进行选择,crossover() 中采用了单点交叉,mutation() 中采用了随机单点变异。最后,genetic_algorithm() 函数将上述操作组合在一起,并返回最优解。在此例中,最优解为函数 f(x)=x^2 在 [-10,10] 区间内的最大值,即 x=0。
阅读全文