In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to install and use geatpy of python genetic algorithm", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to install and use geatpy of python genetic algorithm" article.
1. Installation of geatpy
First, install geatpy, which can be installed using the pip3 command:
Pip3 install geatpy
The installation is successful when prompted as follows:
2. Basic data structure of geatpy
Most of the data in geatpy is stored and calculated using numpy's array, so I'll show you how concepts in genetic algorithms are represented in numpy data, and what rows and columns mean.
2.1 population chromosomes
The most important thing in genetic algorithm is the representation of individual chromosomes. In geatpy, population chromosomes are represented by Chrom, which is a two-dimensional array, in which each row corresponds to an individual chromosome code. The structure of Chrom is as follows: lind represents the length of coding, and Nind represents the size of the population (number of individuals).
2.2 population phenotype
Population phenotype refers to the gene phenotype matrix Phen obtained by decoding the population chromosome matrix Chrom, with each row corresponding to an individual and each column corresponding to a decision variable. The structure of Phen is as follows: Nvar represents the number of variables.
The value of Phen is related to the decoding method used. Geatpy provides binary / Gray code encoding to decimal integer or real number decoding. In addition, Geatpy can also use a "real-valued coding" population that does not need to be decoded, in which each bit of the chromosome corresponds to the actual value of the decision variable, that is, Phen is equivalent to Chrom under this coding mode.
2.3 objective function value
Geatpy uses numpy's array type matrix to store the objective function values of the population. Generally named ObjV, each row corresponds to each individual, so it has the same number of rows as Chrom; each column corresponds to an objective function, so for a single objective function, ObjV has only one column; for a multi-objective function, ObjV has multiple columns, and ObjV is expressed as follows:
2.4 individual fitness
Geatpy uses column vectors to store individual fitness of the population (calculated from the fitness function). Generally named FitnV, it is also the array type of numpy, with each row corresponding to each individual of the population matrix. So it has the same number of lines as Chrom, and FitnV has the following format:
Note: the fitness in Geatpy follows the convention of "minimum fitness is 0".
2.5 degree of constraint violation matrix
Geatpy uses numpy's array type matrix CV (Constraint Violation Value) to store the extent to which individuals violate various constraints. Named CV, each row corresponds to each individual of the population, so it has the same number of rows as Chrom; each column corresponds to a constraint, so if there is a constraint, then the CV matrix will have only one column, and if there are multiple constraints, the CV matrix will have multiple columns. If there are num constraints, the structure of the CV matrix is shown in the following figure:
If an element of the CV matrix is less than or equal to 0, the corresponding individual of the element satisfies the corresponding constraint condition. If it is greater than 0, it means that the constraint is violated, and the greater the value is, the higher the degree to which the individual violates the constraint. Geatpy provides two methods to deal with constraints, one is the penalty function method, and the other is the feasibility law. When using the feasibility rule to deal with constraints, the CV matrix is needed.
2.6 Decoding Matrix
The so-called decoding matrix is only a matrix used to describe the chromosome characteristics of the population, such as the range of decision variables expressed by each element in the chromosome, whether it contains the boundary of the range, the use of binary or Gray code, whether to use logarithmic scale, whether the decision variables represented by chromosome decoding are continuous variables or discrete variables, and so on.
When using only the library functions of the toolbox and not the object-oriented evolutionary algorithm framework provided by Geatpy, the decoding matrix can be used alone. If the object-oriented evolutionary algorithm framework provided by Geatpy is adopted, the decoding matrix can be used in conjunction with a string Encoding that stores the coding mode of the population chromosome.
Currently, there are three kinds of Encoding in Geatpy, which are:
BG: (binary / Gray code)
RI: ((real integer coding, that is, mixed encoding of real and integer numbers)
P: (permutation coding, that is, the elements of each bit of the chromosome are different from each other)
Note: the chromosomes encoded by 'RI'' and'P'do not need to be decoded, and each bit on the chromosome itself represents the true value of the decision variable, so "real integer coding" and "permutation coding" can be collectively referred to as "real value coding".
Taking BG coding as an example, let's show the compilation matrix FieldD. The structure of FieldD is as follows:
Among them, lens,lb,ub,codes,scales,lbin,ubin,varTypes is a row vector whose length is equal to the number of decision variables.
Lens: represents the length of each daughter chromosome in a chromosome.
Lb: represents the upper bound of each variable
Ub: represents the lower bound of each variable
Codes: represents the coding method used for the chromosome string, [1j0jue 1] represents the Gray code for the first variable, the binary code for the second variable, and the Gray code for the third variable.
Scales: indicates whether each substring uses an arithmetic scale or a logarithmic scale. Scales [I] = 0 is the arithmetic scale, and scales [I] = 1 is the logarithmic scale (the logarithmic scale is rarely used and can be ignored. )
Lbin: represents whether the upper bound of a variable contains its scope boundary. 0 means not included, 1 means included. The difference between'['and' (')
Ubin: represents whether the lower bound of a variable contains its scope boundary. 0 means not included, 1 means included.
VarTypes: represents the type of decision variable. An element of 0 indicates that the decision variable at the corresponding position is a continuous variable; 1 indicates that the decision variable is a discrete variable.
For example, there is a decoding matrix
It indicates that the population chromosome matrix Chrom to be decoded can be represented as three decision variables after decoding, and the value range of each decision variable is [1Jing 10], [2Jing 9], [3jue 15] respectively. Among them, the first and second variable uses binary coding, the third variable uses Gray coding, and the first and third decision variables are continuous variables; the second is discrete variables.
# the population phenotype matrix can be decoded by population chromosome chrom and decoding matrix FieldD. Import geatpy as eaPhen = ea.bs2ri (Chrom, FieldD) 2.7Evolutionary tracker
When using Geatpy to program evolutionary algorithms, we often build an evolutionary tracker (such as pop_trace) to record the optimal individuals of each generation of the population in the process of evolution, especially when there is no elite retention mechanism, the evolutionary tracker helps us to record the optimal individuals in the evolutionary process. After the evolution is completed, the "historically best" individuals are selected from the evolution tracker. There are many kinds of evolution recorders, one of which is of numpy's array type, and its structure is as follows: MAXGEN is the algebra of population evolution (number of iterations).
Each column of trace represents different indicators, for example, the first column records the best objective function values of each generation population, and the second column records the average objective function values of each generation population. Each line of trace corresponds to each generation, for example, the first line represents the first generation, and the second row represents the second generation. Another type of evolution logger is a list in which each element is a data with the same data type. For example, pop_trace in the framework of Geatpy's object-oriented evolutionary algorithm is a list, and each element in the list is a population object of past generations.
3. Population structure of geatpy 3.1 Population class
In the framework of object-oriented evolutionary algorithm provided by Geatpy, population class (Population) is a class that stores information related to individuals of the population. It has the following basic properties:
Sizes: int-population size, that is, the number of individuals in the population.
ChromNum: int-the number of chromosomes, that is, how many chromosomes there are in each individual.
Encoding: str-chromosome coding.
Field: array-Decoding matrix, which can be FieldD or FieldDR.
Chrom: array-population chromosome matrix, each row corresponds to one chromosome of an individual.
Lind: int-chromosome length of the population.
ObjV: array-population objective function value matrix.
FitnV: array-the column vector of population individual fitness.
CV: array-the matrix of the degree to which the individual violates the constraint condition.
Phen: array-population phenotype matrix.
We can directly extract individuals and merge individuals from population objects. For example, if pop1 and pop2 are two population objects, then we can merge the individuals of the two populations and get a new population by saying "pop3 = pop1 + pop2". In the process of merging, the attributes of the population are actually merged, and then the merged data is used to generate a new population (see Population.py for details). For example, by executing the statement "pop3 = pop1 [[0]]", we can extract the No. 0 individual of the population and get a new population object pop3 with only one individual. It is worth noting that this individual extraction operation of the population requires that the subscript must be a list or a row vector of type Numpy array, not a scalar (see Population.py for details)
3.2 PsyPopulation classes
The PsyPopulation class is a subclass of Population and provides mixed coding of multiple chromosomes that is not supported by the Population class. It has the following basic properties:
Sizes: int-population size, that is, the number of individuals in the population.
ChromNum: int-the number of chromosomes, that is, how many chromosomes there are in each individual.
Encodings: list-stores a list of how each chromosome is encoded.
Fields: list-stores a list of decoding matrices corresponding to each chromosome.
Chroms: list-stores a list of the chromosome matrices of the population.
Linds: list-stores a list of the chromosomal lengths of the population.
ObjV: array-population objective function value matrix.
FitnV: array-the column vector of population individual fitness.
CV: array-the matrix of the degree to which the individual violates the constraint condition.
Phen: array-population phenotype matrix.
It can be seen that the PsyPopulation class is basically the same as the Population class, except that Linds, Encodings, Fields and Chroms are used to store multiple Lind, Encoding, Field and Chrom, respectively.
PsyPopulation objects are often used in conjunction with evolutionary algorithm templates with the word "psy" to achieve evolutionary optimization of multi-chromosome hybrid coding.
4. Solving the standard test function-- McCormick function
Genetic algorithm solves the minimum value of the following functions:
Code implementation:
#-*-coding:utf-8-*-import numpy as npimport geatpy as ea# is imported into geatpy library import time "" = = objective function = = "def aim (Phen): # the decoded gene phenotype matrix x1 = Phen [:, [0]] # take out the first column and get the first independent variable x2 = Phen [:, [1]] # take out the second column The second independent variable return np.sin (x1 + x2) + (x1-x2) * * 2-1.5 * x1 + 2.5 * x2x1 "" = = variable setting = "" x1 = [- 1.5,4] # the first decision variable range x2 = [- 3,4] # the second decision variable range b1 = [1,1] # the boundary of the first decision variable 0 does not include the boundary of b2 = [1,1] # second decision variable, 1 indicates the boundary of containing range, 0 indicates that it does not contain the range matrix of # generated independent variable, so that the lower bound of all decision variables of the first behavior and the upper bound of the second behavior ranges=np.vstack ([x1, x2]). T # generates the boundary matrix of independent variable borders=np.vstack ([b1, b2]). TvarTypes = np.array ([0,0]) # the type of decision variable 0 means continuous, 1 means discrete "" = chromosome coding setting = "Encoding = 'BG'#'BG' means binary / Gray coding codes = [1,1] # decision variable, and both 1s represent the coding accuracy of the decision variable precisions = [6,6] # It indicates that the precision of the decision variable that can be expressed after decoding can reach 6 digits after the decimal point scales = [0,0] # 0 indicates that the arithmetic scale is used. 1 means to use logarithmic scale # call function to create decoding matrix FieldD = ea.crtfld (Encoding,varTypes,ranges,borders,precisions,codes,scales) "" = genetic algorithm parameter setting = = "NIND = 2 population number of individuals MAXGEN = 10 maximum genetic algebra maxormins = np.array ([1]) # indicates that the objective function is minimized An element of-1 means that the corresponding objective function is maximized selectStyle = 'sus'# using random sampling selection recStyle =' xovdp'# using two-point crossover mutStyle = 'mutbin'# using binary chromosome mutation operator Lind = int (FieldD [0,:]) # calculating chromosome length pc= 0.1 crossover probability pm= 1/Lind# mutation probability obj_trace = np.zeros ((MAXGEN) 2)) # define the target function value recorder var_trace = np.zeros ((MAXGEN, Lind)) # chromosome recorder Record the chromosomes of the best individuals in previous generations "" = start genetic algorithm evolution = = "start_time = time.time () # start timing Chrom = ea.crtpc (Encoding,NIND, FieldD) # generate population chromosome matrix variable = ea.bs2ri (Chrom FieldD) # Decode the initial population ObjV = aim (variable) # calculate the objective function value of the initial population best_ind = np.argmin (ObjV) # calculate the sequence number of the contemporary optimal individual # start evolution for gen in range (MAXGEN): FitnV = ea.ranking (maxormins * ObjV) # assign the fitness value SelCh = Chrom according to the size of the objective function [ea.selecting (selectStyle,FitnV,NIND-1),:] # Select SelCh = ea.recombin (recStyle, SelCh Pc) # Recombinant SelCh = ea.mutate (mutStyle, Encoding, SelCh, pm) # mutation # # merging the chromosomes of the elite individuals of the father and the offspring Get the new generation population Chrom = np.vstack ([Chrom [best _ ind,:], SelCh]) Phen = ea.bs2ri (Chrom, FieldD) # decode the population (binary to decimal) ObjV = aim (Phen) # find the objective function value of the individual # record best_ind = np.argmin (ObjV) # calculate the sequence number obj_ tracegen of the contemporary best individual [ 0] = np.sum (ObjV) / ObjV.shape [0] # record the average value of the objective function of contemporary population obj_trace [gen,1] = ObjV [best _ ind] # record the value of objective function of the optimal individual of contemporary population var_trace [gen,:] = Chrom [best _ ind,:] # record the chromosome of the best individual of contemporary population # Evolution completed end_time = time.time () # end timing ea.trcplot (obj_trace [['population individual average objective function value', 'population optimal individual objective function value']) # drawing image "= = output result = =" best_gen = np.argmin (obj_trace [:, [1]]) print ('objective function value of the optimal solution:', obj_ trace [best _ gen, 1]) variable = ea.bs2ri (var_trace [[best_gen],:] FieldD) # decoded to get the phenotype (that is, the corresponding decision variable value) print (') for i in range (variable.shape [1]): print ('x'+str (I) +' =', variable [0, I]) print ('time:', end_time-start_time,' seconds')
Effect picture:
The results are as follows:
The above is about the content of this article on "how to install and use geatpy of python genetic algorithm". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.