Python implements simple genetic algorithms and python Genetic Algorithms

Source: Internet
Author: User

Python implements simple genetic algorithms and python Genetic Algorithms

Today, I sorted out the code I wrote and found that the genetic algorithm written in python during the dashboard process was quite interesting. I 'd like to share it with you.

First, the genetic algorithm is an optimization algorithm that simulates the survival of the fittest of genes for computation (the specific idea of the algorithm is not described in detail ). The process is divided into initialization code, individual evaluation, selection, crossover, and mutation.

Take the target formula y = 10 * sin (5x) + 7 * cos (4x) as an example to calculate its maximum value.

Initialization includes formula, population quantity, chromosome length, mating probability, and mutation probability to be calculated. And initialize the gene sequence.

Pop_size = 500 # population quantity max_value = 10 # maximum chrom_length = 10 # chromosome length pc = 0.6 # mating probability pm = 0.01 # mutation probability results = [[] # store the optimal solution of each generation, N binary groups fit_value = [] # individual fitness fit_mean = [] # average fitness pop = geneEncoding (pop_size, chrom_length)

GenEncodeing is a simple random generation sequence function. The specific implementation is as follows:

def geneEncoding(pop_size, chrom_length):  pop = [[]]  for i in range(pop_size):   temp = []   for j in range(chrom_length):    temp.append(random.randint(0, 1))   pop.append(temp)   return pop[1:] 

After encoding is complete, individual evaluation is required. Individual evaluation is mainly used to calculate the value of each encoded list and the value corresponding to the target sub-type. Actually, a bunch of binary lists are encoded. Each of these binary lists represents a number. The value is calculated in decimal order. Then, the length of the sequence divided by 2 is reduced by one to the power, that is, the decimal value of the whole list is reduced by one. According to this rule, you can calculate the values of all lists and the values that are included in the formula to be calculated. The Code is as follows:

#0.0 coding: UTF-8 0.0 # decode and calculate the value import math def decodechrom (pop, chrom_length): temp = [] for I in range (len (pop )): t = 0 for j in range (chrom_length): t + = pop [I] [j] * (math. pow (2, j) temp. append (t) return temp def calobjValue (pop, chrom_length, max_value): temp1 = [] obj_value = [] temp1 = decodechrom (pop, chrom_length) for I in range (len (temp1): x = temp1 [I] * max_value/(math. pow (2, chrom_length)-1) obj_value.append (10 * math. sin (5 * x) + 7 * math. cos (4 * x) return obj_value

With the specific value and corresponding gene sequence, and then conduct a elimination, the goal is to eliminate some impossible bad values. This is because the maximum value is calculated, so it is enough to eliminate the negative value.

#0.0 coding: UTF-8 0.0 # elimination (negative value removal) def calfitValue (obj_value): fit_value = [] c_min = 0 for I in range (len (obj_value )): if (obj_value [I] + c_min> 0): temp = c_min + obj_value [I] else: temp = 0.0 fit_value.append (temp) return fit_value

Then, we will make the selection, which is the core part of the entire genetic algorithm. Choose the survival of the fittest That actually simulates biological genetic evolution, so that excellent individuals can survive as much as possible, so that poor individuals can be eliminated as much as possible. The quality of an individual depends on the individual's fitness. The higher the individual fitness, the easier it is to stay, and the lower the individual fitness, the easier it is to be eliminated. The specific code is as follows:

#0.0 coding: UTF-8 0.0 # select import random def sum (fit_value): total = 0 for I in range (len (fit_value )): total + = fit_value [I] return total def cumsum (fit_value): for I in range (len (fit_value)-2,-1,-1 ): t = 0 j = 0 while (j <= I): t + = fit_value [j] j + = 1 fit_value [I] = t fit_value [len (fit_value) -1] = 1 def selection (pop, fit_value): newfit_value = [] # total fitness total_fit = sum (fit_value) for I in range (len (fit_value )): newfit_value.append (fit_value [I]/total_fit) # Calculate the cumulative probability cumsum (newfit_value) ms = [] pop_len = len (pop) for I in range (pop_len): ms. append (random. random () ms. sort () fitin = 0 newin = 0 newpop = pop # runner selection method while newin <pop_len: if (MS [newin] <newfit_value [fitin]): newpop [newin] = pop [fitin] newin = newin + 1 else: fitin = fitin + 1 pop = newpop

The preceding Code mainly performs three operations: calculate the total fitness of individual, and then calculate the cumulative fitness of each individual. These two steps are easy to understand, mainly the third step, the runner disk selection method. In this step, the total number of genes is 0-1 decimal, and then compared with the cumulative individual fitness of each gene. If the cumulative individual fitness is greater than the random number, it is retained; otherwise, it is eliminated. The core idea of this part is: the higher the individual fitness of a gene, the larger the gap between the cumulative fitness that he occupies, that is, the easier he will be preserved.
After the selection, mating and mutations are performed. These two steps are well understood. Is to change the gene sequence, but the change method is different.

Mating:

#0.0 coding: UTF-8 0.0 # mating import random def crossover (pop, pc): pop_len = len (pop) for I in range (pop_len-1): if (random. random () <pc): cpoint = random. randint (0, len (pop [0]) temp1 = [] temp2 = [] temp1.extend (pop [I] [0: cpoint]) temp1.extend (pop [I + 1] [cpoint: len (pop [I]) temp2.extend (pop [I + 1] [0: cpoint]) temp2.extend (pop [I] [cpoint: len (pop [I]) pop [I] = temp1 pop [I + 1] = temp2

Variation:

#0.0 coding: UTF-8 0.0 # gene mutation import random def mutation (pop, pm): px = len (pop) py = len (pop [0]) for I in range (px): if (random. random () <pm): mpoint = random. randint (0, py-1) if (pop [I] [mpoint] = 1): pop [I] [mpoint] = 0 else: pop [I] [mpoint] = 1

The implementation of the entire genetic algorithm is complete. The overall call entry code is as follows:

#0.0 coding: UTF-8 0.0 import matplotlib. pyplot as plt import math from calobjValue import calobjValue from calfitValue import calfitValue from selection import selection from crossover import crossover from mutation import mutation from best import best from geneEncoding import geneEncoding print y = 10 * math. sin (5 * x) + 7 * math. cos (4 * x) '# Calculate the value def b2d (B, max_value, chrom_length) represented by the binary sequence: t = 0 for j in range (len (B )): t + = B [j] * (math. pow (2, j) t = t * max_value/(math. pow (2, chrom_length)-1) return t pop_size = 500 # population quantity max_value = 10 # maximum chrom_length allowed in genes = 10 # chromosome length pc = 0.6 # mating probability pm = 0.01 # mutation probability results = [[] # store the optimal solution of each generation, fit_value = [] # individual fitness fit_mean = [] # average fitness # pop = [[0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1] for I in range (pop_size)] pop = geneEncoding (pop_size, chrom_length) for I in range (pop_size): obj_value = calobjValue (pop, chrom_length, max_value) # individual evaluation fit_value = calfitValue (obj_value) # Eliminate best_individual, best_fit = best (pop, fit_value) # The first stores the optimal solution, and the second stores the optimal gene results. append ([best_fit, b2d (best_individual, max_value, chrom_length)]) selection (pop, fit_value) # new population replication crossover (pop, pc) # mating mutation (pop, pm) # variant results = results [1:] results. sort () X = [] Y = [] for I in range (500): X. append (I) t = results [I] [0] Y. append (t) plt. plot (X, Y) plt. show ()

Finally, the matplotlib package is called to show the change trend of the 500 generation optimal solution.

Complete code can be viewed on github

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.