Reference: http://blog.csdn.net/b2b160/article/details/4680853/#comments (take the liberty of using a few pictures under the link)
Baidu Encyclopedia: Http://baike.baidu.com/link?url=FcwTBx_ Ypcd5ddenn1fqvtkg4qnllkb7yis6qfol65wpn6edt5lxfxucmv4jlufv3luphqgdybgj8khvs3guak
Algorithm Introduction
Genetic algorithm is a computational model to simulate the natural selection of Darwinian evolution and the mechanism of genetic evolution. Applied to the biology of "survival of the fittest, the fittest" principle. In each evolutionary process, the genes with better environmental adaptability are passed on to the next generation, until the last individual satisfies certain conditions, representing the end of evolution, and GA (which is referred to as GA as the genetic algorithm) is an algorithm to search for the optimal solution using the theory of biological evolution.
algorithm principleBasic framework of the algorithm
Understanding the basic framework of the algorithm is the basis of understanding the whole algorithm, the framework of the algorithm includes coding, fitness function, initial group selection. First assume that the objective function of this example is as follows, to find out his maximum value
f (x) = x1 * x1 + x2 * x2; 1<= X1 <=7, 1<= x2<=7
1, the fitness function. The fitness function is used to calculate the individual's adaptive value calculation, as the name implies, the higher the adaptive value of the individual, the better the environmental adaptability, nature will have more opportunities to pass their own genes to the next generation, so, in fact, the fitness function here plays a role of filtering. in this example, the objective function is always non-negative, and the function is maximized to optimize the target, so the value of the function can be used as an adaptive value.
2, encoding. Encoding refers to the representation of an individual's information as a coded string. If the individual variable is in the form of a number, it can be converted into binary mode.
the group selection process of the algorithm
This process is the core process of the genetic algorithm, which is divided into 3 small steps, selection, crossover, mutation.
1, the initial individual selection process. is to choose which individuals will be the next generation of individuals. The process is as follows:
(1). Use the fitness function to calculate the fitness of each individual and calculate the percentage of each individual's fitness total.
(2). Each individual is assigned a certain range according to the percentage.
(3). produce a decimal number [0, 1] to determine which individual's interval the decimal point falls within, indicating that the individual is to be selected. Here in fact already contains the high fitness of the individual priority into the next generation, because fitness high, there is a higher probability that the decimal is falling within their own range.
The form shown in the illustration is as follows:
2, cross operation. The step details of the individual's cross-operation process are as follows:
(1). Start with a random 22 pair for the individual selected by the previous selection step.
(2). Take out a pair of pairs of individuals, randomly set a crossover point, 2 individuals encoded after the intersection of the encoded value is swapped, generating a new 2 individual code.
(3). All paired individuals perform step (2) Actions and finally add to a result set.
There are many ways to cross the operation, the above method is one of the more common single-point intersection.
The form shown in the illustration is as follows:
3. Mutation operation. The procedure details of the mutation operation are as follows:
(1). Iterate through the result set of the result of the cross operation, take out the set of individual codes, prepare for mutation operation
(2). Generates a random mutation point position. The value of the location of the mutation point of the selected individual does a mutation operation, taking his value as a reverse value.
(3). Perform step (2) operations on all elements in the result set of the cross operation.
The form of illustration is as follows:
The whole genetic algorithm of the principle process, with a flowchart of the following form of expression:
Algorithm Code Implementation
The test case of the algorithm code is the same as the principle of the algorithm, the threshold condition of the genetic evolution is: the individual has the maximization value of the objective function, the gene is 111111.
Gatool.java:
Package Ga;import java.util.arraylist;import java.util.random;/** * Genetic Algorithm Tool class * * @author Lyq * */public class Gatool {// Variable min private int minnum;//variable maximum private int maxnum;//number of encoded bits of a single variable private int codenum;//The quantity of the initial population private int initsetsnum;//random Number generator private Random random;//initial group private arraylist<int[]> initsets;public gatool (int minnum, int maxnum, int initse Tsnum) {this.minnum = Minnum;this.maxnum = Maxnum;this.initsetsnum = Initsetsnum;this.random = new Random (); Produceinitsets ();} /** * Generate initialization Group */private void Produceinitsets () {this.codenum = 0;int num = maxnum;int[] array;initsets = new arraylist< > ();//Determine the number of encoded digits while (num! = 0) {codenum++;num/= 2;} for (int i = 0; i < Initsetsnum; i++) {array = Produceinitcode (); Initsets.add (array);}} /** * Generates code for the initial individual * * @return */private int[] Produceinitcode () {int num = 0;int num2 = 0;int[] temparray;int[] array1;int[ ] Array2;temparray = new int[2 * Codenum];array1 = new Int[codenum];array2 = new Int[codenum];num = 0;while (num < miNnum | | num > maxnum) {num = Random.nextint (maxnum) + 1;} Numtobinaryarray (array1, num); while (Num2 < Minnum | | num2 > Maxnum) {num2 = Random.nextint (maxnum) + 1;} Numtobinaryarray (Array2, num2);//composition total encoding for (int i = 0, k = 0; i < temparray.length; i++, k++) {if (K < codenum) {Te Mparray[i] = array1[k];} else {Temparray[i] = Array2[k-codenum];}} return temparray;} /** * Select the operation, the fitness higher individual priority to inherit to the next generation * * @param initcodes * Initial individual code * @return */private arraylist<int[]> Selectope Rate (arraylist<int[]> initcodes) {Double Randomnum = 0;double Sumadaptivevalue = 0; arraylist<int[]> resultcodes = new arraylist<> ();d ouble[] Adaptivevalue = new Double[initsetsnum];for (int i = 0; i < Initsetsnum; i++) {Adaptivevalue[i] = Calcodeadaptivevalue (Initcodes.get (i)); Sumadaptivevalue + = Adaptivevalue[i];} Turn into the form of probability, do a normalization operation for (int i = 0; i < Initsetsnum; i++) {adaptivevalue[i] = adaptivevalue[i]/sumadaptivevalue;} for (int i = 0; i < Initsetsnum; i++) {RandoMnum = Random.nextint (+) + 1;randomnum = Randomnum/100;sumadaptivevalue = 0;//determines the interval for (int j = 0; j < Initsetsnum; J + +) {if (Randomnum > sumadaptivevalue&& randomnum <= sumadaptivevalue + adaptivevalue[j]) {//Use Copy to avoid reference heavy Complex Resultcodes.add (Initcodes.get (j). Clone ()); else {sumadaptivevalue + = Adaptivevalue[j];}}} return resultcodes;} /** * Cross Operation * * @param selectedcodes * The selected code on the previous step * @return */private arraylist<int[]> crossoperate (Array List<int[]> selectedcodes) {int randomnum = 0;//intersection int crosspoint = 0; arraylist<int[]> resultcodes = new arraylist<> ();//random-coded queue for random cross-pairing arraylist<int[]> Randomcodeseqs = new arraylist<> ();//random sort while (selectedcodes.size () > 0) {randomnum = Random.nextint (Selectedcodes.size () ); Randomcodeseqs.add (Selectedcodes.get (Randomnum)); Selectedcodes.remove (randomnum);} int temp = 0;int[] array1;int[] array2;//22 crossover operation for (int i = 1; i < randomcodeseqs.size (); i++) {if (i% 2 = = 1) {ARRay1 = Randomcodeseqs.get (i-1); array2 = Randomcodeseqs.get (i); crosspoint = Random.nextint (2 * codeNum-1) + 1;//cross-point Reset the encoded exchange for (int j = 0; J < 2 * Codenum; j + +) {if (J >= crosspoint) {temp = Array1[j];array1[j] = Array2[j];array2[j] = temp;}} Added to the result of the crossover operation Resultcodes.add (Array1); Resultcodes.add (array2);}} return resultcodes;} /** * Mutation Operation * * @param crosscodes * Results after crossover operation * @return */private arraylist<int[]> variationoperate (arrayl Ist<int[]> crosscodes) {//mutation point int variationpoint = 0; arraylist<int[]> resultcodes = new arraylist<> (); for (int[] array:crosscodes) {variationpoint = Random.next Int (Codenum * 2); for (int i = 0; i < Array.Length; i++) {//Mutation point mutation if (i = = Variationpoint) {Array[i] = (array[i] = = 0 ? 1:0); break;}} Resultcodes.add (array);} return resultcodes;} /** * numbers into binary form * * @param binaryarray * converted binary array form * @param num * To convert digital */private void Numtobinar Yarray (int[] binaryarray, int num) {int index = 0;int teMP = 0;while (num! = 0) {binaryarray[index] = num% 2;index++;num/= 2;} Swap the front and rear of the array for (int i=0; i<binaryarray.length/2; i++) {temp = Binaryarray[i];binaryarray[i] = binaryarray[ Binaryarray.length-1-i];binaryarray[binaryarray.length-1-i] = temp;}} /** * Binary array converted to numbers * * @param binaryarray * binary array to convert */private int binaryarraytonum (int[] binaryarray) {int ResU lt = 0;for (int i = binaryarray.length-1, k=0; i >=0; I--, k++) {if (binaryarray[i] = = 1) {result + = Math.pow (2, k);} }return result;} /** * Calculate individual encoded fitness * * @param codearray */private int calcodeadaptivevalue (int[] codearray) {int result = 0;int X1 = 0;int x 2 = 0;int[] Array1 = new int[codenum];int[] array2 = new Int[codenum];for (int i = 0, k = 0; i < codearray.length; i++, k++) {if (K < codenum) {Array1[k] = codearray[i];} else {array2[k-codenum] = Codearray[i];}} Fitness Overlay x1 = Binaryarraytonum (array1); x2 = Binaryarraytonum (array2); result = x1 * x1 + x2 * x2;return result;} /** * Genetic algorithm to calculate */public voidGeneticcal () {//MAX fitness int maxfitness;//iteration inheritance number int loopcount = 0;boolean Canexit = false; Arraylist<int[]> Initcodes; Arraylist<int[]> Selectedcodes; Arraylist<int[]> Crossedcodes; Arraylist<int[]> variationcodes;int[] Maxcode = new int[2*codenum];//calculates the maximum fitness for (int i=0; i<2*codenum; i++) { Maxcode[i] = 1;} maxfitness = Calcodeadaptivevalue (maxcode); initcodes = Initsets;while (True) {for (int[] array:initcodes) {//the termination condition of the genetic iteration is The presence encoding reaches the maximum fitness if (maxfitness = = Calcodeadaptivevalue (array)) {canexit = True;break;}} if (canexit) {break;} Selectedcodes = Selectoperate (initcodes); crossedcodes = Crossoperate (selectedcodes); variationcodes = Variationoperate (crossedcodes); initcodes = variationcodes;loopcount++;} SYSTEM.OUT.PRINTLN ("Total genetics evolved" + Loopcount + "Times");p Rintfinalcodes (initcodes);} /** * Output FINAL encoding set * * @param finalcodes * Final result encoding */private void Printfinalcodes (arraylist<int[]> finalcode s) {int j = 0;for (int[] array:finalcodes) {System.out.print ("individual" + (j + 1) + ":"); for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]);} System.out.println (); j + +;}}}
The algorithm calls the class Client.java:
Package ga;/** * Genetic Genetic algorithm test class * @author Lyq * */public class Client {public static void main (string[] args) {//variable min and max I NT Minnum = 1;int Maxnum = 7;//initial population size int initsetsnum = 4; Gatool tool = new Gatool (Minnum, Maxnum, Initsetsnum); tool.geneticcal ();}}
The output of the algorithm multiple tests:
Test 1:
Total genetics has evolved 0 times individuals 1:111,001 individuals 2:101,010 individuals 3:101,110 individuals 4:111,111
Test 2:
Total genetics has evolved 1 times individuals 1:101,101 individuals 2:111,111 individuals 3:100,111 individuals 4:100,111
Test 3:
Total genetics has evolved 14 times individuals 1:110,101 individuals 2:111,111 individuals 3:110,101 individuals 4:110,011
algorithm Result AnalysisIt can be seen that the number of cycles of genetic evolution is still uncertain, because the number of individual tests is too small, if the number of individuals is more, a few rounds can appear 111111 such an individual coding group. From the results can be seen, the total is still able to more than 1 of the direction of development.
tell me about my understanding of genetic algorithms.
Through the implementation of GA algorithm, feel that this is a bit of integration of the taste of the algorithm, because this actually used the knowledge of the interdisciplinary, with the knowledge of biological evolution theory, as a search solution of the optimal solution, and the algorithm itself is not particularly difficult to understand and implement.
Genetic algorithm Genetic Algorithm learning