In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article "python genetic algorithm single / multi-objective programming problem how to solve" the knowledge points of most people do not understand, so the editor summarized the following content, detailed, clear steps, with a certain reference value, I hope you can read this article can have a harvest, let's take a look at this "python genetic algorithm single / multi-objective programming problem how to solve" article it.
1. Operation environment
Let's first introduce the running environment.
System: Windows10
Configuration: i7-6700 16G
Python version: 3.10
Geatpy version: 2.7.0
two。 Object-oriented principle
In the previous chapter, we introduced that genetic algorithms are mainly divided into algorithm template class (Algorithm), population class (Population), multi-chromosome mixed coding population class (PsyPopulation) and problem class (Problem). Population class and PsyPopulation class can be directly instantiated into objects to use the class; Algorithm class and Problem class is the parent class, need to instantiate their subclasses to use. Let's demonstrate the usage through a case study.
3. Single objective optimization problem with constraints
3.1 inheriting the Problem problem class to complete the description of the problem model
In this step, our problem is described clearly according to the template, including the objective function and constraints.
Import numpy as npimport geatpy as eaclass MyProblem (ea.Problem): # inherit Problem parent class def _ _ init__ (self): name = 'MyProblem' # initialize name (function name, you can set it at will) M = 1 # initialize M (target dimension) maxormins = [- 1] # initialize target minimum maximum tag list, 1:min -1:max Dim = 3 # initialize Dim (decision variable dimension) varTypes = [0] * Dim # initialize decision variable type, 0: continuous 1: discrete lb = [0,0,0] # decision variable lower bound ub = [1,1,2] # decision variable upper bound lbin = [1,1,0] # decision variable lower boundary ubin = [1,1,0] # decision variable upper boundary # call parent class construction method to instantiate ea.Problem.__init__ (self, name) M, maxormins, Dim, varTypes, lb, ub, lbin, ubin) def aimFunc (self, pop): # objective function Pop is the incoming population object Vars = pop.Phen # to get the decision variable matrix x1 = Vars [:, [0]] # take the first column to get all individuals x1 column vector x2 = Vars [:, [1]] # take the second column to get all individuals x2 column vector x3 = Vars [: [2]] # take out the third column to get the x3 column vector of all individuals # to calculate the value of the objective function The ObjV attribute pop.ObjV = 4 * x1 + 2 * x2 + x3 # assigned to the pop population object uses the feasibility rule to deal with constraints. Generate the population individual violation degree matrix pop.CV = np.hstack ([2 * x1 + x2-1, # first constraint x1 + 2 * x3-2, # second constraint np.abs (x1 + x2 + x3-1)]) # the third constraint 3.2 calls the algorithm template to solve the problem
In the second step, we mainly write the algorithm template to solve the definition of the problem in the first step, where we need to set the population, algorithm parameters, population evolution, and the output of the results.
"" main_solve.py "import geatpy as ea # import geatpyfrom myaim import MyProblem # Import Custom question Interface"= instantiate the problem object =" problem = MyProblem () # instantiate the problem object "="Encoding = 'RI' # Encoding method NIND = 50 # population size Field = ea.crtfld (Encoding, problem.varTypes, problem.ranges)" Problem.borders) # create area descriptor population = ea.Population (Encoding, Field, NIND) # instantiate the population object (at this time the population has not really been initialized Just generate a population object) "" = = algorithm parameter setting = "myAlgorithm = ea.soea_DE_best_1_L_templet (problem, population) # instantiate an algorithm template object myAlgorithm.MAXGEN = 1000 # maximum evolution algebra myAlgorithm.mutOper.F = 0.5 # parameter FmyAlgorithm.recOper.XOVR in differential evolution FmyAlgorithm.recOper.XOVR = 0. 7 # set crossover probability myAlgorithm.logTras = 1 # set how many generations to log If set to 0, log is not recorded myAlgorithm.verbose = True # set whether to print out log information myAlgorithm.drawing = 1 # set drawing mode (0: do not draw 1: draw the result diagram; 2: draw the process animation of the target space 3: draw decision space process animation) "" = call algorithm template for population evolution = "" [BestIndi, population] = myAlgorithm.run () # execute algorithm template Get the optimal individual and the last generation population BestIndi.save () # save the information of the optimal individual in the file "" = = output result = = "print ('evaluation times:% s'% myAlgorithm.evalsNum) print ('time takes% s seconds'% myAlgorithm.passTime) if BestIndi.sizes! = 0: print ('optimal objective function value is:% s'% BestIndi.ObjV [0] [0]] ) print ('optimal control variable value is:') for i in range (BestIndi.Phen.shape [1]): print (BestIndi.Phen [0) I]) else: print ('No feasible solution was found this time.') 3.3 results
The results of population evolution are as follows:
The final result is:
4. Multi-objective optimization problems with constraints
4.1 inheriting the Problem problem class to complete the description of the problem model
For the multi-objective problem, it is still the first to write the goal planning problem.
Import numpy as npimport geatpy as eaclass MyProblem (ea.Problem): # inherits the Problem parent class def _ _ init__ (self): name = 'BNH' # initialization name (function name) M = 2 # initialization M (target dimension) maxormins = [1] * M # initialization maxormins Dim = 2 # initialization Dim (decision variable dimension) varTypes = [0] * Dim # initialization varTypes (type of decision variable, 0: real number 1: integer) lb = [0] * Dim # decision variable lower bound ub = [5,3] # decision variable upper bound lbin = [1] * Dim # decision variable lower boundary ubin = [1] * Dim # call parent class construction method to instantiate ea.Problem.__init__ (self, name, M, maxormins, Dim, varTypes, lb Ub, lbin, ubin) def aimFunc (self, pop): # objective function Vars = pop.Phen # get the decision variable matrix x1 = Vars [:, [0]] # Note that the resulting x1 is a column vector X1 x2 = Vars [:, [1]] F1 = 4*x1**2 + 4*x2**2 f2 = (x1-5) * * 2 + (x2-5) * * 2 # adopt the feasibility law to deal with the constraint pop.CV = np.hstack ([(x1-5) * * 2 + x2constraints 2-25) -(x1-8) * * 2-(x2-3) * * 2 + 7.7]) # assign the obtained objective function value to the population pop ObjV pop.ObjV = np.hstack ([F1, f2]) # # the objective function mainly needs to calculate the CV and ObjV4.2 call algorithm template to solve the problem
Template solving is similar to single-objective programming.
Import geatpy as ea # import geatpyfrom ga_more_aim import MyProblem # Import Custom question Interface import numpy as np "" = instantiate problem object = "problem = MyProblem () # instantiate problem object" = population setting = "" Encoding = 'RI' # Encoding method NIND = 100 # population size Field = ea.crtfld (Encoding, problem.varTypes, problem.ranges,problem.borders) # create area descriptor population = ea.Population (Encoding, Field) NIND) # instantiate the population object (at this time the population has not really been initialized Just generate a population object) "" = algorithm parameter setting = "myAlgorithm = ea.moea_NSGA2_templet (problem, population) # instantiate an algorithm template object myAlgorithm.mutOper.Pm = 0.2 # modify the mutation probability of the mutation operator myAlgorithm.recOper.XOVR = 0.9 # modify the crossover probability of the crossover operator myAlgorithm.MAXGEN = 200 # maximum evolution algebra myAlgorithm.logTras = 1 # set the number of generations to log If set to 0, log is not recorded myAlgorithm.verbose = False # set whether to print out log information myAlgorithm.drawing = 1 # set drawing mode (0: do not draw 1: draw the result graph; 2: draw the target space process animation; 3: draw the decision space process animation) "" = call the algorithm template for population evolution = call run to execute the algorithm template to get the Pareto optimal solution set NDSet and the last generation population. NDSet is an object of population class Population. NDSet.ObjV is the objective function value of the optimal solution individual; NDSet.Phen is the corresponding decision variable value. For more information, see the definition of population classes in Population.py. [NDSet, population] = myAlgorithm.run () # execute the algorithm template to get the non-dominant population and the last generation population NDSet.save () # save the information of the non-dominant population in the file "" = = output result = = "print ('time:% s seconds'% myAlgorithm.passTime) print ('number of non-dominant individuals:% d'% NDSet.sizes) if NDSet.sizes! = 0 else print ('No feasible solution found!') If myAlgorithm.log is not None and NDSet.sizes! = 0: print ('GD', myAlgorithm.log [' gd'] [- 1]) print ('IGD', myAlgorithm.log [' igd'] [- 1]) print ('HV', myAlgorithm.log [' hv'] [- 1]) print ('Spacing', myAlgorithm.log [' spacing'] [- 1]) "" = tracking analysis of evolutionary process indicators = "metricName = ['igd'] ['hv']] Metrics = np.array ([myAlgorithm.log [metricamei] [0]] for i in range (len (metricName))] .T# draws the index tracking analysis chart ea.trcplot (Metrics, labels=metricName, titles=metricName) 4.3 results
Many beginners may not clearly evaluate some indicators of multi-objective programming, such as GD, IGD, HV, etc., here for your reference: the performance evaluation index summary of multi-objective evolutionary algorithm.
Pareto frontier results:
Trends in hv:
The final result:
The above is the content of this article on "how to solve the single / multi-objective programming problem of python genetic algorithm". I believe we all have a certain 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 follow 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.