使用 Jenetics 只有一条染色体显示出良好的结果

Only one chromosome shows good results using Jenetics

我正在使用 Jenetics 库来解决 ga 的问题。我正在扩展官方示例以使用多个这样的染色体:

    List<BitChromosome> arr = new ArrayList<>();
    arr.add(BitChromosome.of(16, 0.5));
    arr.add(BitChromosome.of(16, 0.5));
    arr.add(BitChromosome.of(16, 0.5));
    Factory<Genotype<BitGene>> gtf = Genotype.of(arr);

并更改 eval 函数使其恰好有 8 个 1 和 8 个 0:

    private static int eval(Genotype<BitGene> gt) {
    return 10 - Math.abs(gt.getChromosome()
            .as(BitChromosome.class)
            .bitCount()-8);

其他部分保持不变:

    // 3.) Create the execution environment.
    Engine<BitGene, Integer> engine = Engine
            .builder(Test1::eval, gtf)
            .build();

    // 4.) Start the execution (evolution) and
    //     collect the result.
    Genotype<BitGene> result = engine.stream()
            .limit(100)
            .collect(EvolutionResult.toBestGenotype());

我原以为 ga 会产生 3 个染色体来最大化这个 eval 函数,但我得到:

[01110010|00010111,01000000|00000100,10011101|01110110]

可以看到,只有第一个结果满足条件。我怎样才能扩展这个例子,让所有的染色体都最大化评估函数?

这正是我在查看适应度函数后所期望的。您仅使用第一条染色体来计算适应度。 Genotype.getChromosome()方法returns第一个染色体。它是 Genotype.getChromosome(0) 的快捷方式。其他两条染色体不在你的适应度函数中考虑。