You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyGAD如何生成仅含0/1的解并进化至全1最优列表?

PyGAD二进制种群约束与全1最优解实现

一、限制种群取值为0和1的核心方案

PyGAD默认交叉/变异逻辑可能产生浮点数,需从基因类型约束和遗传操作适配两方面解决:

  • 强制基因类型为整数:初始化GA时设置gene_type=int,确保所有基因始终为整数,避免浮点值生成。
  • 使用二进制专属遗传操作:
    • 交叉选择crossover_type="single_point"(单点交叉),仅交换基因片段,不会产生中间值。
    • 自定义变异函数,仅执行0/1翻转操作,杜绝非二进制值:
      def custom_mutation(ga_instance, offspring, offspring_idx):
          mutation_chance = ga_instance.mutation_percent_genes / 100
          for idx in range(len(offspring)):
              if random.random() < mutation_chance:
                  offspring[idx] = 1 - offspring[idx]
          return offspring
      
    替代默认变异逻辑,确保变异后基因仅在0和1之间切换。

二、引导种群进化到全1解的参数调整

你的适应度函数sum(solution)方向正确(全1解适应度为40,是最大值),只需调整进化参数加速收敛:

  • 增加种群规模:从初始10个个体提升到50-100,提升种群多样性。
  • 增加进化代数:设置num_generations=100甚至更高,给种群足够进化时间。
  • 调整遗传操作概率:
    • 交叉概率设为crossover_probability=0.8,保证优良基因传递。
    • 变异概率控制在mutation_percent_genes=2-5,避免过度变异破坏优良解。
  • 开启精英保留:设置keep_parents=2,将每代最优的2个个体直接保留到下一代,锁定最优基因。

完整可运行代码示例

import pygad
import random

# 初始化50个个体的二进制种群,每个个体含40个基因
initial_population = [[random.randint(0,1) for _ in range(40)] for _ in range(50)]

# 适应度函数:计算基因总和,值越大越优
def fitness_func(ga_instance, solution, solution_idx):
    return sum(solution)

# 自定义二进制变异函数:仅翻转0/1
def custom_mutation(ga_instance, offspring, offspring_idx):
    mutation_chance = ga_instance.mutation_percent_genes / 100
    for idx in range(len(offspring)):
        if random.random() < mutation_chance:
            offspring[idx] = 1 - offspring[idx]
    return offspring

# 创建GA实例并配置参数
ga_instance = pygad.GA(
    num_generations=100,
    num_parents_mating=20,
    initial_population=initial_population,
    fitness_func=fitness_func,
    gene_type=int,
    crossover_type="single_point",
    mutation_type=custom_mutation,
    mutation_percent_genes=3,
    keep_parents=2,
    save_best_solutions=True
)

# 启动进化
ga_instance.run()

# 输出结果
best_sol, best_fitness, _ = ga_instance.best_solution()
print(f"最优适应度值:{best_fitness}")
print(f"最优解是否为全1:{all(gene == 1 for gene in best_sol)}")

内容的提问来源于stack exchange,提问作者Bill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:20:41