MATLAB: Stopping criterion in GA

gastopping criterion

hi everyone I have written a genetic algorithm in matlab and I need to define a stop criterion in which :
if after 100 iteration the produced answer is the same as previous answers, the algorithm must be stopped
how can I write this? can someone help?

Best Answer

alexaa - what you can do is compare, at each generation, the best found solution with the best one from the previous generation/iteration. If the absolute difference between the two is less than some tolerance, then they can be considered equal, and you just increment a counter. When that counter hits 100, exit the loop (I'm guessing that you will be using a for or while loop).
Try the following
% initialize a local variable to keep track of the previous generation's best fitness
prevGenBestFitness = [];
% initialize our counter
numGensWithSameFitness = 0;
% define a tolerance (note that this assumes real fitness scores, if
% your fitness scores are integer, then this should be set to one or
% something similar)
tol = 0.00001;
% do the GA; this will be your for or while loop
while true
% do the GA stuff
% save the best fitness from the current generation
bestFitness = ;
% compare this best with the previous best (we use ~empty to capture
% the first iteration when there is nothing to compare)
if ~isempty(prevGenBestFitness)
% we can compare
% NOTE I'm assuming that the best fitness from the current generation is
% always as good or better than the fitness from the previous generation
if abs(prevGenBestFitness-bestFitness)<tol
% the two fitnesses are considered identical so increment the
% counter
numGensWithSameFitness = numGensWithSameFitness + 1;
if numGensWithSameFitness==100
% 100 generations with same fitness, so exit
break;
end
else
% the two fitnesses are not identical so reset the counter
numGensWithSameFitness = 0;
end
end
prevGenBestFitness = bestFitness;
end
Note that the above does make certain assumptions about the fitness/score for your population and so may have to be adjusted to take into account a different scoring scheme (or data type).
Try the above and see what happens!
Related Question