Python Geatpy genetic algorithms and evolutionary framework of the Quick Start

  Geatpy is a practical type of high-performance genetic algorithm toolbox Python provides an object-oriented framework of evolutionary algorithms, after a comprehensive revision, the new Geatpy2 currently developed by the South China Agricultural University, Jinan University, South China and other joint team of students and this diversification maintain.

  Website (including documentation): http://www.geatpy.com

  Demo : https://github.com/geatpy-dev/geatpy/tree/master/geatpy/demo

  Pypi page : https://pypi.org/project/geatpy/

  Contact us: http://geatpy.com/index.php/about/

  Bug reports: https://github.com/geatpy-dev/geatpy/issues

  Notice: http://geatpy.com/index.php/notice/

  FAQ: http://geatpy.com/index.php/faq/

  Geatpy provides a number of relevant operators of genetic and evolutionary algorithms library functions have been implemented, such as the initial population, selection, crossover, mutation, re-insert, multi-objective optimization of non-dominated sorting, etc., and provides a lot of evolutionary algorithms template has been implemented to achieve diverse evolutionary algorithm. Its efficiency is higher than Matlab, Python written in Java and some well-known toolbox, such as platform or framework, lower learning costs, the decoupling module height, high scalability.

  Geatpy support binary / gray code population, the population real value, the integer value populations, the population coding arrangement. Support ××× bet selection, random sample selection, tournament selection. Providing a single-point crossover, two-point crossover, shuffle cross section matching the cross (the PMX), order crossover (OX), linear recombination, recombinant discrete, intermediate reorganization recombination operator. It provides a simple discrete variation, variation of real value, the integer value Mutation, exchange mutation operator. It supports random re-insertion, re-insert the elite. Support awGA, rwGA, nsga2, fast non-dominated multi-objective optimization of library functions such as sorting, provide common templates wait for the next evolutionary algorithm evolutionary algorithm framework.

  Genetic algorithms, evolutionary algorithms learning materials, the official website of https://www.geatpy.com detailed explanation and academic papers related links. At the same time there are also a lot of information online.

  Without further ado ...... Here to talk about how to install and use:

  Let me talk about the installation method:

  The first is to the windows system, Python 3.5, 3.6 or 3.7 if the version and installed pip. Just execute the console

  pip install geatpy

  It can be installed successfully. Or to download the source code to compile on github installation: https: //github.com/geatpy-dev/geatpy. Recommended installation is directly pip way. Because of this convenient subsequent updates. I run for the convenience of demo code and view the source code and tutorials official documents, so in addition also on github download (but still pip installation mode).

  I do not know how to write code after some Python beginner readers reflect still do not know how to install or installation. It is recommended to install Anaconda, which integrates many popular Python runtime, such as Numpy, Scipy and so on. Its built-in style is similar to Spyder software development with Matlab, gives a familiar feeling, more easy to use.

  To tell you the update method:

  Geatpy continually updated. Can make the latest version of the official version on the computer is consistent with the following command:

  pip install --upgrade geatpy

  If it is "--user" the wrong problem during the update process, which is one of the common problems encountered when installing with pip. It means that you need to run as administrator mode:

  pip install --user --upgrade geatpy

  Geatpy offers two ways to use evolutionary algorithms to solve the problem. Before speaking about the first basic ways: to write programming scripts.

  1. scripting achieve genetic algorithm:

  In a very simple single-objective optimization problem as an example: Demand f (x) = x * sin (10 * pi * x) at the maximum value of +2.0 [1,2] on the x∈.

  Direct written script as follows:

  """demo.py"""

  import numpy as np

  import geatpy as ea # import geatpy library

  import matplotlib.pyplot as plt

  import time

  "" "Objective function ============================ ================= =========== "" "

  def aim (x): # after the introduction of the population chromosome gene expression matrix decoding matrix type

  return x * np.sin (10 * np.pi * x) + 2.0

  x = np.linspace(-1, 2, 200)

  plt.plot (x, aim (x)) # draw the target image function

  "" "Variable is set ============================ ================= =========== "" "

  x1 = [-1, 2] # argument range

  b1 = [1, 1] # argument boundary

  varTypes = np.array ([0]) # type argument, 0 represents a continuous, discrete represents 1

  Encoding = 'BG' # 'BG' represents a binary / Gray code

  codes = [1] # coding variables, two variables are encoded using Gray

  precisions = [4] # variable encoding precision

  scales = [0] # the arithmetic scale

  ranges = np.vstack ([x1]). T # argument matrix generation range

  borders = np.vstack ([b1]). T # boundary matrix generated argument

  "" "========================= genetic algorithm parameter settings ================== ======= "" "

  NIND = 40; number of individuals in the population #

  MAXGEN = 25; # maximum hereditary algebra

  FieldD = ea.crtfld (Encoding, varTypes, ranges, borders, precisions, codes, scales) # call the function to create area descriptor

  Lind = int (np.sum (FieldD [0,:])) # chromosome length after calculation code

  obj_trace = np.zeros ((MAXGEN, 2)) # define the objective function value recorder

  var_trace = np.zeros ((MAXGEN, Lind)) # Chromosomal recorder, recording the best individual of each generation chromosome

  "" "========================= start genetic algorithm evolution ================== ====== "" "

  start_time = time.time () # start time

  Chrom = ea.crtbp (NIND, Lind) # generate a population of chromosome matrix

  variable = ea.bs2real (Chrom, FieldD) # decoding the initial population

  ObjV = aim (variable) # calculates the objective function value of the initial population of individuals

  best_ind = np.argmax (ObjV) # calculates the current best individual serial number

  # Began to evolve

  for gen in range(MAXGEN):

  FitnV = ea.ranking (-ObjV) # size distribution according to the fitness value of the objective function (due to follow the agreed target minimized, thus maximizing the objective function value Problems to be multiplied by -1)

  SelCh = Chrom [ea.selecting ( 'rws', FitnV, NIND-1),:] # selected using 'rws' ××× selected bet

  SelCh = ea.recombin ( 'xovsp', SelCh, 0.7) # recombination (two-point crossover manner, crossover probability 0.7)

  SelCh = ea.mutbin (Encoding, SelCh) # Binary population variation

  # The elite individual merger with parent offspring

  Chromium np.vstack = ([chrome [best_ind,:] Salchah])

  variable = ea.bs2real (Chrom, FieldD) # breeding population of decoding (Binary Coded Decimal)

  ObjV = aim (variable) # find individual objective function value breeding

  Record #

  best_ind = np.argmax (ObjV) # calculates the current best individual serial number

  obj_trace [gen, 0] = np.sum (ObjV) / NIND # contemporary recording objective function population mean

  obj_trace [gen, 1] = ObjV [best_ind] # record the best individual objective function value contemporary populations

  var_trace [gen,:] = Chrom [best_ind,:] # contemporary populations optimum recording individual variable values

  # Evolution complete

  end_time = time.time () # end timing

  "" "The output and Mapping =============== ============================ ================= "" "

  best_gen = np.argmax(obj_trace[:, [1]])

  print ( 'maximum objective function:', obj_trace [best_gen, 1]) # output destination Maximization

  variable = ea.bs2real (var_trace [[best_gen],:], FieldD) # decoded phenotype

  print ( 'decision variables corresponding to values:')

  print (variable [0] [0]) # because here is a variable matrix, with the [0] [0] element to remove the inside

  print('用时:', end_time - start_time)

  plt.plot(variable, aim(variable),'bo')

  ea.trcplot (obj_trace, [[ 'population average individual objective function value,' 'best individual objective function value populations']])

  Results are as follows:

  The maximum value of the objective function: 3.850272716105895

  Corresponding decision variable values ​​are:

  1.8505813776055176

  Time: .02496051788330078

  A closer look at the above code, we will find Geatpy writing style similar to Matlab, Matlab programming experience has basically can be seamlessly transferred to Python use Geatpy genetic algorithm program development.

  Geatpy provides a detailed API documentation, example code above to see the "ranking" function is doing, you can do in python

  import geatpy as ga

  help(ga.ranking)

  You can see the relevant use of "ranking" function.

  In addition there are also the official website for more detailed Geatpy tutorial: http: //geatpy.com/index.php/details/

  2. Using the framework of realization of genetic algorithm.

  Geatpy provide an open object-oriented framework of evolutionary algorithms. That "class issue" + "evolutionary algorithms template class + class population." For some complex evolutionary algorithms, such as multi-objective evolutionary optimization, improved genetic algorithm, in accordance with the above mentioned scripting code it is very troublesome, but with methodological framework can greatly improve programming efficiency.

  Here is an example of using the framework implements Pareto front surface NSGA-II algorithm for multiobjective optimization function ZDT-1 is:

  The first step: First class ZDT1 written questions, writing in "MyProblem.py" file:

  # -*- coding: utf-8 -*-

  """MyProblem.py"""

  import numpy as np

  import geatpy as ea

  class MyProblem (ea.Problem): # inherit the parent class Problem

  def __init__(self):

  name = 'ZDT1' # name initialization (function name can be arbitrarily set)

  Initialization M = 2 # M (target dimension)

  maxormins = [1] * M # initialization maxormins (minimaxing labeled target list, 1: Minimize the target; -1: maximization of the target)

  Dim = 30 # Initialization Dim (dimension of decision variables)

  varTypes = [0] * Dim # initialization varTypes (decision variable type, 0: real; a: an integer)

  lb = [0] * Dim # lower bound of the decision variables

  ub = [1] * on the boundary decision variables Dim #

  lbin = [1] * lower boundary decision variables Dim #

  ubin = [1] * on the boundary decision variables Dim #

  # Call the parent class constructor complete instantiation

  ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)

  def aimFunc (self, pop): # objective function

  Vars = pop.Phen # obtain a decision variable matrix

  ObjV1 = Vars [:, 0]

  Gksh = 1 + 9 * Npksum (Vars [:, 1:30], 1)

  hx = 1 - np.sqrt(ObjV1 / gx)

  ObjV2 = gx * hx

  pop.ObjV = np.array ([ObjV1, ObjV2]). T # assign the result to ObjV

  def calBest (self): # calculate the global optimal solution

  N = 10000 # 10000 generates reference points

  ObjV1 = np.linspace(0, 1, N)

  ObjV2 = 1 - np.sqrt(ObjV1)

  globalBestObjV = np.array([ObjV1, ObjV2]).T

  return globalBestObjV

  In the above code, the problem class constructor __init __ () is used to define parameters associated with test ZDT1 problems, such as the range of decision variables, type, and so the boundary. aimFunc () is the objective function to be optimized. calBest () can be used to calculate the theoretical global optimal solution, optimal solution to this theory can be obtained by calculation, can also be obtained by data import external files, if the problem to be solved or not is not known theory most What is the optimal solution, then this calBest () function can be omitted.

  Step Two: Write in the same folder to execute the script, the above-mentioned problems instantiate an object class, and then call the evolutionary algorithm template nsga2 algorithm Geatpy provided (moea_NSGA2_templet), and finally the global optimum combination of theory PF (commonly known as " real frontier point ") by calculating GD, IGD, HV and other indicators to analyze the effect of optimization:

  # -*- coding: utf-8 -*-

  import geatpy as ea # import geatpy

  from MyProblem import MyProblem

  "" "================================ problems of object instances =========== ================== "" "

  problem = MyProblem () # generated the object in question

  "" "Set population ================================== =========== ===================== "" "

  Encoding = 'RI' # coding

  NIND = 50 # population size

  Field = ea.crtfld (Encoding, problem.varTypes, problem.ranges, problem.borders) # create zones descriptor

  population = ea.Population (Encoding, Field, NIND) # instantiated objects populations (population at this time has not been initialized, only the instantiation of the object population)

  "" "================================ algorithm parameters ============ =================== "" "

  myAlgorithm = ea.moea_NSGA2_templet (problem, population) # instantiate a template object algorithm `

  myAlgorithm.MAXGEN = 200 # The maximum evolution generation

  myAlgorithm.drawing = 1 # Set the drawing mode (0: no drawing; 1: FIG drawing result; 2: Animation drawing process)

  "" "=========================== call algorithm template population evolution ============== =============

  Call the run template execution algorithm to obtain the Pareto optimal solution set NDSet. NDSet is a class Population population of objects.

  NDSet.ObjV optimal solution for the objective function value of the individual; NDSet.Phen value corresponding decision variables.

  See Population.py definition of the class of the population.

  """

  NDSet = myAlgorithm.run () # template execution algorithm to obtain non-dominant populations

  NDSet.save () # save the results to a file

  # Output Wuxi gynecological check how much money http://www.120csfkyy.com/

  print ( 'when used:% f s'% (myAlgorithm.passTime))

  print ( 'times Evaluation:% d times'% (myAlgorithm.evalsNum))

  print ( 'number of individuals nondominated:% d a'% (NDSet.sizes))

  print ( 'number of unit time to find Pareto front points:% d a'% (int (NDSet.sizes // myAlgorithm.passTime)))

  # Calculate the index

  PF = problem.getBest () # get the real frontier, see Problem.py Problem definition of the class

  if PF is not None and NDSet.sizes != 0:

  GD = ea.indicator.GD (NDSet.ObjV, PF) # index calculated GD

  IGD = ea.indicator.IGD (NDSet.ObjV, PF) # index calculated IGD

  HV = ea.indicator.HV (NDSet.ObjV, PF) # index calculated HV

  Spacing = ea.indicator.Spacing (NDSet.ObjV) # Spacing metrics calculated

  print('GD',GD)

  print('IGD',IGD)

  print('HV', HV)

  print('Spacing', Spacing)

  "" "============================= evolution indicator tracking analysis ============= =============== "" "

  if PF is not None:

  metricName = [['IGD'], ['HV']]

  [NDSet_trace, Metrics] = ea.indicator.moea_tracking(myAlgorithm.pop_trace, PF, metricName, problem.maxormins)

  # Draw indicator tracking analysis chart

  ea.trcplot(Metrics, labels = metricName, titles = metricName)

  Results are as follows:

  Population information is exported finished.

  Time: 0.503653 seconds

  Number of reviews: 10000

  Nondominated number of individuals: 50

  The number of units of time to find the Pareto frontier points: 99

  GD 0.0011025023611967554

  IGD 0.15098973339777405

  HV 0.624906599521637

  Spacing 0.009326105831814594

  Ongoing evolution tracking index analysis, please wait ......

  Index tracking analysis end, evolution recorder effective evolution algebra: 200

  The code for each process has been detailed notes. Which core logic evolutionary algorithm is written in the evolutionary algorithm inside templates, you can go to see the corresponding source code. In addition, we can refer to Geatpy evolutionary algorithm source code template to customize the template algorithm to achieve a variety of evolutionary algorithms, such as a variety of improved evolutionary algorithm:

  Finally it is worth noting: the objective function aimFunc () that a local easiest wrong. aimFunc () pop input parameter is a target population (population about the object to view Population.py source category toolbox, or view Geatpy data structure). pop.Phen a population of phenotype matrix, meaning that the population phenotype matrix decoded chromosome, the decision variable is the problem in its corresponding class. Phen is a matrix, each row corresponds to an individual in the population phenotype. When calculating the target function, this can be split into Phen line by line, i.e. the calculated one by one by the individual objective function value, and then assigned to the matrix makes up a pop ObjV attribute object. Can also be used to calculate the matrix of Numpy "breath," the objective function value calculated for all individual stocks. Regardless of what kind of calculation, the resulting value of the objective function is to save the properties ObjV pop object of this ObjV the "objective function value matrix Population", each row corresponds to all of an individual objective function value, each of one corresponding to a target. such as:

  


  It has a population of three individuals represented, there are two objectives to be optimized.


Guess you like

Origin blog.51cto.com/14335413/2429367