GenerateRandom rnd = new MersenneTwisterGenerateRandom();
EvaluateExpression eval = new EvaluateExpression(rnd);
Population pop = initPopulation(rnd, eval);
ScoreFunction score = new ScoreSmallExpression(training,30);
EvolutionaryAlgorithm genetic = new BasicEA(pop, score);
genetic.addOperation(0.3, new MutateTree(3));
genetic.addOperation(0.7, new CrossoverTree());
genetic.setShouldIgnoreExceptions(false);
int sameSolutionCount = 0;
int iteration = 1;
double lastSolution = Double.MAX_VALUE;
StringBuilder builder = new StringBuilder();
while (sameSolutionCount < MAX_SAME_SOLUTION && iteration<1000) {
genetic.iteration();
double thisSolution = genetic.getLastError();
builder.setLength(0);
builder.append("Iteration: ");
builder.append(iteration++);
builder.append(", Current error = ");
builder.append(thisSolution);
builder.append(", Best Solution Length = ");
builder.append(genetic.getBestGenome().size());
System.out.println(builder.toString());
if (Math.abs(lastSolution - thisSolution) < 1.0) {
sameSolutionCount++;
} else {
sameSolutionCount = 0;
}
lastSolution = thisSolution;
}
System.out.println("Good solution found:");
TreeGenome best = (TreeGenome) genetic.getBestGenome();
System.out.println(eval.displayExpressionNormal(best.getRoot()));
genetic.finishTraining();
}