genetic algorithm options
options for genetic algorithm
set options for ga
by using
optimoptions
.
options = optimoptions('ga','option1','value1','option2','value2');
some options are listed in
italics
. these options do not appear in the listing thatoptimoptions
returns. to see why 'optimoptions
hides these option values, see .ensure that you pass options to the solver. otherwise,
patternsearch
uses the default option values.[x,fval] = ga(fun,x0,a,b,aeq,beq,lb,ub,nonlcon,options)
plot options
plotfcn
specifies the plot function or functions called at each
iteration by ga
or gamultiobj
. set the
plotfcn
option to be a built-in plot function name or a
handle to the plot function. you can stop the algorithm at any time by clicking the
stop button on the plot window. for example, to display
the best function value, set options
as follows:
options = optimoptions('ga','plotfcn','gaplotbestf');
to display multiple plots, use a cell array of built-in plot function names or a cell array of function handles:
options = optimoptions('patternsearch',... 'plotfcn', {@plotfun1, @plotfun2, ...});
where @plotfun1
, @plotfun2
, and so on are
function handles to the plot functions. if you specify more than one plot function,
all plots appear as subplots in the same window. right-click any subplot to obtain a
larger version in a separate figure window.
available plot functions for ga
or for
gamultiobj
:
'gaplotscorediversity'
plots a histogram of the scores at each generation.'gaplotstopping'
plots stopping criteria levels.'gaplotgenealogy'
plots the genealogy of individuals. lines from one generation to the next are color-coded as follows:red lines indicate mutation children.
blue lines indicate crossover children.
black lines indicate elite individuals.
'gaplotscores'
plots the scores of the individuals at each generation.'gaplotdistance'
plots the average distance between individuals at each generation.'gaplotselection'
plots a histogram of the parents.'gaplotmaxconstr'
plots the maximum nonlinear constraint violation at each generation. forga
, available only when thenonlinearconstraintalgorithm
option is'auglag'
(default for non-integer problems). therefore, not available for integer-constrained problems, as they use the'penalty'
nonlinear constraint algorithm.you can also create and use your own plot function. structure of the plot functions describes the structure of a custom plot function. pass any custom function as a function handle.
the following plot functions are available for ga
only:
'gaplotbestf'
plots the best score value and mean score versus generation.'gaplotbestindiv'
plots the vector entries of the individual with the best fitness function value in each generation.'gaplotexpectation'
plots the expected number of children versus the raw scores at each generation.'gaplotrange'
plots the minimum, maximum, and mean score values in each generation.
the following plot functions are available for gamultiobj
only:
'gaplotpareto'
plots the pareto front for the first two or three objective functions.'gaplotparetodistance'
plots a bar chart of the distance of each individual from its neighbors.'gaplotrankhist'
plots a histogram of the ranks of the individuals. individuals of rank 1 are on the pareto frontier. individuals of rank 2 are lower than at least one rank 1 individual, but are not lower than any individuals from other ranks, etc.'gaplotspread'
plots the average spread as a function of iteration number.
structure of the plot functions
the first line of a plot function has this form:
function state = plotfun(options,state,flag)
the input arguments to the function are
options
— structure containing all the current options settings.state
— structure containing information about the current generation. the state structure describes the fields ofstate
.flag
— description of the stage the algorithm is currently in. for details, see output function options.
explains how to provide additional parameters to the function.
the output argument state
is a state structure as well.
pass the input argument, modified if you like; see changing the state structure. to stop the iterations, set
state.stopflag
to a nonempty character vector, such as
'y'
.
the state structure
ga. the state structure for ga
, which is an input
argument to plot, mutation, and output functions, contains the following
fields:
generation
— current generation number.starttime
— time when genetic algorithm started, returned bytic
.stopflag
— reason for stopping, a character vector.lastimprovement
— generation at which the last improvement in fitness value occurred.lastimprovementtime
— time at which last improvement occurred.best
— vector containing the best score in each generation.how
— the'auglag'
nonlinear constraint algorithm reports one of the following actions:'infeasible point'
,'update multipliers'
, or'increase penalty'
; see .funeval
— cumulative number of function evaluations.expectation
— expectation for selection of individuals.selection
— indices of individuals selected for elite, crossover, and mutation.population
— population in the current generation.score
— scores of the current population.nonlinineq
— nonlinear inequality constraints at current point, present only when a nonlinear constraint function is specified, there are no integer variables,flag
is not'interrupt'
, andnonlinearconstraintalgorithm
is'auglag'
.nonlineq
— nonlinear equality constraints at current point, present only when a nonlinear constraint function is specified, there are no integer variables,flag
is not'interrupt'
, andnonlinearconstraintalgorithm
is'auglag'
.evalelites
— logical value indicating whetherga
evaluates the fitness function of elite individuals. initially, this value istrue
. in the first generation, if the elite individuals evaluate to their previous values (which indicates that the fitness function is deterministic), then this value becomesfalse
by default for subsequent iterations. whenevalelites
isfalse
,ga
does not reevaluate the fitness function of elite individuals. you can override this behavior in a custom plot function or custom output function by changing the outputstate.evalelites
.haveduplicates
— logical value indicating whetherga
adds duplicate individuals for the initial population.ga
uses a small relative tolerance to determine whether an individual is duplicated or unique. ifhaveduplicates
istrue
, thenga
locates the unique individuals and evaluates the fitness function only once for each unique individual.ga
copies the fitness and constraint function values to duplicate individuals.ga
repeats the test in each generation until all individuals are unique. the test takes ordern*m*log(m)
operations, wherem
is the population size andn
is . to override this test in a custom plot function or custom output function, set the outputstate.haveduplicates
tofalse
.
gamultiobj. the state structure for gamultiobj
, which is an input
argument to plot, mutation, and output functions, contains the following
fields:
population
— population in the current generationscore
— scores of the current population, apopulation
-by-nobjectives
matrix, wherenobjectives
is the number of objectivesgeneration
— current generation numberstarttime
— time when genetic algorithm started, returned bytic
stopflag
— reason for stopping, a character vectorfuneval
— cumulative number of function evaluationsselection
— indices of individuals selected for elite, crossover, and mutationrank
— vector of the ranks of members in the populationdistance
— vector of distances of each member of the population to the nearest neighboring memberaveragedistance
— standard deviation (not average) ofdistance
spread
— vector where the entries are the spread in each generationmineq
— number of nonlinear inequality constraintsmeq
— number of nonlinear equality constraintsmall
— total number of nonlinear constraints,mall
=mineq
meq
c
— nonlinear inequality constraints at current point, apopulationsize
-by-mineq
matrixceq
— nonlinear equality constraints at current point, apopulationsize
-by-meq
matrixisfeas
— feasibility of population, a logical vector withpopulationsize
elementsmaxlininfeas
— maximum infeasibility with respect to linear constraints for the population
population options
population options let you specify the parameters of the population that the genetic algorithm uses.
populationtype
specifies the type of input to the fitness
function. types and their restrictions are:
'doublevector'
— use this option if the individuals in the population have typedouble
. also, the recommended data type for mixed integer programming is'doublevector'
, using the technique in .'doublevector'
is the default data type.'bitstring'
— you can use this option if the individuals in the population have components that are0
or1
.caution
the individuals in a
bit string
population are vectors of typedouble
, not strings or characters.for
creationfcn
andmutationfcn
, use'gacreationuniform'
and'mutationuniform'
or handles to custom functions. forcrossoverfcn
, use'crossoverscattered'
,'crossoversinglepoint'
,'crossovertwopoint'
, or a handle to a custom function.the
'bitstring'
data type can be awkward to use.ga
ignores all constraints, including bounds, linear constraints, and nonlinear constraints. you cannot use ahybridfcn
. to use binary variables most easily inga
, see .'custom'
— indicates a custom population type. in this case, you must also use a customcrossoverfcn
andmutationfcn
. you must provide either a custom creation function or aninitialpopulationmatrix
. you cannot use ahybridfcn
, andga
ignores all constraints, including bounds, linear constraints, and nonlinear constraints.
populationsize
specifies how many individuals there are in each
generation. with a large population size, the genetic algorithm searches the
solution space more thoroughly, thereby reducing the chance that the algorithm
returns a local minimum that is not a global minimum. however, a large population
size also causes the algorithm to run more slowly. the default is '50 when
numberofvariables <= 5, else 200'
.
if you set populationsize
to a vector, the genetic algorithm
creates multiple subpopulations, the number of which is the length of the vector.
the size of each subpopulation is the corresponding entry of the vector. note that
this option is not useful. see migration options.
creationfcn
specifies the function that creates the initial
population for ga
. choose from:
[]
uses the default creation function for your problem type.'gacreationuniform'
creates a random initial population with a uniform distribution. this is the default when there are no linear constraints, or when there are integer constraints. the uniform distribution is in the initial population range (initialpopulationrange
). the default values forinitialpopulationrange
are[-10;10]
for every component, or[-9999;10001]
when there are integer constraints. these bounds are shifted and scaled to match any existing boundslb
andub
.caution
do not use
'gacreationuniform'
when you have linear constraints. otherwise, your population might not satisfy the linear constraints.'gacreationlinearfeasible'
is the default when there are linear constraints and no integer constraints. this choice creates a random initial population that satisfies all bounds and linear constraints. if there are linear constraints,'gacreationlinearfeasible'
creates many individuals on the boundaries of the constraint region, and creates a well-dispersed population.'gacreationlinearfeasible'
ignoresinitialpopulationrange
.'gacreationlinearfeasible'
callslinprog
to create a feasible population with respect to bounds and linear constraints.for an example showing its behavior, see .
'gacreationnonlinearfeasible'
is the default creation function for the'penalty'
nonlinear constraint algorithm. for details, see constraint parameters.'gacreationuniformint'
is the default creation function forga
when the problem has integer constraints. this function applies an artificial bound to unbounded components, generates individuals uniformly at random within the bounds, and then enforces integer constraints.note
when your problem has integer constraints,
ga
andgamultiobj
enforce that integer constraints, bounds, and all linear constraints are feasible at each iteration. for nondefault mutation, crossover, creation, and selection functions,ga
andgamultiobj
apply extra feasibility routines after the functions operate.'gacreationsobol'
is the default creation function forgamultiobj
when the problem has integer constraints. the creation function uses a quasirandom sobol sequence to generate a well-dispersed initial population. the population is feasible with respect to bounds, linear constraints, and integer constraints.a function handle lets you write your own creation function, which must generate data of the type that you specify in
populationtype
. for example,options = optimoptions('ga','creationfcn',@myfun);
your creation function must have the following calling syntax.
function population = myfun(genomelength, fitnessfcn, options)
the input arguments to the function are:
genomelength
— number of independent variables for the fitness functionfitnessfcn
— fitness functionoptions
— options
the function returns
population
, the initial population for the genetic algorithm.explains how to provide additional parameters to the function.
caution
when you have bounds or linear constraints, ensure that your creation function creates individuals that satisfy these constraints. otherwise, your population might not satisfy the constraints.
initialpopulationmatrix
specifies an initial population for the
genetic algorithm. the default value is []
, in which case
ga
uses the default creationfcn
to
create an initial population. if you enter a nonempty array in the
initialpopulationmatrix
, the array must have no more than
populationsize
rows, and exactly nvars
columns, where nvars
is the number of variables, the second input
to ga
or gamultiobj
. if you have a
partial initial population, meaning fewer than
populationsize
rows, then the genetic algorithm calls
creationfcn
to generate the remaining individuals.
initialscorematrix
specifies initial scores for the initial
population. the initial scores can also be partial. if your problem has nonlinear
constraints then the algorithm does not use
initialscorematrix
.
initialpopulationrange
specifies the range of the vectors in
the initial population that is generated by the gacreationuniform
creation function. you can set initialpopulationrange
to be a
matrix with two rows and nvars
columns, each column of which has
the form [lb;ub]
, where lb
is the lower bound
and ub
is the upper bound for the entries in that coordinate. if
you specify initialpopulationrange
to be a 2-by-1 vector, each
entry is expanded to a constant row of length nvars
. if you do
not specify an initialpopulationrange
, the default is
[-10;10]
([-1e4 1;1e4 1]
for
integer-constrained problems), modified to match any existing bounds.
'gacreationlinearfeasible'
ignores
initialpopulationrange
. see for an example.
fitness scaling options
fitness scaling converts the raw fitness scores that are returned by the fitness function to values in a range that is suitable for the selection function.
fitnessscalingfcn
specifies the function that performs the
scaling. the options are
'fitscalingrank'
— the default fitness scaling function,'fitscalingrank'
, scales the raw scores based on the rank of each individual instead of its score. the rank of an individual is its position in the sorted scores. an individual with rank r has scaled score proportional to . so the scaled score of the most fit individual is proportional to 1, the scaled score of the next most fit is proportional to , and so on. rank fitness scaling removes the effect of the spread of the raw scores. the square root makes poorly ranked individuals more nearly equal in score, compared to rank scoring. for more information, see .'fitscalingprop'
— proportional scaling makes the scaled value of an individual proportional to its raw fitness score.'fitscalingtop'
— top scaling scales the top individuals equally. you can modify the top scaling using an additional parameter:options = optimoptions('ga',... 'fitnessscalingfcn',{@fitscalingtop,quantity})
quantity
specifies the number of individuals that are assigned positive scaled values.quantity
can be an integer from 1 through the population size or a fraction from 0 through 1 specifying a fraction of the population size. the default value is0.4
. each of the individuals that produce offspring is assigned an equal scaled value, while the rest are assigned the value 0. the scaled values have the form [01/n 1/n 0 0 1/n 0 0 1/n ...].'fitscalingshiftlinear'
— shift linear scaling scales the raw scores so that the expectation of the fittest individual is equal to a constant calledrate
multiplied by the average score. you can modify therate
parameter:options = optimoptions('ga','fitnessscalingfcn',... {@fitscalingshiftlinear, rate})
the default value of
rate
is2
.a function handle lets you write your own scaling function.
options = optimoptions('ga','fitnessscalingfcn',@myfun);
your scaling function must have the following calling syntax:
function expectation = myfun(scores, nparents)
the input arguments to the function are:
scores
— a vector of scalars, one for each member of the populationnparents
— the number of parents needed from this population
the function returns
expectation
, a column vector of scalars of the same length asscores
, giving the scaled values of each member of the population. the sum of the entries ofexpectation
must equalnparents
.explains how to provide additional parameters to the function.
see for more information.
selection options
selection options specify how the genetic algorithm chooses parents for the next generation.
the selectionfcn
option specifies the selection
function.
gamultiobj
uses only the
'selectiontournament'
selection function.
for ga
the options are:
'selectionstochunif'
— thega
default selection function,'selectionstochunif'
, lays out a line in which each parent corresponds to a section of the line of length proportional to its scaled value. the algorithm moves along the line in steps of equal size. at each step, the algorithm allocates a parent from the section it lands on. the first step is a uniform random number less than the step size.'selectionremainder'
— remainder selection assigns parents deterministically from the integer part of each individual's scaled value and then uses roulette selection on the remaining fractional part. for example, if the scaled value of an individual is 2.3, that individual is listed twice as a parent because the integer part is 2. after parents have been assigned according to the integer parts of the scaled values, the rest of the parents are chosen stochastically. the probability that a parent is chosen in this step is proportional to the fractional part of its scaled value.'selectionuniform'
— uniform selection chooses parents using the expectations and number of parents. uniform selection is useful for debugging and testing, but is not a very effective search strategy.'selectionroulette'
— roulette selection chooses parents by simulating a roulette wheel, in which the area of the section of the wheel corresponding to an individual is proportional to the individual's expectation. the algorithm uses a random number to select one of the sections with a probability equal to its area.'selectiontournament'
— tournament selection chooses each parent by choosingsize
players at random and then choosing the best individual out of that set to be a parent.size
must be at least 2. the default value ofsize
is4
. setsize
to a different value as follows:options = optimoptions('ga','selectionfcn',... {@selectiontournament,size})
when
nonlinearconstraintalgorithm
ispenalty
,ga
uses'selectiontournament'
with size2
.note
when your problem has integer constraints,
ga
andgamultiobj
enforce that integer constraints, bounds, and all linear constraints are feasible at each iteration. for nondefault mutation, crossover, creation, and selection functions,ga
andgamultiobj
apply extra feasibility routines after the functions operate.a function handle enables you to write your own selection function.
options = optimoptions('ga','selectionfcn',@myfun);
your selection function must have the following calling syntax:
function parents = myfun(expectation, nparents, options)
ga
provides the input argumentsexpectation
,nparents
, andoptions
. your function returns the indices of the parents.the input arguments to the function are:
expectation
for
ga
,expectation
is a column vector of the scaled fitness of each member of the population. the scaling comes from the fitness scaling options.tip
you can ensure that you have a column vector by using
expectation(:,1)
. for example,edit selectionstochunif
or any of the other built-in selection functions.for
gamultiobj
,expectation
is a matrix whose first column is the negative of the rank of the individuals, and whose second column is the distance measure of the individuals. see multiobjective options.
nparents
— number of parents to select.options
— genetic algorithmoptions
.
the function returns
parents
, a row vector of lengthnparents
containing the indices of the parents that you select.explains how to provide additional parameters to the function.
see for more information.
reproduction options
reproduction options specify how the genetic algorithm creates children for the next generation.
elitecount
specifies the number of individuals that are
guaranteed to survive to the next generation. set elitecount
to
be a positive integer less than or equal to the population size. the default value
is ceil(0.05*populationsize)
for continuous problems, and
0.05*(default populationsize)
for mixed-integer
problems.
crossoverfraction
specifies the fraction of the next
generation, other than elite children, that are produced by crossover. set
crossoverfraction
to be a fraction between
0
and 1
. the default value is
0.8
.
see "setting the crossover fraction" in for an example.
mutation options
mutation options specify how the genetic algorithm makes small random changes in
the individuals in the population to create mutation children. mutation provides
genetic diversity and enables the genetic algorithm to search a broader space.
specify the mutation function in the mutationfcn
option.
mutationfcn
options:
'mutationgaussian'
— the default mutation function forga
for unconstrained problems,'mutationgaussian'
, adds a random number taken from a gaussian distribution with mean 0 to each entry of the parent vector. the standard deviation of this distribution is determined by the parametersscale
andshrink
, and by theinitialpopulationrange
option. setscale
andshrink
as follows:options = optimoptions('ga','mutationfcn', ... {@mutationgaussian, scale, shrink})
the
scale
parameter determines the standard deviation at the first generation. if you setinitialpopulationrange
to be a 2-by-1 vectorv
, the initial standard deviation is the same at all coordinates of the parent vector, and is given byscale
*(v(2)-v(1))
.if you set
initialpopulationrange
to be a vectorv
with two rows andnvars
columns, the initial standard deviation at coordinatei
of the parent vector is given byscale
*(v(i,2) - v(i,1))
.the
shrink
parameter controls how the standard deviation shrinks as generations go by. if you setinitialpopulationrange
to be a 2-by-1 vector, the standard deviation at the kth generation, σk, is the same at all coordinates of the parent vector, and is given by the recursive formulaif you set
initialpopulationrange
to be a vector with two rows andnvars
columns, the standard deviation at coordinate i of the parent vector at the kth generation, σi,k, is given by the recursive formulaif you set
shrink
to1
, the algorithm shrinks the standard deviation in each coordinate linearly until it reaches 0 at the last generation is reached. a negative value ofshrink
causes the standard deviation to grow.
the default value of both
scale
andshrink
is 1.caution
do not use
mutationgaussian
when you have bounds or linear constraints. otherwise, your population will not necessarily satisfy the constraints. instead, use'mutationadaptfeasible'
or a custom mutation function that satisfies linear constraints.'mutationuniform'
— uniform mutation is a two-step process. first, the algorithm selects a fraction of the vector entries of an individual for mutation, where each entry has a probabilityrate
of being mutated. the default value ofrate
is0.01
. in the second step, the algorithm replaces each selected entry by a random number selected uniformly from the range for that entry.to change the default value of
rate
,options = optimoptions('ga','mutationfcn', {@mutationuniform, rate})
caution
do not use
mutationuniform
when you have bounds or linear constraints. otherwise, your population will not necessarily satisfy the constraints. instead, use'mutationadaptfeasible'
or a custom mutation function that satisfies linear constraints.'mutationadaptfeasible'
, the default mutation function forgamultiobj
and forga
when there are noninteger constraints, randomly generates directions that are adaptive with respect to the last successful or unsuccessful generation. the mutation chooses a direction and step length that satisfies bounds and linear constraints.'mutationpower'
is the default mutation function forga
andgamultiobj
when the problem has integer constraints. power mutation mutates a parent,x
, via the following. for each component of the parent, thei
th component of the child is given by:mutationchild(i) = x(i) - s(x(i) - lb(i))
ift < r
= x(i) s(ub(i) - x(i))
ift >= r
.here,
t
is the scaled distance ofx(i)
from thei
th component of the lower bound,lb(i)
.s
is a random variable drawn from a power distribution andr
is a random number drawn from a uniform distribution.this function can handle
lb(i) = ub(i)
. new children are generated with thei
th component set tolb(i)
, which equalsub(i)
. for more information on this crossover function see section 2.1 of the following reference:kusum deep, krishna pratap singsh, m. l. kansal, c. mohan. a real coded genetic algorithm for solving integer and mixed integer optimization problems. applied mathematics and computation, 212 (2009), 505–518.
note
when your problem has integer constraints,
ga
andgamultiobj
enforce that integer constraints, bounds, and all linear constraints are feasible at each iteration. for nondefault mutation, crossover, creation, and selection functions,ga
andgamultiobj
apply extra feasibility routines after the functions operate.'mutationpositivebasis'
— this mutation function is similar to orthogonal mads steps, modified for linear constraints and bounds.a function handle enables you to write your own mutation function.
options = optimoptions('ga','mutationfcn',@myfun);
your mutation function must have this calling syntax:
function mutationchildren = myfun(parents, options, nvars, fitnessfcn, state, thisscore, thispopulation)
the arguments to the function are
parents
— row vector of parents chosen by the selection functionoptions
— optionsnvars
— number of variablesfitnessfcn
— fitness functionstate
— structure containing information about the current generation. the state structure describes the fields ofstate
.thisscore
— vector of scores of the current populationthispopulation
— matrix of individuals in the current population
the function returns
mutationchildren
—the mutated offspring—as a matrix where rows correspond to the children. the number of columns of the matrix isnvars
.explains how to provide additional parameters to the function.
caution
when you have bounds or linear constraints, ensure that your mutation function creates individuals that satisfy these constraints. otherwise, your population will not necessarily satisfy the constraints.
crossover options
crossover options specify how the genetic algorithm combines two individuals, or parents, to form a crossover child for the next generation.
crossoverfcn
specifies the function that performs the
crossover. you can choose from the following functions:
'crossoverscattered'
, the default crossover function for problems without linear constraints, creates a random binary vector and selects the genes where the vector is a 1 from the first parent, and the genes where the vector is a 0 from the second parent, and combines the genes to form the child. for example, ifp1
andp2
are the parentsp1 = [a b c d e f g h] p2 = [1 2 3 4 5 6 7 8]
and the binary vector is [1 1 0 0 1 0 0 0], the function returns the following child:
child1 = [a b 3 4 e 6 7 8]
caution
when your problem has linear constraints,
'crossoverscattered'
can give a poorly distributed population. in this case, use a different crossover function, such as'crossoverintermediate'
.'crossoversinglepoint'
chooses a random integer n between 1 andnvars
and thenselects vector entries numbered less than or equal to n from the first parent.
selects vector entries numbered greater than n from the second parent.
concatenates these entries to form a child vector.
for example, if
p1
andp2
are the parentsp1 = [a b c d e f g h] p2 = [1 2 3 4 5 6 7 8]
and the crossover point is 3, the function returns the following child.
child = [a b c 4 5 6 7 8]
caution
when your problem has linear constraints,
'crossoversinglepoint'
can give a poorly distributed population. in this case, use a different crossover function, such as'crossoverintermediate'
.'crossovertwopoint'
selects two random integersm
andn
between1
andnvars
. the function selectsvector entries numbered less than or equal to
m
from the first parentvector entries numbered from
m 1
ton
, inclusive, from the second parentvector entries numbered greater than
n
from the first parent.
the algorithm then concatenates these genes to form a single gene. for example, if
p1
andp2
are the parentsp1 = [a b c d e f g h] p2 = [1 2 3 4 5 6 7 8]
and the crossover points are 3 and 6, the function returns the following child.
child = [a b c 4 5 6 g h]
caution
when your problem has linear constraints,
'crossovertwopoint'
can give a poorly distributed population. in this case, use a different crossover function, such as'crossoverintermediate'
.'crossoverintermediate'
, the default crossover function when there are linear constraints, creates children by taking a weighted average of the parents. you can specify the weights by a single parameter,ratio
, which can be a scalar or a row vector of lengthnvars
. the default value ofratio
is a vector of all 1's. set theratio
parameter as follows.options = optimoptions('ga','crossoverfcn', ... {@crossoverintermediate, ratio});
'crossoverintermediate'
creates the child fromparent1
andparent2
using the following formula.child = parent1 rand * ratio * ( parent2 - parent1)
if all the entries of
ratio
lie in the range [0, 1], the children produced are within the hypercube defined by placing the parents at opposite vertices. ifratio
is not in that range, the children might lie outside the hypercube. ifratio
is a scalar, then all the children lie on the line between the parents.'crossoverlaplace'
is the default crossover function when the problem has integer constraints. the laplace crossover generates children using either of the following formulae (chosen at random):xoverkid = p1 bl*abs(p1 – p2)
xoverkid = p2 bl*abs(p1 – p2)
here,
p1
,p2
are the parents ofxoverkid
andbl
is a random number generated from a . for more information on this crossover function see section 2.1 of the following reference:kusum deep, krishna pratap singsh, m. l. kansal, c. mohan. a real coded genetic algorithm for solving integer and mixed integer optimization problems. applied mathematics and computation, 212 (2009), 505–518.
'crossoverheuristic'
returns a child that lies on the line containing the two parents, a small distance away from the parent with the better fitness value in the direction away from the parent with the worse fitness value. you can specify how far the child is from the better parent by the parameterratio
. the default value ofratio
is 1.2. set theratio
parameter as follows.options = optimoptions('ga','crossoverfcn',... {@crossoverheuristic,ratio});
if
parent1
andparent2
are the parents, andparent1
has the better fitness value, the function returns the childchild = parent2 ratio * (parent1 - parent2);
caution
when your problem has linear constraints,
'crossoverheuristic'
can give a poorly distributed population. in this case, use a different crossover function, such as'crossoverintermediate'
.'crossoverarithmetic'
creates children that are the weighted arithmetic mean of two parents. children are always feasible with respect to linear constraints and bounds.note
when your problem has integer constraints,
ga
andgamultiobj
enforce that integer constraints, bounds, and all linear constraints are feasible at each iteration. for nondefault mutation, crossover, creation, and selection functions,ga
andgamultiobj
apply extra feasibility routines after the functions operate.a function handle enables you to write your own crossover function.
options = optimoptions('ga','crossoverfcn',@myfun);
your crossover function must have the following calling syntax.
xoverkids = myfun(parents, options, nvars, fitnessfcn, ... unused,thispopulation)
the arguments to the function are
parents
— row vector of parents chosen by the selection functionoptions
— optionsnvars
— number of variablesfitnessfcn
— fitness functionunused
— placeholder not usedthispopulation
— matrix representing the current population. the number of rows of the matrix ispopulationsize
and the number of columns isnvars
.
the function returns
xoverkids
—the crossover offspring—as a matrix where rows correspond to the children. the number of columns of the matrix isnvars
.explains how to provide additional parameters to the function.
caution
when you have bounds or linear constraints, ensure that your crossover function creates individuals that satisfy these constraints. otherwise, your population will not necessarily satisfy the constraints.
migration options
note
subpopulations refer to a form of parallel processing
for the genetic algorithm. ga
currently does not support
this form. in subpopulations, each worker hosts a number of individuals. these
individuals are a subpopulation. the worker evolves the subpopulation
independently of other workers, except when migration causes some individuals to
travel between workers.
because ga
does not currently support this form of
parallel processing, there is no benefit to setting
populationsize
to a vector, or to setting the
migrationdirection
, migrationinterval
,
or migrationfraction
options.
migration options specify how individuals move between subpopulations. migration
occurs if you set populationsize
to be a vector of length greater
than 1. when migration occurs, the best individuals from one subpopulation replace
the worst individuals in another subpopulation. individuals that migrate from one
subpopulation to another are copied. they are not removed from the source
subpopulation.
you can control how migration occurs by the following three options:
migrationdirection
— migration can take place in one or both directions.if you set
migrationdirection
to'forward'
, migration takes place toward the last subpopulation. that is, the nth subpopulation migrates into the (n 1)th subpopulation.if you set
migrationdirection
to'both'
, the nth subpopulation migrates into both the (n–1)th and the (n 1)th subpopulation.
migration wraps at the ends of the subpopulations. that is, the last subpopulation migrates into the first, and the first may migrate into the last.
migrationinterval
— specifies how many generation pass between migrations. for example, if you setmigrationinterval
to20
, migration takes place every 20 generations.migrationfraction
— specifies how many individuals move between subpopulations.migrationfraction
specifies the fraction of the smaller of the two subpopulations that moves. for example, if individuals migrate from a subpopulation of 50 individuals into a subpopulation of 100 individuals and you setmigrationfraction
to0.1
, the number of individuals that migrate is 0.1*50=5.
constraint parameters
constraint parameters refer to the nonlinear constraint solver. for details on the algorithm, see .
choose between the nonlinear constraint algorithms by setting the
nonlinearconstraintalgorithm
option to
'auglag'
(augmented lagrangian) or
'penalty'
(penalty algorithm).
augmented lagrangian genetic algorithm
initialpenalty
— specifies an initial value of the penalty parameter that is used by the nonlinear constraint algorithm.initialpenalty
must be greater than or equal to1
, and has a default of10
.penaltyfactor
— increases the penalty parameter when the problem is not solved to required accuracy and constraints are not satisfied.penaltyfactor
must be greater than1
, and has a default of100
.
penalty algorithm
the penalty algorithm uses the
'gacreationnonlinearfeasible'
creation function by
default. this creation function uses fmincon
to find
feasible individuals. 'gacreationnonlinearfeasible'
starts
fmincon
from a variety of initial points within the
bounds from the initialpopulationrange
option. optionally,
'gacreationnonlinearfeasible'
can run
fmincon
in parallel on the initial points.
you can specify tuning parameters for
'gacreationnonlinearfeasible'
using the following
name-value pairs.
name | value |
---|---|
solveropts | fmincon options, created using
optimoptions or
optimset . |
useparallel | when true , run
fmincon in parallel on initial points;
default is false . |
numstartpts | number of start points, a positive integer up to
sum(populationsize) in value. |
include the name-value pairs in a cell array along with
@gacreationnonlinearfeasible
.
options = optimoptions('ga','creationfcn',{@gacreationnonlinearfeasible
,...
'useparallel',true,'numstartpts',20});
multiobjective options
multiobjective options define parameters characteristic of the
gamultiobj
algorithm. you can specify the following
parameters:
paretofraction
— sets the fraction of individuals to keep on the first pareto front while the solver selects individuals from higher fronts. this option is a scalar between 0 and 1.note
the fraction of individuals on the first pareto front can exceed
paretofraction
. this occurs when there are too few individuals of other ranks in step 6 of .distancemeasurefcn
— defines a handle to the function that computes distance measure of individuals, computed in decision variable space (genotype, also termed design variable space) or in function space (phenotype). for example, the default distance measure function is'distancecrowding'
in function space, which is the same as{@distancecrowding,'phenotype'}
.“distance” measures a crowding of each individual in a population. choose between the following:
'distancecrowding'
, or the equivalent{@distancecrowding,'phenotype'}
— measure the distance in fitness function space.{@distancecrowding,'genotype'}
— measure the distance in decision variable space.@distancefunction
— write a custom distance function using the following template.function distance = distancefunction(pop,score,options) % uncomment one of the following two lines, or use a combination of both % y = score; % phenotype % y = pop; % genotype popsize = size(y,1); % number of individuals numdata = size(y,2); % number of dimensions or fitness functions distance = zeros(popsize,1); % allocate the output % compute distance here
gamultiobj
passes the population inpop
, the computed scores for the population inscores
, and the options inoptions
. your distance function returns the distance from each member of the population to a reference, such as the nearest neighbor in some sense. for an example, edit the built-in filedistancecrowding.m
.
hybrid function options
ga
hybrid function
a hybrid function is another minimization function that runs after the genetic
algorithm terminates. you can specify a hybrid function in the
hybridfcn
option. do not use with integer problems. the
choices are
[]
— no hybrid function.'fminsearch'
— uses the matlab® function to perform unconstrained minimization.'patternsearch'
— uses a pattern search to perform constrained or unconstrained minimization.'fminunc'
— uses the optimization toolbox™ function to perform unconstrained minimization.'fmincon'
— uses the optimization toolbox function to perform constrained minimization.
note
ensure that your hybrid function accepts your problem constraints.
otherwise, ga
throws an error.
you can set separate options for the hybrid function. use for
fminsearch
, or for
fmincon
, patternsearch
, or
fminunc
. for example:
hybridopts = optimoptions('fminunc','display','iter',... 'algorithm','quasi-newton');
options
as
follows:options = optimoptions('ga',options,'hybridfcn',{@fminunc,hybridopts});
hybridopts
must exist before you set options
.see hybrid scheme in the genetic algorithm for an example. see .
gamultiobj
hybrid function
a hybrid function is another minimization function that runs after the
multiobjective genetic algorithm terminates. you can specify the hybrid function
'fgoalattain'
in the hybridfcn
option.
in use as a multiobjective hybrid function, the solver does the following:
compute the maximum and minimum of each objective function at the solutions. for objective j at solution k, let
compute the total weight at each solution k,
compute the weight for each objective function j at each solution k,
for each solution k, perform the goal attainment problem with goal vector fk(j) and weight vector p(j,k).
for more information, see section 9.6 of deb .
stopping criteria options
stopping criteria determine what causes the algorithm to terminate. you can specify the following options:
maxgenerations
— specifies the maximum number of iterations for the genetic algorithm to perform. the default is100*numberofvariables
.maxtime
— specifies the maximum time in seconds the genetic algorithm runs before stopping, as measured bytic
andtoc
. this limit is enforced after each iteration, soga
can exceed the limit when an iteration takes substantial time.fitnesslimit
— the algorithm stops if the best fitness value is less than or equal to the value offitnesslimit
. does not apply togamultiobj
.maxstallgenerations
— the algorithm stops if the average relative change in the best fitness function value overmaxstallgenerations
is less than or equal tofunctiontolerance
. (if thestalltest
option is'geometricweighted'
, then the test is for a geometric weighted average relative change.) for a problem with nonlinear constraints,maxstallgenerations
applies to the subproblem (see ).for
gamultiobj
, if the geometric average of the relative change in the spread of the pareto solutions overmaxstallgenerations
is less thanfunctiontolerance
, and the final spread is smaller than the average spread over the lastmaxstallgenerations
, then the algorithm stops. the geometric average coefficient is ½. the spread is a measure of the movement of the pareto front. see .maxstalltime
— the algorithm stops if there is no improvement in the best fitness value for an interval of time in seconds specified bymaxstalltime
, as measured bytic
andtoc
.functiontolerance
— the algorithm stops if the average relative change in the best fitness function value overmaxstallgenerations
is less than or equal tofunctiontolerance
. (if thestalltest
option is'geometricweighted'
, then the test is for a geometric weighted average relative change.)for
gamultiobj
, if the geometric average of the relative change in the spread of the pareto solutions overmaxstallgenerations
is less thanfunctiontolerance
, and the final spread is smaller than the average spread over the lastmaxstallgenerations
, then the algorithm stops. the geometric average coefficient is ½. the spread is a measure of the movement of the pareto front. see .constrainttolerance
— theconstrainttolerance
is not used as stopping criterion. it is used to determine the feasibility with respect to nonlinear constraints. also,max(sqrt(eps),constrainttolerance)
determines feasibility with respect to linear constraints.
see for an example.
output function options
output functions are functions that the genetic algorithm calls at each
generation. unlike other solvers, a ga
output function can not
only read the values of the state of the algorithm, but also modify those values. an
output function can also halt the solver according to conditions you set.
options = optimoptions('ga','outputfcn',@myfun);
for multiple output functions, enter a cell array of function handles:
options = optimoptions('ga','outputfcn',{@myfun1,@myfun2,...});
to see a template that you can use to write your own output functions, enter
edit gaoutputfcntemplate
at the matlab command line.
for an example, see custom output function for genetic algorithm.
structure of the output function
your output function must have the following calling syntax:
[state,options,optchanged] = myfun(options,state,flag)
matlab passes the options
, state
,
and flag
data to your output function, and the output
function returns state
, options
, and
optchanged
data.
note
to stop the iterations, set state.stopflag
to a
nonempty character vector, such as 'y'
.
the output function has the following input arguments:
options
— optionsstate
— structure containing information about the current generation. the state structure describes the fields ofstate
.flag
— current status of the algorithm:'init'
— initialization state'iter'
— iteration state'interrupt'
— iteration of a subproblem of a nonlinearly constrained problem for the'auglag'
nonlinear constraint algorithm. whenflag
is'interrupt'
:the values of
state
fields apply to the subproblem iterations.ga
does not accept changes inoptions
, and ignoresoptchanged
.the
state.nonlinineq
andstate.nonlineq
fields are not available.
'done'
— final state
explains how to provide additional parameters to the function.
the output function returns the following arguments to
ga
:
state
— structure containing information about the current generation. the state structure describes the fields ofstate
. to stop the iterations, setstate.stopflag
to a nonempty character vector, such as'y'
.options
— options as modified by the output function. this argument is optional.optchanged
— boolean flag indicating changes tooptions
. to changeoptions
for subsequent iterations, setoptchanged
totrue
.
changing the state structure
caution
changing the state structure carelessly can lead to inconsistent or erroneous results. usually, you can achieve the same or better state modifications by using mutation or crossover functions, instead of changing the state structure in a plot function or output function.
ga
output functions can change the
state
structure (see the state structure). be careful when changing values in this
structure, as you can pass inconsistent data back to
ga
.
tip
if your output structure changes the population
field,
then be sure to update the score
field, and possibly the
best
, nonlinineq
, or
nonlineq
fields, so that they contain consistent
information.
to update the score
field after changing the
population
field, first calculate the fitness function
values of the population, then calculate the fitness scaling for the population.
see fitness scaling options.
display to command window options
'display'
specifies how much information is displayed at the
command line while the genetic algorithm is running. the available options
are
'final'
(default) — the reason for stopping is displayed.'off'
or the equivalent'none'
— no output is displayed.'iter'
— information is displayed at each iteration.'diagnose'
— information is displayed at each iteration. in addition, the diagnostic lists some problem information and the options that have been changed from the defaults.
both 'iter'
and 'diagnose'
display the
following information:
generation
— generation numberf-count
— cumulative number of fitness function evaluationsbest f(x)
— best fitness function valuemean f(x)
— mean fitness function valuestall generations
— number of generations since the last improvement of the fitness function
when a nonlinear constraint function has been specified, 'iter'
and 'diagnose'
do not display the mean f(x)
,
but additionally display:
max constraint
— maximum nonlinear constraint violation
in addition, 'iter'
and 'diagnose'
display
problem information before the iterative display, such as problem type and which
creation, mutation, crossover, and selection functions ga
or
gamultiobj
is using.
vectorize and parallel options (user function evaluation)
you can choose to have your fitness and constraint functions evaluated in serial,
parallel, or in a vectorized fashion. set the 'usevectorized'
and
'useparallel'
options with
optimoptions
.
when
'usevectorized'
isfalse
(default),ga
calls the fitness function on one individual at a time as it loops through the population. (this assumes'useparallel'
is at its default value offalse
.)when
'usevectorized'
istrue
,ga
calls the fitness function on the entire population at once, in a single call to the fitness function.if there are nonlinear constraints, the fitness function and the nonlinear constraints all need to be vectorized in order for the algorithm to compute in a vectorized manner.
see for an example.
when
useparallel
istrue
,ga
calls the fitness function in parallel, using the parallel environment you established (see ). setuseparallel
tofalse
(default) to compute serially.
note
you cannot simultaneously use vectorized and parallel computations. if you set
'useparallel'
to true
and
'usevectorized'
to true
,
ga
evaluates your fitness and constraint functions in a
vectorized manner, not in parallel.
how fitness and constraint functions are evaluated
usevectorized =
false | usevectorized =
true | |
---|---|---|
useparallel = false | serial | vectorized |
useparallel = true | parallel | vectorized |