您可能会查看Codec界面。该接口负责将问题域的对象转换为Genotype
. 如果我正确理解您的问题,可能的编码可能如下所示:
static final List<String> OBJECTS = List.of("A", "B", "C", "D");
static final int LENGTH = 10;
static final Codec<List<String>, IntegerGene> CODEC = Codec.of(
// Create the Genotype the GA is working with.
Genotype.of(IntegerChromosome.of(0, OBJECTS.size() - 1, LENGTH)),
// Convert the Genotype back to your problem domain.
gt -> gt.chromosome().stream()
.map(IntegerGene::allele)
.map(OBJECTS::get)
.collect(Collectors.toList())
);
// Calculate the fitness function in terms of your problem domain.
static double fitness(final List<String> objects) {
return 0;
}
static final Engine<IntegerGene, Double> ENGINE = Engine
.builder(Main::fitness, CODEC)
.build();
Codec
创建Genotype
由长度为 10的a 组成的 aIntegerChromosome
并将其转换回您的问题域。
我不确定我是否正确理解了您的第二个问题。但是如果你也想收集中间结果,你可以使用该Stream::peek
方法。
public static void main(final String[] args) {
final List<Phenotype<IntegerGene, Double>> intermediateResults = new ArrayList<>();
final var bestPhenotype = ENGINE.stream()
.limit(Limits.bySteadyFitness(25))
.peek(er -> intermediateResults.add(er.bestPhenotype()))
.collect(EvolutionResult.toBestPhenotype());
}