Introduction:This tutorial contains information how to create and use Java Genetic Algorithm Library.Creating population:
To create population we will use default construtor.
Population oldPopulation = new Population();
Now we have empty population. Let's fill it by chromosomes. To do that we will use standardBitChromosome model where all genes are represent by bit - true or false. Before we do that we have to define fitness function. This function is used to calculate value (fitness value) of the chromosome. We can create our own function using FittnessFunctionModel interfase or use funcitons from package. In this tutorial we will use package function BitFitnessFunction were value of the chromosome is calculated according to the formula y = y + i ^2 where:
y - is fitness function value i - is position of gene (bit) in chromosome
BitFitnessFunction fitnesssFunction = new BitFitnessFunction();
Now we can fill our population. Chromosome size is defined to 10, cross over propability is set to 1.0 and mutation propability is set to 0.0
int chromosomeSize = 10;
for (int i=0; i < populationSize; i++){ oldPopulation.addChromosome(new BitChromosome(chromosomeSize,fitnesssFunction)); } Learning:
When we have population we can start using our population. To to that we have to define cross over function and roulette function. To to that we will use standard function.
DefaultCrossFunctionModel crossFunctionModel = new DefaultCrossFunctionModel();
RouletteReproductionFunctionModel reproductionModel = new RouletteReproductionFunctionModel();
Now we can create learning algorythm for earlier create population. Number of intaration will be set to 10.
LearningAlgorythm learning = new LearningAlgorythm(oldPopulation,10);
Learning algorytm must know which Cross Over function andReproduction function have to use.
learning.setReproductionFunctionModel(reproductionModel);
learning.setCrossFunctionModel(crossFunctionModel);
Let's start learning process:
learning.learn();
At the end we can write list of best chromosome in each iteration. First we will create ArrayList with chromosomes and then print it.
ArrayList bestChromosome = learning.getBestChromosomeList();
System.out.println(bestChromosome); |