我正在使用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 go 会产生 3 条染色体,从而最大化此评估函数,但我得到:
[01110010|00010111,01000000|00000100,10011101|01110110]
如您所见,只有第一个结果满足条件。我如何扩展这个例子,以便所有染色体都最大化评估函数?
最佳答案
这正是我在查看适应度函数后所期望的。您仅使用第一条染色体来计算适应度。 Genotype.getChromosome()
方法返回第一个染色体。它是 Genotype.getChromosome(0)
的快捷方式。您的适应度函数中不考虑其他两条染色体。
关于java - 使用 Jenetics 仅一条染色体显示出良好结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47196922/