写一个基于python的遗传算法
时间: 2024-06-12 08:03:58 浏览: 72
遗传算法(Genetic Algorithm)是一种通过模拟生物进化过程,寻找优化问题最优解的一种方法。Python可以很方便地实现遗传算法,下面是一个简单的示例代码:
```python
import random
# 遗传算法的参数设置
POP_SIZE = 50 # 种群大小
GENE_LENGTH = 20 # 基因长度
CROSS_RATE = 0.8 # 交叉概率
MUTATION_RATE = 0.01 # 变异概率
N_GENERATIONS = 300 # 迭代次数
# 初始化种群
def init_population():
population = []
for i in range(POP_SIZE):
gene = [random.randint(0, 1) for _ in range(GENE_LENGTH)] # 随机生成一个基因
population.append(gene)
return population
# 选择
def selection(population, fitness):
idx = random.choice(range(POP_SIZE))
return population[idx]
# 交叉
def crossover(parent1, parent2):
if random.random() < CROSS_RATE:
idx = random.randint(0, GENE_LENGTH-1)
offspring1 = parent1[:idx] + parent2[idx:]
offspring2 = parent2[:idx] + parent1[idx:]
return offspring1, offspring2
else:
return parent1, parent2
# 变异
def mutation(offspring):
for i in range(GENE_LENGTH):
if random.random() < MUTATION_RATE:
offspring[i] = 1 - offspring[i]
return offspring
# 计算适应度
def calc_fitness(gene):
return sum(gene)
# 遗传算法主函数
def genetic_algorithm():
population = init_population()
for generation in range(N_GENERATIONS):
# 计算适应度
fitness = [calc_fitness(gene) for gene in population]
# 选择两个个体
parent1 = selection(population, fitness)
parent2 = selection(population, fitness)
# 交叉
offspring1, offspring2 = crossover(parent1, parent2)
# 变异
offspring1 = mutation(offspring1)
offspring2 = mutation(offspring2)
# 替换
idx = random.choice(range(POP_SIZE))
population[idx] = offspring1
idx = random.choice(range(POP_SIZE))
population[idx] = offspring2
# 返回最优解
best_gene = max(population, key=calc_fitness)
return best_gene
# 测试
best_gene = genetic_algorithm()
print(best_gene)
```
该示例代码中,我们通过随机生成0/1的基因来初始化种群,然后迭代300次进行选择、交叉、变异和替换操作,最终返回适应度最高的基因作为最优解。其中,选择操作采用了轮盘赌选择方式,交叉概率为0.8,变异概率为0.01。这个示例代码比较简单,只是为了展示遗传算法的基本流程,实际应用中需要根据具体问题进行调整和优化。
阅读全文