Genetic algorithm python version, genetic algorithm python

Source: Internet
Author: User

Genetic algorithm python version, genetic algorithm python

This article provides examples of the python genetic algorithm code for your reference. The specific content is as follows:

1. Basic Concepts

Genetic Algorithm (GA) is a smart search algorithm first proposed by Professor Holland of the United States based on the Basic Law of Nature "survival of the fittest, survival of the fittest. This rule is a good interpretation of the natural selection process of biological evolution. Genetic algorithms also use this Basic Law to convert the solution of a problem into an individual in a population by encoding based on the concept of population, and let these individuals constantly simulate the biological evolution process through selection, crossover and mutation operators, and then use the "survival of the fittest" rule to select the adaptive individuals in the population to form a subpopulation, then let the sub-population repeat similar evolutionary processes until they find the optimal solution of the problem or reach a certain evolutionary (operational) time.

Several important terms in the Ga algorithm.

Individual (chromosome): an individual (chromosome) in nature represents a creature. In the GA algorithm, individual (chromosome) represents a solution to a specific problem.

GENE: In the GA algorithm, genes represent a decision variable for the specific problem solution. The relationship between the problem solution and the gene in the chromosome is as follows:

Population: multiple individuals form a population. In the GA algorithm, multiple groups of solutions to a problem constitute the population of solutions to the problem.

2. Main Steps

The basic steps of the GA algorithm are as follows:

Step 1. initialize the population. Select an encoding scheme and initialize a certain number of individuals to form the population of GA in the solution space by means of random generation.

Step 2. Evaluate the population. The heuristic algorithm is used to generate a pattern chart for the individual in the population (the placement order of Rectangular Parts) and calculate the adaptive function value (utilization rate) of the individual based on the sample ), then, the optimal individual in the current population is saved as the optimal search result.

Step 3. Select an operation. Based on the fitness of the individual in the population, the high fitness individual is selected from the current population by means of round-robin or expectation method.

Step 4. Cross-operate. Use the probability threshold value Pc to control whether to use single-point crossover, multi-point crossover, or other crossover methods to generate a new crossover individual.

Step 5. Mutation operation. Use a certain probability threshold Pm to control whether single point of variation or multi-point variation is performed on some individual genes.

Step 6. Terminate judgment. If the condition for termination is met, the algorithm is terminated; otherwise, Step 2 is returned.

The flowchart is as follows:

3. Main Operations

3.1 population Initialization

