遗传算法优化:初始解生成与种群演化
init_solution=generate_init_solution()
贪心算法产生初始解
print(init_solution)
population=[init_solution]+[random.sample(init_solution,len(init_solution)) for i in range(population_size*2-1)]
population= sorted(population, key=lambda x: calculate_fitness(x), reverse=False)[:population_size//2]
population=[init_solution]+[random.sample(init_solution,len(init_solution)) for i in range(population_size-1)]
迭代寻优
for _ in range(n_generations): # 选择(3元锦标赛) 两两比较 选1半 population=tournament_selection(population) offspring=population.copy() # 保留优秀父代population
# 交叉 用population
num_list=list(range(len(offspring)))
for i in range(0, len(offspring)//2): # 以步长为2依次选取两个染色体
a,b=random.sample(num_list,2)
chromosome1 = offspring[a]
chromosome2 = offspring[b]
#print(chromosome1,chromosome2)
if random.random() < crossover_probability:# 局部匹配交叉
new_chromosome1,new_chromosome2=cx_partialy_matched(chromosome1, chromosome2)
#print(new_chromosome1,new_chromosome2)
offspring[a] = new_chromosome1
offspring[b] = new_chromosome2
num_list.remove(a)
num_list.remove(b)
# 变异(反转\交换二选一)
for mutant in offspring:
if random.random() < mutation_probability:
if random.random()<0.5: # 反转变异 均匀变异--按照0.2固定的概率对每个基因进行随机变异
mutant = reverse_mutation(mutant, indpb=0.2) # 对个体进行反转变异
else: # 交换变异
mutant =swap_mutation(mutant, indpb=0.2) # 对个体进行交换变异
# 将变异后的子代和父代合并,形成下一代种群
population=population + offspring #50+50
输出结果
best_solution=population[0]
这个算法可能存在以下问题:
-
种群数量较小:种群数量只有50个,可能不足以保证全局最优解的探索。
-
遗传算子的选择:该算法采用的是局部匹配交叉和交换、反转二选一的变异方式,但是这些遗传算子的效果可能不如其他算子,需要根据具体问题进行选择。
-
算法收敛速度慢:该算法只有一个初始解,可能无法快速探索到更优解,需要增加多个初始解或者采用其他启发式算法进行初始解的生成。同时,在交叉、变异等操作中也可能存在局部最优解的问题,导致算法收敛速度慢。
原文地址: https://www.cveoy.top/t/topic/oeM9 著作权归作者所有。请勿转载和采集!