c++ 遗传算法 代码
时间: 2023-05-14 16:02:57 浏览: 210
遗传算法是一种模拟生物进化的计算方法,它模拟了生物进化的过程,通过遗传、选择、交叉和突变等操作,逐步优化求解目标函数。它以群体的方式寻找全局最优解,是一种高效的全局搜索优化算法。
下面是一段简单的实现遗传算法的Python代码:
1.初始化种群
import random
def init_population(pop_size, chrom_length):
"""初始化种群"""
population = []
for i in range(pop_size):
chrom = [random.randint(0, 1) for j in range(chrom_length)]
population.append(chrom)
return population
2.计算适应度
def fitness_func(chrom):
"""计算适应度"""
x = get_x(chrom)
y = x**2
return y
def get_x(chrom):
"""将二进制数转换为十进制数"""
x = 0
for i, bit in enumerate(chrom):
x += bit*pow(2, len(chrom)-i-1)
return x
3.选择
def selection(population, k=2):
"""选择"""
mate_pool = []
for i in range(len(population)):
candidates = random.sample(population, k)
best_cand = max(candidates, key=fitness_func)
mate_pool.append(best_cand)
return mate_pool
4.交叉
def crossover(mate_pool, cross_rate=0.8):
"""交叉"""
offspring = []
for i in range(0, len(mate_pool), 2):
chrom1 = mate_pool[i]
chrom2 = mate_pool[i+1]
if random.random() < cross_rate:
pos = random.randint(1, len(chrom1)-1)
new_chrom1 = chrom1[:pos]+chrom2[pos:]
new_chrom2 = chrom2[:pos]+chrom1[pos:]
offspring.extend([new_chrom1, new_chrom2])
else:
offspring.extend([chrom1, chrom2])
return offspring
5.突变
def mutation(offspring, mutation_rate=0.01):
"""突变"""
for i in range(len(offspring)):
if random.random() < mutation_rate:
pos = random.randint(0, len(offspring[i])-1)
offspring[i][pos] = 1-offspring[i][pos]
return offspring
6.执行遗传算法
def genetic_algorithm(pop_size, chrom_length, max_gen):
population = init_population(pop_size, chrom_length)
for i in range(max_gen):
mate_pool = selection(population)
offspring = crossover(mate_pool)
offspring = mutation(offspring)
population = offspring
best_chrom = max(population, key=fitness_func)
best_x = get_x(best_chrom)
best_y = fitness_func(best_chrom)
return best_chrom, best_x, best_y
如果需要改变这个遗传算法的目标函数,只需要修改3中的fitness_func函数即可。此代码为一个简单的实现,处理问题的能力有限,可能会出现算法收敛速度慢、过早收敛或局部最优问题等。在实际应用中需根据具体问题进行优化。
阅读全文