Population Initialization is related to specific problems. For example, a problem occurs:NDecision variables {X1, x2 ,..., Xn}. Each decision variable has a value range: Lower Bound {L1, L2 ,..., Ln} And Upper Bound {U1, U2 ,..., Un}, Then the initialization of individual in the population randomly generates the values of each decision variable within the value range of the decision variable: Xj = {x1, x2 ,..., xn}, in which xi belongs to the range (Li, Ui. All individuals constitute a population. After each individual is initialized, the population is initialized.

3.2 rating population

Population evaluation is to calculate the fitness value of individual in the population. Hypothesis populationPopulationYesPopsizeIndividual. Calculate the fitness value of each individual and the evaluation population in sequence.

3.3 Select Operation

Common selection operations in the GA algorithm include the round-robin method: the higher the probability that an individual with a better fitness value in the population will be selected. Assuming popsize = 4, calculate the size of the selected probability of each individual according to the following expression, and then use a pie chart to represent the following.

P (Xj) = fit (Xj)/(fit (X1) + fit (X2) + fit (X3) + fit (X4), j = 1, 2, 3, 4

When selected based on the way of gambling, the higher the probability, the more likely to be selected.

3.4 cross operations

There are also many types of cross operations: Single Point Crossover and two point crossover. Here, we will only explain the intersection of two points. First, we use the selection operation to select parent1 and parent2 from the population, and then randomly generate two pos1 and pos2 locations to exchange the gene bit information between these two locations, the following figure shows the off1 and off2 individuals, but these two individuals usually have a genetic bit information conflict (during integer encoding). At this time, you need to adjust the off1 and off2 individuals: the conflicting genes in off1 are adjusted to those at the same position in parent2 according to the genes in parent1. If "1" appears twice in off1, "1" in the second place needs to be adjusted to "4" in parent2 corresponding to "1" in parent1 ", and so on. Note that to adjust off2, You need to refer to parent2.

3.5 mutation operation

For the mutation operation, there are different mutation operations according to different encoding methods.

If it is a floating-point number encoding, the mutation can be performed on the information of a certain gene bit in the middle of the chromosome (re-generated or other adjustment schemes ).

If the integer encoding scheme is used, there are generally multiple mutation methods: location variation and symbol variation.

Location variation:

Symbol variation:

4. Python code

#-*- coding:utf-8 -*-  import random import math from operator import itemgetter  class Gene:  '''''  This is a class to represent individual(Gene) in GA algorithom  each object of this class have two attribute: data, size  '''  def __init__(self,**data):   self.__dict__.update(data)     self.size = len(data['data'])#length of gene             class GA:  '''''  This is a class of GA algorithm.  '''  def __init__(self,parameter):   '''''   Initialize the pop of GA algorithom and evaluate the pop by computing its' fitness value .   The data structure of pop is composed of several individuals which has the form like that:      {'Gene':a object of class Gene, 'fitness': 1.02(for example)}    Representation of Gene is a list: [b s0 u0 sita0 s1 u1 sita1 s2 u2 sita2]      '''   #parameter = [CXPB, MUTPB, NGEN, popsize, low, up]   self.parameter = parameter    low = self.parameter[4]   up = self.parameter[5]      self.bound = []   self.bound.append(low)   self.bound.append(up)      pop = []   for i in range(self.parameter[3]):    geneinfo = []    for pos in range(len(low)):     geneinfo.append(random.uniform(self.bound[0][pos], self.bound[1][pos]))#initialise popluation         fitness = evaluate(geneinfo)#evaluate each chromosome    pop.append({'Gene':Gene(data = geneinfo), 'fitness':fitness})#store the chromosome and its fitness       self.pop = pop   self.bestindividual = self.selectBest(self.pop)#store the best chromosome in the population     def selectBest(self, pop):   '''''   select the best individual from pop   '''   s_inds = sorted(pop, key = itemgetter("fitness"), reverse = False)   return s_inds[0]     def selection(self, individuals, k):   '''''   select two individuals from pop   '''   s_inds = sorted(individuals, key = itemgetter("fitness"), reverse=True)#sort the pop by the reference of 1/fitness   sum_fits = sum(1/ind['fitness'] for ind in individuals) #sum up the 1/fitness of the whole pop      chosen = []   for i in xrange(k):    u = random.random() * sum_fits#randomly produce a num in the range of [0, sum_fits]    sum_ = 0    for ind in s_inds:     sum_ += 1/ind['fitness']#sum up the 1/fitness     if sum_ > u:      #when the sum of 1/fitness is bigger than u, choose the one, which means u is in the range of [sum(1,2,...,n-1),sum(1,2,...,n)] and is time to choose the one ,namely n-th individual in the pop      chosen.append(ind)      break      return chosen     def crossoperate(self, offspring):   '''''   cross operation   '''   dim = len(offspring[0]['Gene'].data)    geninfo1 = offspring[0]['Gene'].data#Gene's data of first offspring chosen from the selected pop   geninfo2 = offspring[1]['Gene'].data#Gene's data of second offspring chosen from the selected pop      pos1 = random.randrange(1,dim)#select a position in the range from 0 to dim-1,   pos2 = random.randrange(1,dim)    newoff = Gene(data = [])#offspring produced by cross operation   temp = []   for i in range(dim):    if (i >= min(pos1,pos2) and i <= max(pos1,pos2)):     temp.append(geninfo2[i])     #the gene data of offspring produced by cross operation is from the second offspring in the range [min(pos1,pos2),max(pos1,pos2)]    else:     temp.append(geninfo1[i])     #the gene data of offspring produced by cross operation is from the frist offspring in the range [min(pos1,pos2),max(pos1,pos2)]   newoff.data = temp      return newoff    def mutation(self, crossoff, bound):   '''''   mutation operation   '''      dim = len(crossoff.data)    pos = random.randrange(1,dim)#chose a position in crossoff to perform mutation.    crossoff.data[pos] = random.uniform(bound[0][pos],bound[1][pos])   return crossoff    def GA_main(self):   '''''   main frame work of GA   '''      popsize = self.parameter[3]      print("Start of evolution")      # Begin the evolution   for g in range(NGEN):        print("-- Generation %i --" % g)           #Apply selection based on their converted fitness    selectpop = self.selection(self.pop, popsize)      nextoff = []     while len(nextoff) != popsize:      # Apply crossover and mutation on the offspring                 # Select two individuals     offspring = [random.choice(selectpop) for i in xrange(2)]          if random.random() < CXPB: # cross two individuals with probability CXPB      crossoff = self.crossoperate(offspring)      fit_crossoff = evaluate(self.xydata, crossoff.data)# Evaluate the individuals               if random.random() < MUTPB: # mutate an individual with probability MUTPB       muteoff = self.mutation(crossoff,self.bound)       fit_muteoff = evaluate(self.xydata, muteoff.data)# Evaluate the individuals       nextoff.append({'Gene':muteoff,'fitness':fit_muteoff})           # The population is entirely replaced by the offspring    self.pop = nextoff        # Gather all the fitnesses in one list and print the stats    fits = [ind['fitness'] for ind in self.pop]         length = len(self.pop)    mean = sum(fits) / length    sum2 = sum(x*x for x in fits)    std = abs(sum2 / length - mean**2)**0.5    best_ind = self.selectBest(self.pop)     if best_ind['fitness'] < self.bestindividual['fitness']:     self.bestindividual = best_ind     print("Best individual found is %s, %s" % (self.bestindividual['Gene'].data,self.bestindividual['fitness']))    print(" Min fitness of current pop: %s" % min(fits))    print(" Max fitness of current pop: %s" % max(fits))    print(" Avg fitness of current pop: %s" % mean)    print(" Std of currrent pop: %s" % std)      print("-- End of (successful) evolution --")   if __name__ == "__main__":   CXPB, MUTPB, NGEN, popsize = 0.8, 0.3, 50, 100#control parameters    up = [64, 64, 64, 64, 64, 64, 64, 64, 64, 64]#upper range for variables  low = [-64, -64, -64, -64, -64, -64, -64, -64, -64, -64]#lower range for variables  parameter = [CXPB, MUTPB, NGEN, popsize, low, up]    run = GA(parameter)  run.GA_main() 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.