python遗传算法_【机器学习】遗传算法(Genetic Algorithm)的Python实现
时间: 2024-06-08 13:09:20 浏览: 112
遗传算法Genetic Algorithm代码复现【Python】
5星 · 资源好评率100%
遗传算法是一种模拟自然进化过程的优化算法,主要用于解决复杂的优化问题。在遗传算法中,通过对个体(解)进行基因操作(交叉、变异等),不断地产生新的个体,并通过选择机制,筛选出适应度高的个体,从而逐步优化得到最优解。
下面是一个简单的遗传算法的Python实现代码:
```python
import random
# 定义适应度函数
def fitness(individual):
# 适应度函数为 x^2 的形式,其中 x 为个体的染色体长度
return sum([gene**2 for gene in individual])
# 初始化种群
def init_population(pop_size, gene_size):
population = []
for i in range(pop_size):
individual = [random.randint(0, 1) for j in range(gene_size)]
population.append(individual)
return population
# 选择操作
def selection(population):
# 轮盘赌选择
fitness_values = [fitness(individual) for individual in population]
total_fitness = sum(fitness_values)
probabilities = [fitness/total_fitness for fitness in fitness_values]
selected_population = []
for i in range(len(population)):
selected_individual = None
while selected_individual is None:
for j in range(len(population)):
if random.random() < probabilities[j]:
selected_individual = population[j]
break
selected_population.append(selected_individual)
return selected_population
# 交叉操作
def crossover(parent1, parent2, crossover_rate):
# 一点交叉
if random.random() > crossover_rate:
return 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 mutation(individual, mutation_rate):
# 每个基因以 mutation_rate 的概率发生变异
for i in range(len(individual)):
if random.random() < mutation_rate:
individual[i] = 1 - individual[i]
return individual
# 遗传算法
def genetic_algorithm(pop_size, gene_size, max_generation, crossover_rate, mutation_rate):
population = init_population(pop_size, gene_size)
for i in range(max_generation):
population = selection(population)
new_population = []
while len(new_population) < pop_size:
parent1, parent2 = random.sample(population, 2)
child1, child2 = crossover(parent1, parent2, crossover_rate)
child1 = mutation(child1, mutation_rate)
child2 = mutation(child2, mutation_rate)
new_population.append(child1)
new_population.append(child2)
population = new_population
best_individual = min(population, key=lambda individual: fitness(individual))
return best_individual
# 测试
best_individual = genetic_algorithm(pop_size=100, gene_size=10, max_generation=1000, crossover_rate=0.8, mutation_rate=0.1)
print(best_individual, fitness(best_individual))
```
在上面的代码中,定义了适应度函数、初始化种群、选择、交叉、变异等操作,并通过遗传算法不断迭代,最终得到最优解。在测试中,我们设定种群大小为100,染色体长度为10,最大迭代次数为1000,交叉率为0.8,变异率为0.1,得到的最优解为[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],适应度函数的值为0。
阅读全文