请问Python中有哪些可生成多最优解的遗传优化算法?
可输出多个近优解的Python遗传优化算法推荐
针对你需要在指定时间后生成多个近优解(单目标最大化)的需求,以下几种算法和实现库最适合:
NSGA-II(非支配排序遗传算法)
原本是多目标优化的经典算法,但在单目标场景下,它通过非支配排序+拥挤度计算的机制,能有效维持种群多样性,避免过早收敛到单一最优解。你可以设置时间阈值,停止后从最终种群中筛选出适应度靠前的个体作为近优解。
用DEAP库实现的示例代码:from deap import algorithms, base, creator, tools import random import time # 定义最大化问题 creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox = base.Toolbox() # 替换为你的变量范围 toolbox.register("attr_float", random.uniform, -10, 10) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=2) toolbox.register("population", tools.initRepeat, list, toolbox.individual) # 替换为你的目标函数 def evaluate(individual): return (-(individual[0]**2 + individual[1]**2),) toolbox.register("evaluate", evaluate) toolbox.register("mate", tools.cxBlend, alpha=0.5) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2) toolbox.register("select", tools.selNSGA2) pop = toolbox.population(n=100) # 设置60秒的运行时间限制 start_time = time.time() while time.time() - start_time < 60: offspring = algorithms.varAnd(pop, toolbox, cxpb=0.5, mutpb=0.2) fits = toolbox.map(toolbox.evaluate, offspring) for fit, ind in zip(fits, offspring): ind.fitness.values = fit pop = toolbox.select(offspring + pop, k=len(pop)) # 提取前20个近优解 top_individuals = sorted(pop, key=lambda x: x.fitness.values[0], reverse=True)[:20] for idx, ind in enumerate(top_individuals): print(f"近优解{idx+1}: {ind}, 适应度: {ind.fitness.values[0]:.4f}")小生境遗传算法(Niche Genetic Algorithm)
专为单目标场景下挖掘多个峰值(近优解)设计,通过共享适应度或清除机制,让种群在不同的最优区域维持个体,避免种群聚集到单一解。pygad库内置了小生境支持,实现起来更简便:import pygad import time # 替换为你的目标函数 def fitness_func(solution, solution_idx): return -(solution[0]**2 + solution[1]**2) ga_instance = pygad.GA(sol_per_pop=100, num_parents_mating=20, fitness_func=fitness_func, num_genes=2, # 替换为你的变量范围 gene_space={'low': -10, 'high': 10}, niche_strength=2.0, # 开启小生境机制 mutation_percent_genes=10) # 设置60秒运行时间 start_time = time.time() while time.time() - start_time < 60: ga_instance.next_generation() # 获取多个近优解 top_solutions = ga_instance.solutions[ga_instance.best_solutions_indices] for idx, sol in enumerate(top_solutions): print(f"近优解{idx+1}: {sol}, 适应度: {fitness_func(sol, 0):.4f}")SPEA2(强度Pareto进化算法)
同样是多目标算法,但在单目标场景下,它通过强度值和原始适应度的结合选择个体,比NSGA-II更擅长维持种群的多样性,能找到分布更均匀的近优解。在DEAP中只需把选择算子换成tools.selSPEA2即可复用NSGA-II的大部分代码。MOEA/D(基于分解的多目标进化算法)
将单目标问题分解为多个子问题,每个子问题对应一个解,最终能得到一组分布均匀的近优解。适合需要系统挖掘多个解的场景,可通过pymoo库实现,设置时间停止条件后收集各子问题的最优解。
内容的提问来源于stack exchange,提问作者sayuri
相关产品推荐
相关产品推荐

