On the detailed principles of genetic algorithms and specific definitions here is not much to introduce, want to understand the Baidu, the following is a simple introduction of their own understanding of genetic algorithms, this article on the encoding of genes using the binary rules.
Algorithm idea:
Genetic algorithm According to Darwin's theory of evolution, that species are in a good direction to develop (survival of the fittest), so it can be considered enough algebra, the maximum can be the actual maximum value is very close.
Algorithm steps:
- 1) randomly generating a population;
- 2 to calculate the population adaptability, the best adaptability, the worst fitness, the average fitness and other indicators;
- 3) To verify whether the population algebra to achieve its own set threshold, if the end of the calculation, otherwise continue to the next step calculation;
- 4 the generation of the offspring can be selected by the turntable gambling method, and the next generation population (the number of individuals in the population will not change) will be generated.
- 5) Genetic mutation occurred in population;
- 6) Repeat 2, 3, 4, 5 steps.
Algorithm implementation-Gene part
1, the population (here is considered a chromosome), in the individual, we add two attributes for this individual, the individual gene and gene corresponding to the fitness (function value).
public class Chromosome {
private boolean[] gene;//gene sequence
private double score;//corresponding function score
}
2, randomly generated gene sequence, each gene location is 0 or 1, here in a completely random way to achieve.
Public chromosome (int size) {
if (size <= 0) {return
;
}
Initgenesize (size);
for (int i = 0; i < size; i++) {
Gene[i] = math.random () >= 0.5;
}
}
private void initgenesize (int size) {
if (size <= 0) {return
;
}
Gene = new boolean[size];
}
3, the gene into the corresponding value, such as 101 corresponding to the number is 5, where the use of bitwise operations to achieve.
public int Getnum () {
if (gene = = null) {return
0;
}
int num = 0;
For (Boolean bool:gene) {
num <<= 1;
if (bool) {
num = 1;
}
}
return num;
}
4, genetic mutation, for the location of the mutation is completely random way to achieve, the principle of variation from 1 to 0, 0 into 1.
public void mutation (int num) {
//allow variant
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;
}
}
5, cloning genes, used to produce the next generation, this step is the existing gene copy a copy.
public static chromosome clone (final chromosome c) {
if (c = null | | | 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;
}
6, both parents produce the next generation, here two individual generation two individual offspring, concrete which section of gene poor crossover, completely random.
public static list<chromosome> genetic (chromosome P1, chromosome p2) {if (P1 = = NULL | |
P2 = = null) {//chromosome has one is empty, does not produce 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;
Crossover for the gene in position for (int i = min; I <= max; i++) {Boolean 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; }
Algorithm implementation-Genetic algorithm
1, for genetic algorithms, we need to have a corresponding population and we need to set some constants: population number, gene length, gene mutation number, gene mutation rate, etc., specific reference to the following code:
Public abstract class Geneticalgorithm {
private list<chromosome> population = new Arraylist<chromosome > ()//Population
private int popsize = 100;//population number
private int genesize;//gene Max length
private int maxiternum = 500;// Maximum number of iterations
private double mutationrate = probability of 0.01;//gene mutation
private int maxmutationnum = 3;//Max mutation step
private int Generation = 1;//Current heredity to the first few generations of
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 a historical population
private Double y; Record the best Y value of a historical population.
private int genei;//x y algebra
}
2, initializing the population, when the genetic algorithm begins, we need to initialize a primitive population, this is the original first generation.
private void Init () {for
(int i = 0; i < popsize; i++) {
population = new arraylist<chromosome> ();
Chromosome chro = new chromosome (genesize);
Population.add (CHRO);
}
Cacultescore ();
}
3, after the initial population exists, we need to calculate the population adaptability and the best adaptability, the worst fitness and the average fitness.
private void Cacultescore () {
setchromosomescore (population.get (0));
Bestscore = Population.get (0). Getscore ();
Worstscore = 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.getscore ();
}
Totalscore + + chro.getscore ();
}
Averagescore = totalscore/popsize;
Because the accuracy problem results in an average greater than the best value, set the average to best value
Averagescore = averagescore > Bestscore? bestscore:averagescore;
}
4, in the calculation of individual fitness, we need to calculate the corresponding Y-value according to the gene, here we set two abstract methods, concrete implementation by the implementation of the class.
private void Setchromosomescore (chromosome chro) {
if (chro = = null) {return
;
}
Double x = Changex (chro);
Double y = caculatey (x);
Chro.setscore (y);
}
/**
* @param chro *
@return
* @Description: Converts the binary to the corresponding X/public
abstract double Changex ( Chromosome chro);
/**
* @param x
* @return
* @Description: X calculates Y-value y=f (x)/public
abstract double Caculatey ( Double x);
5, after the calculation of population fitness, we need to use the turntable betting method to select the next generation of individuals, there is a condition that only the individual's fitness is not less than the average fitness will be immortal next generation (survival of the fittest).
Private chromosome Getparentchromosome () {
Double slice = math.random () * Totalscore;
Double sum = 0;
for (chromosome chro:population) {
sum + = Chro.getscore ();
Go to the corresponding position and the fitness is not less than the average fitness
if (Sum > Slice && chro.getscore () >= averagescore) {return
chro;
}
}
return null;
}
6. After choosing the individual who can produce the next generation, it is necessary to mate to produce the next generation.
private void Evolve () {
list<chromosome> childpopulation = new arraylist<chromosome> ();
Generate next-generation population while
(Childpopulation.size () < popsize) {
chromosome p1 = Getparentchromosome ();
Chromosome P2 = getparentchromosome ();
list<chromosome> children = Chromosome.genetic (P1, p2);
if (children!= null) {for
(chromosome chro:children) {
childpopulation.add (chro);
}}} New population replaces old population
list<chromosome> t = population;
Population = childpopulation;
T.clear ();
t = null;
Gene mutation
mutation ();
To calculate the adaptability of new population
Cacultescore ();
}
7. In the process of producing the next generation, genetic variation may occur.
private void mutation () {for
(chromosome chro:population) {
if (Math.random () < Mutationrate) {//Gene mutation
int mutationnum = (int) (Math.random () * maxmutationnum);
Chro.mutation (Mutationnum);}}
8. Repeat the above steps from generation to generation.
public void Caculte () {
//initialized population
generation = 1;
Init ();
while (Generation < Maxiternum) {
//Population genetic
evolve ();
Print ();
generation++
}
}
Writing implementation Classes
Since the class of the above genetic algorithm is an abstract class, we need to write the implementation class for a particular case, assuming we calculate the Y=100-log (X) value on [6,106].
1, we assume that the length of the gene is 24 (the length of the gene is determined by the effective length of the required result), so the corresponding binary maximum is 1<< 24, we do the following setting
public class Geneticalgorithmtest extends geneticalgorithm{public
static final int NUM = 1 <<;
Public Geneticalgorithmtest () {
super;
}
}
2, the X value of the abstract method to achieve
@Override public
Double Changex (chromosome chro) {
//TODO auto-generated a stub return
(1.0 * chro.ge Tnum ()/NUM) + 6;
}
3. To implement the abstract method of Y
@Override public
Double Caculatey (double x) {
//TODO auto-generated a stub return
100-math.log (x);
}
Run results
The thinking of genetic algorithm
I have seen a lot of genetic algorithms introduced, the above mentioned optimal solution is the last generation of the most value, I have a question, why I know all the previous band in the highest value, that is, the program x Y value, why not use X Y value to do the final result of genetic algorithm?
Complete code
1, Chromosome class
/** * @Description: Gene genetic chromosome/package com.lulei.genetic.algorithm;
Import java.util.ArrayList;
Import java.util.List; public class Chromosome {private boolean[] gene;//gene sequence private double score;//corresponding function score public double Getscore
() {return score;
The public void SetScore (double score) {This.score = score; /** * @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; }/** * Generates a new gene */public chromosome () {}/** * @param c * @return *
@Description: Cloning gene */public static chromosome clone (final chromosome C) {if (c = NULL | | 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<CHROMOSOME&G T
Genetic (chromosome P1, chromosome p2) {if (P1 = null | | p2 = NULL) {//chromosome has one is empty, does not produce 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 the gene in position foR (int i = min; I <= max; i++) {Boolean 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: Mutations in the location of the gene NUM/public void mutation (int num) {//Allow mutation
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;
}
}
2, Geneticalgorithm class
/** * @Description: * * Package com.lulei.genetic.algorithm;
Import java.util.ArrayList;
Import java.util.List;
Public abstract class Geneticalgorithm {private list<chromosome> population = new arraylist<chromosome> (); private int popsize = 100;//population number private int genesize;//gene max length private int maxiternum = 500;//maximum Iteration number private Double mutationrate = probability of 0.01;//gene mutation private int maxmutationnum = 3;//Max mutation step private int generation = 1;//Current heredity to cap Several generations of private double bestscore;//best score private double worstscore;//The worst score private double totalscore;//total score Privat E 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 a historical population private int genei;//x y is the algebra public geneticalgorithm (int genesize) {this.genesize = Genesize
;
public void Caculte () {//initialized population generation = 1;
Init ();
while (Generation < Maxiternum) {//Population genetic evolve (); PriNT ();
generation++; }/** * @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);
/** * @Description: Initialize the population */private void init () {for (int i = 0; i < popsize; i++) {
Population = new arraylist<chromosome> ();
Chromosome chro = new chromosome (genesize);
Population.add (CHRO);
} cacultescore (); /** * @Author: Lulei * @Description: Population for genetic/private void evolve () {list<chromosome> Childpopulation = new Arraylist<chromosoMe> ();
Generate next-generation population while (Childpopulation.size () < popsize) {chromosome P1 = Getparentchromosome ();
Chromosome P2 = getparentchromosome ();
list<chromosome> children = Chromosome.genetic (P1, p2);
if (children!= null) {for (chromosome Chro:children) {childpopulation.add (CHRO);
}}//New population replaces old population list<chromosome> t = population;
Population = childpopulation;
T.clear ();
t = null;
Gene mutation mutation ();
To calculate the adaptability of new population cacultescore ();
/** * @return * @Description: Roulette option can be inherited from the next generation of chromosomes * * Private chromosome getparentchromosome () {
Double slice = math.random () * totalscore;
Double sum = 0;
for (chromosome chro:population) {sum + = Chro.getscore ();
if (Sum > Slice && chro.getscore () >= averagescore) {return chro;
} return null; }/** * @DescriptioN: Calculation of population fitness/private void Cacultescore () {setchromosomescore (population.get (0));
Bestscore = Population.get (0). Getscore ();
Worstscore = 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.getscore ();
} 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 () {for (chromosome chro:population) {if Math.rand Om () < mutationrate) {//occurrence of gene mutation int mutatIonnum = (int) (Math.random () * maxmutationnum);
Chro.mutation (Mutationnum); }}/** * @param chro * @Description: Set chromosome score/private void Setchromosomescore (Chromosom
E chro) {if (chro = = null) {return;
Double x = Changex (CHRO);
Double y = caculatey (x);
Chro.setscore (y); /** * @param chro * @return * @Description: Converts the binary to the corresponding X/public abstract double Changex (chro
Mosome chro);
/** * @param x * @return * @Description: Calculate Y value based on x y=f (x)/public abstract double Caculatey (double x);
public void Setpopulation (list<chromosome> population) {this.population = population;
The public void setpopsize (int popsize) {this.popsize = popsize;
The public void setgenesize (int genesize) {this.genesize = genesize;
The public void setmaxiternum (int maxiternum) {this.maxiternum = Maxiternum; } public VoiD setmutationrate (double mutationrate) {this.mutationrate = mutationrate;
The public void setmaxmutationnum (int maxmutationnum) {this.maxmutationnum = Maxmutationnum;
Public double Getbestscore () {return bestscore;
Public double Getworstscore () {return worstscore;
Public double Gettotalscore () {return totalscore;
Public double Getaveragescore () {return averagescore;
Public double GetX () {return x;
Public double GetY () {return y;
}
}
3, Geneticalgorithmtest class
/**
* @Description: * *
package com.lulei.genetic.algorithm;
public class Geneticalgorithmtest extends geneticalgorithm{public
static final int NUM = 1 <<;
Public Geneticalgorithmtest () {
super;
}
@Override public
Double Changex (chromosome chro) {
//TODO auto-generated a stub return
(1.0 * chro. Getnum ()/NUM) + 6;
}
@Override public
Double Caculatey (double x) {
//TODO auto-generated a stub return
100-math.log (x);
}
public static void Main (string[] args) {
geneticalgorithmtest test = new Geneticalgorithmtest ();
Test.caculte ();
}
The above is a detailed introduction of Java genetic algorithm, I hope that we learn Java genetic algorithm to help.