Reprint please indicate the origin: http://blog.csdn.net/tyhj_sf/article/details/53321527 principle
In order to better explain and understand the principle of genetic algorithm and the operation process, the following combined with examples of genetic algorithms to simulate the main implementation steps.
For example: Find the maximum value of the following two-dollar function:
(1) Individual coding
The arithmetic object of the genetic algorithm is the symbolic string representing the individual, so the variable must be X1 and x2 encoded into a symbolic string. In this subject, the unsigned binary integer is used to represent the. Because of the X1, X2 is 0 ~ 7 integer, so the 3-bit unsigned binary integers, respectively, the combination of the 6-bit unsigned binary numbers formed the individual genotype, representing a feasible solution.
For example, the phenotype of genotype x=101110 is: x=[5,6]. Individual phenotype x and genotype x can be converted to each other by encoding and decoding programs.
The Java code corresponding to this step:
/** Gene Length * * Public
static final int gene_length = 6;
The/** gene corresponds to the numerical upper limit, determined by the gene's number of digits
/public static final int NUM = 1 << gene_length;
And:
/**
* @param size
* @Description: Initialization gene length *
/
private void initgenesize (int size) {
if (size <= 0 ) {return
;
}
Gene = new boolean[size];
}
/**
* @param size
* Randomly generated gene sequence
*
/Public chromosome (int size) {
if (size <= 0) {return
;
}
initgenesize (size);
for (int i = 0; i < size; i++) {
Gene[i] = math.random () >= 0.5;
}
}
(2) generation of initial population
Genetic Algorithm (GA) is an evolutionary operation to the population, and some initial population data representing the starting search point must be prepared.
In this case, the size of the population is 4, that is, the group is composed of 4 individuals, each individual can pass a random
Method is produced. such as: 011101,101011,011100,111001
The Java code corresponding to this step:
/**
* @Description: Initialize the population
*
/private void init () {
System.out.println ("1> Generate initial population ...");
Ddwindow.setvisible (true);
Population = new arraylist<chromosome> ();
for (int i = 0; i < popsize i++) {
chromosome chro = new chromosome (genesize);
Population.add (CHRO);
}
(3) The calculation of fitness
in the genetic algorithm, the degree of individual fitness is evaluated to determine the size of the genetic opportunity.
In this example, the objective function is always non-negative, and the maximum value of the function is the optimization objective, so the objective function value can be used as the adaptive degree of the individual.
The Java code corresponding to this step:
/** * @Description: Calculating population fitness/private void Cacultescore () {System.out.println ("2>) calculates population fitness."
.");
Bestscore= (double) population.get (0). Getscore ();
Worstscore= (double) population.get (0). Getscore ();
Totalscore = 0;
for (chromosome chro:population) {setchromosomescore (CHRO);
if (Chro.getscore () > Bestscore) {//Set the best genetic value Bestscore = Chro.getscore ();
if (Y < Bestscore) {x = Changex (CHRO);
y = Bestscore;
Genei = generation; } if (Chro.getscore () < Worstscore) {//Set the worst genetic value Worstscore = CHRO.GETSC
Ore ();
} Totalscore + = Chro.getscore ();
} Averagescore = Totalscore/popsize; Because the precision problem results in an average greater than the best value, set the average to best value Averagescore = averagescore > Bestscore? Bestscore:averAgescore; }
(4) Select Operation
A select operation (or a copy operation) is used to pass on a rule or model to the next generation of individuals with a higher degree of adaptability in the current group. Individuals with a higher degree of adaptation generally require more opportunities to be passed on to the next generation group.
In this case, we use the probability proportional to the fitness to determine the number of individual individuals copied to the next generation group. Its specific operation process is:
• First calculate the sum of the fitness of all the individuals in the group Σfi (i=1.2,..., M);
• Second, calculate the size of each individual's relative fitness fi/σfi, which is inherited for each individual
The probability of being in the next generation group,
• Each probability value constitutes an area, and the sum of the total probability value is 1;
• Finally, a random number from 0 to 1 is generated, according to which probability region the random number appears
field to determine the number of times each individual is selected.
The Java code corresponding to this step:
/** *
@return *
email:tyhj_sf@163.com *
@Description: Roulette option can be inherited from the next generation of chromosomes * *
Private chromosome Getparentchromosome () {
System.out.println ("4.1> Filter parent population once ...");
while (true) {
double slice = math.random () * Totalscore;
Double sum = 0;
for (chromosome chro:population) {
sum + = Chro.getscore ();
System.out.println ("Test: sum=" +sum+ " chro.getscore () =" +chro.getscore ());
if (Sum > Slice && chro.getscore () >= averagescore) {return
chro;
}
}
}
(5) Cross Operation
Crossover operation is the main process of generating new individuals in genetic algorithm, which exchanges some chromosomes between two individuals in a certain probability.
This example uses the single point intersection method, its concrete operation process is:
• Random pairing of groups;
Second, randomly set up the intersection point position;
• Finally exchange the genes between the paired chromosomes.
The Java code corresponding to this step:
/** * @Description: Population for genetic/private void evolve () {List<chromos
ome> childpopulation = new arraylist<chromosome> (); Generate next-generation population while (Childpopulation.size () < popsize) {chromosome parent1 = Getparentchromosome ()
;
Chromosome Parent2 = Getparentchromosome ();
list<chromosome> children = chromosome.genetic (parent1, Parent2); if (children!= null) {for (chromosome Chro:children) {childpopulation.add (CHR
O);
}} System.out.println ("4.2> produces descendant population ...");
Replacement of old population by new species population.clear ();
Population = childpopulation; }
(6) Mutation Operation
The mutation operation is to change the genetic value of one or some of the loci according to a small probability, it is also a method of producing new individuals.
In this example, we use the basic bit mutation method for mutation operations, the specific procedures are:
• First determine the genetic variation of each individual, the following table shows the location of the randomly generated variation points,
The number indicates that the mutation point is set at the gene locus;
• Then the original gene value of the mutation point is reversed according to a certain probability.
The Java code corresponding to this step:
/**
* Gene mutation
/
private void mutation () {
System.out.println ("5> gene mutation ...");
for (chromosome chro:population) {
if (Math.random () < Mutationrate) {//mutated gene mutation
int mutationnum = (int) (Math . Random () * maxmutationnum);
Chro.mutation (Mutationnum);}}
(7) Iterative
A new generation of group P (t+1) can be obtained after a selection, crossover and mutation operation of group P (t).
As can be seen from the table above, after a generation of evolution, the maximum and average fitness of the population has been significantly improved. In fact, the best individual "111111" has been found here.
It should be explained that the data in some columns of the table are randomly generated. In order to better illustrate the problem, we deliberately selected some good values to be able to get better results, and in the actual operation of the process may require a certain number of cycles to achieve this optimal result. As shown in the following illustration, set the number of loops to 500 times, and the results of each loop quickly converge to the maximum value.
The Java code corresponding to this step:
/**
* Iterative Operation
*/public
void Caculte () {
//1. Initialize population
init ();
for (generation = 1; generation < Maxiternum; generation++) {
//2. Calculation of population adaptability
cacultescore ();
SYSTEM.OUT.PRINTLN ("3> authentication threshold ...");
4. Population genetic
evolve ();
5. Gene mutation
mutation ();
Print ();
}
}
Special attention
The basic genetic algorithm uses 3 kinds of genetic operators :
1 Select operator using proportional selection;
2 cross operation using single point crossover operator;
3 The mutation operation uses the basic bit mutation operator or the uniform mutation operator.
Run parameter Settings :
1 group size, generally set to 20-100 chromosomes;
2 evolutionary algebra, generally set to 100-500 generations;
3 chromosome crossover probability, generally set to 0.4-0.99;
4 mutation probability, generally set to 0.0001-0.1; Complete Source
Please write down your email in the comments section of the students who need the complete project source files under Eclipse.
Because the code is longer, only a partial code of genetic algorithm to facilitate the understanding of the principle of the previous explanation, the graphical interface dynamic display part no longer posted:
The code has already added a large number of comments, no longer explain the code, please check the previous principle of their own analysis. chromosome type chromosome source code:
public class Chromosome {private boolean[] gene;//gene sequence private double score;//corresponding function score public double GE
Tscore () {return score;
The public void SetScore (double score) {This.score = score; /** * @param size * Random-generated gene sequence * */public chromosome (int size) {if (size <= 0)
{return;
} initgenesize (size);
for (int i = 0; i < size; i++) {Gene[i] = Math.random () >= 0.5; }/** * Generates a new gene */public chromosome () {}/** * @param c * @re Turn * @Description: Cloning gene */public static chromosome clone (final chromosome C) {if (c = = nul L | |
C.gene = = null) {return null;
} Chromosome copy = new chromosome ();
Copy.initgenesize (c.gene.length);
for (int i = 0; i < c.gene.length; i++) { Copy.gene[i] = C.gene[i];
return copy;
/** * @param size * @Description: Initialization gene length */private void initgenesize (int size) {
if (size <= 0) {return;
Gene = new Boolean[size]; /** * @param C1 * @param c2 * @Description: Genetic generation/public static List<chrom
Osome> genetic (chromosome P1, chromosome p2) {if (P1 = null | | p2 = NULL) {//chromosome has one empty, does not produce the next generation
return null;
} if (P1.gene = null | | p2.gene = NULL) {//chromosome has a no gene sequence, does not produce next generation return null;
} if (P1.gene.length!= p2.gene.length) {//chromosome gene sequence length is different, do not produce next generation return null;
} Chromosome C1 = Clone (p1);
Chromosome C2 = Clone (p2);
Randomly generated cross swap position int size = C1.gene.length;
int a = (int) (Math.random () * size)% size; int B = (inT) (Math.random () * size))% size; int min = a > B?
b:a; int max = a > B?
A:B;
Cross-swap Boolean t for gene in position;
for (int i = min; I <= max; i++) {t = C1.gene[i];
C1.gene[i] = C2.gene[i];
C2.gene[i] = t;
} list<chromosome> List = new arraylist<chromosome> ();
List.add (C1);
List.add (C2);
return list;
/** * @param num * @Description: Gene num position variation/public void mutation (int num) {
Allow variation int size = Gene.length;
for (int i = 0; i < num; i++) {//Find mutation position int at = ((int) (Math.random () * size))% size;
The variable value boolean bool =!gene[at];
Gene[at] = bool; }/** * @return * @Description: Converts the gene to the corresponding number/public int getnum () {if ( Gene = NULL) {return 0;
int num = 0;
For (Boolean bool:gene) {num <<= 1;
if (bool) {num = 1;
} return num; }
}
main algorithm class Geneticalgorithm source code:
Public abstract class Geneticalgorithm {private list<chromosome> population = new arraylist<chromosome>
();
/** Population Number * * Private int popsize = 40;
/** Chromosome Maximum length * * private int genesize;
/** Maximum iterative number of * * private int maxiternum = 500;
Probability of/** gene mutation * * private double mutationrate = 0.001;
/** Maximum mutation step/private int maxmutationnum = 3;
/** is currently hereditary to the first few generations */private int generation = 1; Private double bestscore;//best score private double worstscore;//worst score private double totalscore;//total score Private Double averagescore;//average score private double X; Record the best x value in the history population private double y;
Record the best Y value of the historical population private int genei;//x y where the algebra private Dynamicdatawindow Ddwindow;
Private long TP;
Public geneticalgorithm (int genesize) {this.genesize = genesize;
public void Caculte () {//1. Initialize population init ();
for (generation = 1; generation < Maxiternum; generation++) { 2. Calculation of population adaptability cacultescore ();
SYSTEM.OUT.PRINTLN ("3> authentication threshold ...");
4. Population genetic evolve ();
5. Gene mutation mutation ();
Print (); }/** * @Description: Output/private void print () {System.out.println ("------
--------------------------");
SYSTEM.OUT.PRINTLN ("The Generation is:" + generation);
System.out.println ("The Best y is:" + bestscore);
System.out.println ("The Worst Fitness is:" + worstscore);
System.out.println ("The average fitness is:" + averagescore);
System.out.println ("The Total Fitness is:" + totalscore);
System.out.println ("Genei:" + Genei + "\TX:" + x + "\ty:" + (y));
Long Millis=system.currenttimemillis ();
if (millis-tp>300) {tp=millis;
Ddwindow.adddata (Millis, y);
try {thread.sleep (10L); catch (inTerruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }/** * @Description: Initializing population/private void init () {System.out.println ("1>
Into the initial population ... ");
Ddwindow.setvisible (TRUE);
Population = new arraylist<chromosome> ();
for (int i = 0; i < popsize i++) {Chromosome chro = new chromosome (genesize);
Population.add (CHRO); }/** * @Description: Population for genetic/private void evolve () {list<chromosome> C
Hildpopulation = new arraylist<chromosome> (); Generate next-generation population while (Childpopulation.size () < popsize) {chromosome parent1 = Getparentchromosome ()
;
Chromosome Parent2 = Getparentchromosome ();
list<chromosome> children = chromosome.genetic (parent1, Parent2); if (children!= null) {for(Chromosome Chro:children)
{Childpopulation.add (CHRO);
}} System.out.println ("4.2> produces descendant population ...");
Replacement of old population by new species population.clear ();
Population = childpopulation; /** * @return * email:tyhj_sf@163.com * @Description: Roulette option can be inherited from the next generation of chromosomes * * * priva
Te chromosome getparentchromosome () {System.out.println ("4.1> Filter the parent population once ...");
while (true) {Double slice = math.random () * totalscore;
Double sum = 0;
for (chromosome chro:population) {sum + = Chro.getscore ();
System.out.println ("Test: sum=" +sum+ "chro.getscore () =" +chro.getscore ());
if (Sum > Slice && chro.getscore () >= averagescore) {return chro;
/** * @Description: Calculating Population Adaptability * * private void Cacultescore () {System.out.println ("2> Compute population Fitness ...");
Bestscore= (double) population.get (0). Getscore ();
Worstscore= (double) population.get (0). Getscore ();
Totalscore = 0;
for (chromosome chro:population) {setchromosomescore (CHRO);
if (Chro.getscore () > Bestscore) {//Set the best genetic value Bestscore = Chro.getscore ();
if (Y < Bestscore) {x = Changex (CHRO);
y = Bestscore;
Genei = generation; } if (Chro.getscore () < Worstscore) {//Set the worst genetic value Worstscore = CHRO.GETSC
Ore ();
} Totalscore + = Chro.getscore ();
} Averagescore = Totalscore/popsize; Because the precision problem results in an average greater than the best value, set the average to best value Averagescore = averagescore > Bestscore?
Bestscore:averagescore;
/** * Gene mutation * * private void mutation () {SYSTEM.OUT.PRINTLN ("5> gene mutation ..."); for (chromosome chro:population) {if (Math.random () < Mutationrate) {//gene mutation int m
Utationnum = (int) (Math.random () * maxmutationnum);
Chro.mutation (Mutationnum); }}/** * @param chro * @Description: Calculate and set chromosome fitness/private void Setchro
Mosomescore (chromosome chro) {if (chro = = null) {return;
int x = Changex (CHRO);