JAVA-based Genetic Algorithm

Source: Internet
Author: User

JAVA-based Genetic Algorithm

The detailed principles and specific definitions of genetic algorithms are not described here. If you want to know more about them, you can use Baidu. Below we will briefly introduce your understanding of genetic algorithms, this article uses binary rules for gene encoding.

 

Algorithm idea:

According to Darwin's evolution, genetic algorithms consider that species develop in a positive direction (Survival of the fittest). Therefore, we can think that after enough algebra, the greatest value obtained is very close to the actual value.

 

Algorithm steps:

1)Generate a random population;
2)Calculate the population fitness, best fitness, worst fitness, average fitness, and other indicators;
3)Check whether the population Algebra has reached its own threshold. If the population algebra reaches the end of the calculation, otherwise proceed to the next calculation;
4)The turntable gambling method can be used to generate the next generation of parent generation and generate the next generation of population (the number of individuals in the population remains unchanged );
5)Population Genetic Mutation;
6)Repeat steps 2, 3, 4, and 5.

 

Algorithm Implementation-genetics

1. Individual populations(This is considered as a chromosome). In an individual, we add two attributes for this individual. the fitness of the individual's genes and genes (function value ).

 

Public class Chromosome {private boolean [] gene; // gene sequence private double score; // corresponding function score}

 

 

2. Generate a random gene sequenceThe position of each gene is 0 or 1, which is completely random.
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. Convert genes into corresponding values.For example, if the number corresponding to 101 is 5, bitwise operations are used here.

 

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 VariationFor the location of the variation, the random method is adopted here. The variation principle is changed from 1 to 0 to 1.

 

 

Public void mutation (int num) {// allowed variant int size = gene. length; for (int I = 0; I <num; I ++) {// find the variant position int at = (int) (Math. random () * size) % size; // The variant value boolean bool =! Gene [at]; gene [at] = bool ;}}

5. Clone Genes,This step is to copy existing genes to generate the next generation.

 

 

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 generate the next generationThe two individuals generate two child generations. The specific genetic difference crossover is completely random.

 

 

Public static List
 
  
Genetic (Chromosome p1, Chromosome p2) {if (p1 = null | p2 = null) {// One of the chromosomes is null and no next generation return null is generated ;} if (p1.gene = null | p2.gene = null) {// There is no gene sequence on the chromosome and no next-generation return null is generated;} if (p1.gene. length! = P2.gene. length) {// The length of the Chromosome gene sequence is different, and the next generation return null is not generated;} Chromosome c1 = clone (p1); Chromosome c2 = clone (p2 ); // generate random cross-swapping 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; // perform crossover for (int I = min; I <= max; I ++) {boolean t = c1.gene [I]; c1.gene [I] = c2.gene [I]; c2.gene [I] = t;} List
  
   
List = new ArrayList
   
    
(); List. add (c1); list. add (c2); return list ;}
   
  
 

 

 


Algorithm Implementation-Genetic Algorithm

1,For genetic algorithms, we need the corresponding population and our needs.SetSomeConstant: The population quantity, gene length, gene mutation count, gene mutation rate, and so on. The specific code is as follows:

 

Public abstract class GeneticAlgorithm {private List
 
  
Population = new ArrayList
  
   
(); // Population private int popSize = 100; // population quantity private int geneSize; // Maximum length of the gene private int maxIterNum = 500; // maximum iterations private double mutationRate = 0.01; // probability of genetic variation private int maxMutationNum = 3; // maximum variation step private int generation = 1; // The current generation of private double bestScore; // the best score is private double worstScore; // The worst score is private double totalScore; // The total score is private double averageScore; // average private double x; // the best private double y value in the History population; // The best Y value in the History population: private int geneI; // algebra where x y is located}
  
 

2. initialize the populationAt the beginning of the genetic algorithm, we need to initialize an original population, which is the first generation of the original population.

 

 

private void init() {for (int i = 0; i < popSize; i++) {population = new ArrayList
 
  ();Chromosome chro = new Chromosome(geneSize);population.add(chro);}caculteScore();}
 

3,After the initial population exists, we need to calculate Population fitnessAnd the best fitness, 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 () <worstSco Re) {// set the worst Gene value worstScore = chro. getScore ();} totalScore + = chro. getScore () ;}averagescore = totalScore/popSize; // if the average value is greater than the best value due to precision problems, set the average value to the best value: averageScore = averageScore> bestScore? BestScore: averageScore ;}

4,When calculating individual fitness, we need Calculate the corresponding Y valueHere we set two abstract methods to implement them by class implementation.

 

 

Private void setChromosomeScore (Chromosome chro) {if (chro = null) {return;} double x = changeX (chro); double y = caculateY (x); chro. setScore (y);}/*** @ param chro * @ return * @ Author: lulei * @ Description: convert the binary data to the corresponding X */public abstract double changeX (Chromosome chro);/*** @ param x * @ return * @ Author: lulei * @ Description: calculate Y = F (X) */public abstract double caculateY (double X) based on x );

5,After calculating the population fitness, we need to use Turntable gamblingSelect Yes Generation of next generation individualsHere, there is a condition that only individuals whose fitness is not smaller than the average fitness will survive the next generation (Survival of the fittest ).

 

 

Private Chromosome getParentChromosome () {double slice = Math. random () * totalScore; double sum = 0; for (Chromosome chro: population) {sum + = chro. getScore (); // jump 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,Mating is required when you select an individual that can generate the next generation. Generate Next Generation.

 

 

Private void evolve () {List
 
  
ChildPopulation = new ArrayList
  
   
(); // Generate the next generation of population while (childPopulation. size () <popSize) {Chromosome p1 = getParentChromosome (); Chromosome p2 = getParentChromosome (); List
   
    
Children = Chromosome. genetic (p1, p2); if (children! = Null) {for (Chromosome chro: children) {childPopulation. add (chro) ;}}// replace the old population List with the new population
    
     
T = population; population = childPopulation; t. clear (); t = null; // mutation (); // calculate the adaptability of the new population to caculteScore ();}
    
   
  
 

7,The next generation may occur. Genetic Variation.

 

 

Private void mutation () {for (Chromosome chro: population) {if (Math. random () <mutationRate) {// occurrence of a genetic mutation int mutationNum = (int) (Math. random () * maxMutationNum); chro. mutation (mutationNum );}}}

8,Add the preceding steps Repeated execution from generation to generation.

 

 

Public void caculte () {// initialize population generation = 1; init (); while (generation <maxIterNum) {// population genetics evolve (); print (); generation ++ ;}}


 

Write implementation class

Because the class of the above genetic algorithm is an abstract class, we need to write the implementation class for specific cases. Suppose we calculate the maximum value of Y = 100-log (X) on [6,106.

 

1,Let's assume thatGene lengthIs 24 (the length of the gene is determined by the valid length of the required results), so the maximum binary value is 1 <24, we make the following settings

 

public class GeneticAlgorithmTest extends GeneticAlgorithm{public static final int NUM = 1 << 24;public GeneticAlgorithmTest() {super(24);  }}

2. Implement the abstract method of X value

 

 

@Overridepublic double changeX(Chromosome chro) {// TODO Auto-generated method stub  return ((1.0 * chro.getNum() / NUM) * 100) + 6;}

3. Implement the abstract method of Y

 

 

@Overridepublic double caculateY(double x) {// TODO Auto-generated method stub  return 100 - Math.log(x);}


 

Running result

 

Genetic algorithm thinking

I have read a lot of Introduction to genetic algorithms. The optimal solution mentioned above is the best value of the last generation. I have a question. Why do I know the best value of all the above bands, that is, the x y value in the program. Why cannot we use x y as the final result value of the genetic algorithm?

 

Complete code

1. Chromosome class

 

/*** @ Description: genetics 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 ;} 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 * @ Author: lulei * @ Description: clone 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 * @ Author: lulei * @ Description: Initialize the gene length */private void initGeneSize (int size) {if (size <= 0) {return;} gene = new boolean [size];}/*** @ param c1 * @ param c2 * @ Author: lulei * @ Description: generate the Next Generation. */public static List
 
  
Genetic (Chromosome p1, Chromosome p2) {if (p1 = null | p2 = null) {// One of the chromosomes is null and no next generation return null is generated ;} if (p1.gene = null | p2.gene = null) {// There is no gene sequence on the chromosome and no next-generation return null is generated;} if (p1.gene. length! = P2.gene. length) {// The length of the Chromosome gene sequence is different, and the next generation return null is not generated;} Chromosome c1 = clone (p1); Chromosome c2 = clone (p2 ); // generate random cross-swapping 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; // perform crossover for (int I = min; I <= max; I ++) {boolean t = c1.gene [I]; c1.gene [I] = c2.gene [I]; c2.gene [I] = t;} List
  
   
List = new ArrayList
   
    
(); List. add (c1); list. add (c2); return list;}/*** @ param num * @ Author: lulei * @ Description: Variation in gene num position */public void mutation (int num) {// allowed variant int size = gene. length; for (int I = 0; I <num; I ++) {// find the variant position int at = (int) (Math. random () * size) % size; // The variant value boolean bool =! Gene [at]; gene [at] = bool;}/*** @ return * @ Author: lulei * @ Description: convert 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
 
  
Population = new ArrayList
  
   
(); Private int popSize = 100; // population quantity private int geneSize; // Maximum length of the gene private int maxIterNum = 500; // maximum number of iterations private double mutationRate = 0.01; // probability of genetic variation private int maxMutationNum = 3; // maximum Variant Step private int generation = 1; // the current generation of private double bestScore; // The best score is private double worstScore. // The worst score is private double totalScore. // The total score is private double averageScore. // The average score is private double x; // record the best X value in the Historical population private double y; // record the best Y value in the Historical population private int geneI; // The algebra where x y is located public GeneticAlgorithm (int geneSize) {this. geneSize = geneSize;} public void caculte () {// initialize population generation = 1; init (); while (generation <maxIterNum) {// population genetics evolve (); print (); generation ++;}/*** @ Author: lulei * @ Description: output result */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);}/*** @ Author: lulei * @ Description: initialize the population */private void init () {for (int I = 0; I <popSize; I ++) {population = new ArrayList
   
    
(); Chromosome chro = new Chromosome (geneSize); population. add (chro);} caculteScore ();}/*** @ Author: lulei * @ Description: Perform population genetics */private void evolve () {List
    
     
ChildPopulation = new ArrayList
     
      
(); // Generate the next generation of population while (childPopulation. size () <popSize) {Chromosome p1 = getParentChromosome (); Chromosome p2 = getParentChromosome (); List
      
        Children = Chromosome. genetic (p1, p2); if (children! = Null) {for (Chromosome chro: children) {childPopulation. add (chro) ;}}// replace the old population List with the new population
       
         T = population; population = childPopulation; t. clear (); t = null; // mutation (); // calculate the adaptability of the new population caculteScore ();}/*** @ return * @ Author: lulei * @ Description: The gambling method selects the next generation Chromosome that can be inherited */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 ;}} ret Urn null;}/*** @ Author: lulei * @ Description: calculates the 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 = best Score; geneI = generation ;}} if (chro. getScore () <worstScore) {// set the worst genetic value worstScore = chro. getScore ();} totalScore + = chro. getScore () ;}averagescore = totalScore/popSize; // if the average value is greater than the best value due to precision problems, set the average value to the best value: averageScore = averageScore> bestScore? BestScore: averageScore;}/*** genetic mutation */private void mutation () {for (Chromosome chro: population) {if (Math. random () <mutationRate) {// occurrence of a genetic mutation int mutationNum = (int) (Math. random () * maxMutationNum); chro. mutation (mutationNum) ;}}/ *** @ param chro * @ Author: lulei * @ Description: sets the Chromosome score */private void setChromosomeScore (Chromosome chro) {if (chro = null) {return;} double x = changeX (chro); double y = caculateY (x); chro. setScore (y);}/*** @ param chro * @ return * @ Author: lulei * @ Description: convert the binary data to the corresponding X */public abstract double changeX (Chromosome chro);/*** @ param x * @ return * @ Author: lulei * @ Description: calculate Y = F (X) */public abstract double caculateY (double X) based on x; public void setPopulation (List
        
          Population) {this. population = population;} public void setPopSize (int popSize) {this. popSize = popSize;} public void setGeneSize (int geneSize) {this. geneSize = geneSize;} public void setMaxIterNum (int maxIterNum) {this. maxIterNum = maxIterNum;} public void setMutationRate (double mutationRate) {this. mutationRate = mutationRate;} 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 << 24;public GeneticAlgorithmTest() {super(24);  }@Overridepublic double changeX(Chromosome chro) {// TODO Auto-generated method stub  return ((1.0 * chro.getNum() / NUM) * 100) + 6;}@Overridepublic double caculateY(double x) {// TODO Auto-generated method stub  return 100 - Math.log(x);}public static void main(String[] args) {GeneticAlgorithmTest test = new GeneticAlgorithmTest();test.caculte();}}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.