Created
March 2, 2018 15:04
-
-
Save jenetics/ebaf87a7ae85f9b36f16a139e4cda9c8 to your computer and use it in GitHub Desktop.
Managing the fitness diversity with the 'CyclicEngine' class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static io.jenetics.engine.EvolutionResult.toBestEvolutionResult; | |
import static io.jenetics.engine.Limits.bySteadyFitness; | |
import java.util.Random; | |
import io.jenetics.BitGene; | |
import io.jenetics.Mutator; | |
import io.jenetics.SinglePointCrossover; | |
import io.jenetics.engine.Engine; | |
import io.jenetics.engine.EvolutionResult; | |
import io.jenetics.engine.EvolutionStreamable; | |
import io.jenetics.engine.Limits; | |
import io.jenetics.example.Knapsack; | |
import io.jenetics.ext.engine.CyclicEngine; | |
public class FitnessDiversity { | |
public static void main(final String[] args) { | |
final Knapsack knapsack = Knapsack.of(15, new Random(123)); | |
// The base engine tries to approximate to good solution in current | |
// environment. | |
final Engine<BitGene, Double> baseEngine = Engine.builder(knapsack) | |
.populationSize(500) | |
.alterers( | |
new Mutator<>(0.115), | |
new SinglePointCrossover<>(0.16)) | |
.build(); | |
// The 'diversity' engine tries to broaden the search space again. | |
final Engine<BitGene, Double> diversityEngine = baseEngine.builder() | |
.alterers(new Mutator<>(0.5)) | |
.build(); | |
// Concatenates the two engines into one cyclic engine. | |
final EvolutionStreamable<BitGene, Double> engine = CyclicEngine.of( | |
// This engine stops the evolution after 10 non-improving | |
// generations and hands over to the diversity engine. | |
baseEngine.limit(() -> Limits.bySteadyFitness(10)), | |
// The higher mutation rate of this engine broadens the search | |
// space for 15 generations and hands over to the base engine. | |
diversityEngine.limit(15) | |
); | |
final EvolutionResult<BitGene, Double> best = engine.stream() | |
// The evolution is stopped after 50 non-improving generations. | |
.limit(bySteadyFitness(50)) | |
.collect(toBestEvolutionResult()); | |
System.out.println(best.getTotalGenerations()); | |
System.out.println(best.getBestPhenotype()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment