--javascript realization of __ garbled problem based on genetic algorithm for calculating function maximum value

Source: Internet
Author: User
Tags rand
Background KnowledgeEvolutionary algorithm (evolutionary algorithms,ea) is a search algorithm based on biological evolution mechanism, such as natural selection and natural heredity. Biological evolution is achieved through reproduction, mutation, competition and selection, while evolutionary algorithms are mainly through selection, reorganization and mutationThese three kinds of operation realize the solution of the optimization problem. Evolutionary algorithm is an "algorithm cluster", including genetic Algorithm (GA), genetic programming, evolutionary strategy and evolutionary planning. Basic Ideas

Practical Problems

Next I will solve the problem with the following diagram and combining the code.
I. Initialization of chromosome population

First, we define the structure of chromosomes. You can use the object in JS so that it has two properties, one attribute is the gene, one is the corresponding fitness function value of the gene.

        Define the structure of the chromosome
        var gene = {
            "genebit": Undefined,//Gene
            "fitvalue": undefined//The gene corresponds to the fitness function value
        }

Then, initialize the chromosomes. According to the title requirement, the integer between [0,30] is represented by a 5-bit binary encoding.

       var bit = 5; Number of loci
      //initialization chromosome
       function Createsingle () {
           var str = "";
           for (var i = 0; i < bit-1 i++) {
               if (math.random () < 0.5) {
                   str = "1";
               } else {str =
                   "0";
               }

           //Guaranteed number of generated in [0,30]
           if (str = = "1111") {
               str = 0;
           } else {
               if (math.random () < 0.5) {
  str + = "1";
               } else {
                   str + = "0";
               }
           }
           return str;
       }

Then, initialize the population.

        var popnum = 100; Number of chromosomes
        var Pop = new Array ();//Population
        //initialization population
        function Createpop () {for
            (var j = 0; J < Popnum) J + + {
                Pop[j] = new Object ();
                Pop[j].genebit = Createsingle ();
            }
        }
second, calculate the fitness function value of each individual

Before calculating the fitness, choose the appropriate fitness function. The fitness function has two characteristics of maximum and nonnegative. The greater the number of fitness functions, the greater the likelihood of their being chosen.
I used the R language curve (x*x*x-60*x*x+900*x+100,0,30) to draw the image of the function.

found that it satisfies the above conditions, so we choose the fitness function is: X * x * x-60 * x * x + 900 * x + 100
Of course, before the calculation of the fitness function value there is a decoding work, that is, binary conversion to decimal.

        Compute the fitness function value functions
        calfitvalue (x) {return
            x * x * x-60 * x * x + 900 * x +;
        }

        binary conversion to decimal (decoding)
        function Toten (x) {return
            x[0] * + x[1] * 8 + x[2] * 4 + x[3] * 2 + x[4] * 1;
        }

        Binary converts to decimal and calculates the fitness function value functions
        Totenandcalfitvalue () {for
            (var j = 0; J < Popnum; J + +) {
                var tenvalue = Toten (pop[j].genebit);
                Pop[j].fitvalue = Calfitvalue (Tenvalue);
            }
        }
Third, choose the intersection according to the fitness function value

The

embodies the natural state of the fittest. The
uses the Roulette method to choose. A roulette wheel is produced according to the individual's choice probability, and the angle of each area of the wheel is proportional to the individual's choice probability. Produces a random number, it falls into which area of the turntable to select the corresponding individual intersection. Meet the first number that is larger than him to fall into the corresponding area.

        Roulette Selection Method Function selection () {var totallfitvalue = 0;//Total fitness var Choicepro = NE W Array (Popnum); Each chromosome's fitness value corresponds to the probability var Sumchoicepro = new Array (popnum);
            Cumulative probability for (var j = 0; J < Popnum J + +) {Totallfitvalue = = Pop[j].fitvalue;
                for (var j = 0; J < Popnum; J + +) {Choicepro[j] = Pop[j].fitvalue/totallfitvalue;
                if (J!= 0) {Sumchoicepro[j] = Sumchoicepro[j-1] + choicepro[j];
                else {Sumchoicepro[j] = choicepro[j];
                for (var j = 0 J < Popnum-1; J + +) {var Rand = Math.random ();
                        for (var k = 0; k < Popnum-1; k++) {if (Rand <= sumchoicepro[k)) { Crossover (k, k + 1);
                    Select the chromosome to be crossed with his next break;
                }}
            }
        } 
Iv. CrossA point of intersection: randomly set an intersection in the individual string, the intersection, the point before or after the two individual parts of the structure of the exchange, and generate two new individuals. Two-point crossover: Randomly set two intersection points to exchange the code string between the two intersections. Uniform crossover: Some bits are extracted according to the uniform probability, and each bit is randomly selected and independent of the other bits. The two individuals are then replaced by the extracted bits to form two new individuals.
In the intersection of two points, attention should be paid to the modification of the crossover method.
        Cross (single point)
        function Crossover (x, y) {
            if (Math.random () < 0.6) {//mutation probability for 0.6
                var str1, str2, tem1 = 0,
                    te m2 = 0;
                var pos = Math.floor (Math.random () * bit);
                STR1 = pop[x].genebit.substring (POS);
                str2 = pop[y].genebit.substring (POS);
                Pop[x].genebit = pop[x].genebit.substring (0, POS) + str2;
                Pop[y].genebit = pop[y].genebit.substring (0, POS) + str1;

                To calculate the fitness value
                tem1 = Toten (pop[x].genebit) for the individual obtained after crossing;
                Pop[x].fitvalue = Calfitvalue (tem1);
                TEM2 = Toten (pop[y].genebit);
                Pop[y].fitvalue = Calfitvalue (TEM2);
            }
        }
v. Variation

Simulate mutations in heredity. Locus Variation: Individual code strings in a group, randomly selected one or more loci, and the genetic value of these loci varies by mutation probability.

        Variant
        function mutation () {
            for (var j = 0; J < Popnum; J + +) {
                if (Math.random () < 0.01) {//mutation probability is 0.01
  var pos = Math.floor (Math.random () * bit);
                    var tem = 0;
                    if (pop[j].genebit[pos] = = "1") {
                        Pop[j].genebit[pos] = "0";
                    } else {
                        Pop[j].genebit[pos] = "1";
                    }

                    The degree of fitness value
                    tem = Toten (pop[j].genebit) is calculated for the individual after mutation.
                    Pop[j].fitvalue = Calfitvalue (TEM);}}
        

Of course, you also need to record the maximum value after each iteration.

        Record maximum
        function Bestgene () {
            Bestvalue = 0, bestgenetenvalue = 0;
            for (var j = 0; J < Popnum J + +) {
                if (Pop[j].fitvalue > Bestvalue) {
                    bestvalue = Pop[j].fitvalue;
                    Bestgenetenvalue = Toten (pop[j].genebit);
                }}}
        

Demo can poke here to see

The above is also a personal learning in some understanding and practice, there are any mistakes, I hope everyone criticized correct.

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.