MATLAB ga函数的使用方法
一、ga句法结构
x = ga(fitnessfcn,nvars)
x = ga(fitnessfcn,nvars,A,b)
x = ga(fitnessfcn,nvars,A,b,Aeq,beq)
x = ga(fitnessfcn,nvars,A,b,Aeq,beg,IB,UB)
x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon)
x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon,options)
x = ga(fitnessfcn,nvars,A,b,[],[],LB,UB,nonlcon,IntCon)
x = ga(fitnessfcn,nvars,A,b,[],[],LB,UB,nonlcon,IntCon,options)
x = ga(problem)
[x,fval] = ga(fitnessfcn,nvars,...)
[x,fval,exitflag] = ga (fitnessfcn,nvars,...)
[x,fval,exitflag,output] = ga(fitnessfcn,nvars,...)
[x,fval,exitflag,output,population] = gafitnessfcn,nvars,...)
[x,fval,exitflag,output,population,scores] = ga(fitnessfcn,nvars,...)
二、释义及解读
- fitnessfcn 为适应度句柄函数(即:目标函数);
- nvars 为目标函数自变量的个数;
- options 为算法的属性设置,该属性是通过函数gaoptimset赋予的;
- x 为经过遗传进化以后自变量最佳染色体返回值;
- fval 为最佳染色体的适应度;
- exitflag 为算法停止的原因;
-
output 为输出的算法结构;
-
population 为最终得到种群适应度的列向量(即当前群体,而群体里性能最好的个体,便是最优值点);
-
scores 为最终得到的种群(即:最优值点的目标函数取值);
-
A A A 与 b b b:线性不等式约束 A ∗ x ≤ b A*x\leq b A∗x≤b 中的矩阵;
(Note: If the problem has m linear inequality constraints and nvars variables. then A is a matrix of size m-by-nvars and b is a vector of length m. ga evaluates the matrix product A*x as if x is transposed (Ax’). ) -
A e q Aeq Aeq 与 b e q beq beq:线性等式约束 A e q ∗ x = b e q Aeq*x=beq Aeq∗x=beq 中的矩阵;
(Note: ga does not enforce linear constraints to be satisfied when the PopulationType option is ‘bitstring’ or ‘custom’.) -
nonlcon:非线性约束,该函数返回两个输出,即:[g,h] = nonlcon(x) ,g为非线性不等式约束,所有的不等式约束均以列向量的形式存在变量g中。h为非线性等式约束,也以列向量的形式存储。非线性约束中[g,h]使用规则与我另一篇博客MATLAB fmincon函数 进阶资料(磕盐记录)一样,这里不展开叙述了。 需要注意:ga atempts to achieve g = 0 g = 0 g=0 and h = 0 h= 0 h=0. g g g and h are row vectors when there are multiple constraints. Set unused outputs to g = [ ] or h = [ ].
-
IntCon:若变量 x 中存在整数变量,则在这里设置!具体地,IntCon 是由正数整数组成的向量,取值从 1 到 nvars,IntCon 中的每个值代表决策变量 x 中相应位置的索引变量是整数变量。
(Note: When IntCon is nonempty, Aeq and beq must be empty ([ ]), and nonlcon must return empty for ceq. For more information on integer programming, see Mixed Integer Optimizaton.) -
options:Create options using gaoptimset. 下一章节将详细介绍 options 中关于 gaoptimset 的设置规则。
三、gaoptimset 介绍(初级)
gaoptimset 常用来设置 options 中的各个选项,其句式结构如下:
options = gaoptimset('param1',value1,'param2',value2,...)
其中, ‘Param1’、 ‘Param2’等是需要设定的参数,比如:种群规模(PopulationSize)、交叉比例(CrossoverFraction)等,value1、value2等则是Param的具体值,常用的参数名如下表:
设定的参数名(Param名) | 说明 | 默认值 |
---|---|---|
CrossoverFraction | 交叉比例 | 0.8 |
Generations | 算法中止的最大迭代次数 | 100 |
PopulationSize | 种群规模 | 20 |
MigrationFraction | 变异概率 | 0.2 |
FitnessLimit | 当适应度函数达到设定的值时算法中止 | - |
StallGenLimit | 当超过StallGenLimit代适应度函数为改善时,算法中止 | 50 |
更多参数设定详见 MATLAB 官方文档,可在MATLAB命令窗口中输入 “doc gaoptimset” 查看 [2]:
或参见本博客“第六节”。
四、实例运行
实例原始网址: MATLAB利用遗传算法函数求目标函数的最优解
- 目标函数如下:
function f = myfit( x )
f = (339-0.01*x(1)-0.003*x(2))*x(1)...
+ (399-0.004*x(1)-0.01*x(2))*x(2)...
- (400000+195*x(1)+225*x(2));
f = -f; %因为GA是寻找最小值,所以为了求这个函数的最大值,取f的相反数
end
- 主函数如下:
options = gaoptimset();
options.Generations = 2000; %最大迭代数设为2000
% 当然,如果有很多参数都需要设置时,可以按照 options = gaoptimset('param1',value1,'param2',value2,...) 的形式统一设置
% options = gaoptimset('PopulationSize', 20, ... % 种群包含个体数目
% 'EliteCount', 10, ... % 种群中精英个体数目
% 'CrossoverFraction', 0.75, ... % 交叉后代比率
% 'Generations', 500, ... % 迭代代数
% 'StallGenLimit', 500, ... % 停止代数
% 'TolFun', 1e-100, ... % 适应度函数偏差
% 'PlotFcns', {@gaplotbestf, @gaplotbestindiv, @gaplotstopping}); % 绘制最优个体适应度函数与最优个体
[X,FVAL,EXITFLAG,OUTPUT] =ga(@myfit, 2 ,[], [],[],[],[],[],[],[],options)
运行结果为:
EXITFLAG 返回值为1,说明所求结果无特殊情况。
需要注意的是:如果 options.Generations 不设为 2000,采用默认迭代100轮来运行上述代码,则运行结果如下图所示:
注意到此时,EXITFLAG 返回值为0,显示信息为:Optimization terminated: maximum number of generations exceeded.
即:达到最大迭代轮数,此时的结果与最优理想结果相差甚远。由此例可知,关于最大迭代次数的设定,一定要小心,务必满足迭代次数的要求!
五、关于 exitflag 取值的说明(重要)
前文给出了 exitflag 取值的一个表格,说明了 GA 停止运行的原因 [3],这几类原因可概括为 exitflag 取值为以下三种情况:
- exitflag 为正值:意味着 GA 认为它做得相当好,有特定的理由停止运行
- exitflag = -2:无可行解,你肯定没有得到有用的答案
- exitflag 取其他情况时:意味着 GA 认为如果让它运行更长时间,你可能会得到更好的解决方案。 它没有在函数值中看到停止的具体原因,但它遇到了你设置的资源限制。
更详细的原因,可解释为 [3]:
- As I know, good solution is when it converges, the change of few last iteration does not improves (exit flag 1, 3). Or when solution meets your specified value (exit flag 5).
- And not so good solution is if it stops due to max time/iteration (exit flag 0, -4, -5), means it may not converge. It may gives better solution when you increase those limits. Or when the solution change is smaller than matlab capability (exit flag 4), this means you may need to improve your objective function.
- Clearly bad solution is when no solution is found (exit flag -2).
六、gaoptimset 详述(进阶)
options 选项在 GA 函数中,是以结构体的形式存在,该结构体包含哪些变量呢?在第四节中介绍了几个常见的变量,我将在本节详细介绍所有变量,以及各变量的作用。
首先,在MATLAB命令窗口中输入下述命令:
gaoptimset(@ga)
显示结果如下:
上述结果中,每一行都对应一个可设置的参数项(左侧是变量名,右侧是默认取值)
各变量名的详细解读:
-
大括号 { } 中的值表示默认值;
-
{ }* 表示当问题具有线性约束且 MutationFcn 有边界时的默认值;
-
I* 表示 ga 以不同的方式处理整数约束的选项; 此表示法不适用于 gamultiobj;
-
NM 表示该选项不适用于 GA 的多目标优化问题中(gamultiobj)。
序号 | Option | Description | Values |
---|---|---|---|
1 | ConstraintTolerance | 确定了非线性约束的可行性。此外,max(sqrt(eps),Constraint Tolerance) 确定了线性约束的可行性. (我理解,此参数表示约束违反的精度误差) For an options structure, use TolCon. | Positive scalar | {1e-3} |
2 | CreationFcn | 创建初始种群的函数。 指定为内置创建函数或函数句柄的名称。See Population Options. | {‘gacreationuniform’}|{‘gacreationlinearfeasible’}* |‘gacreationnonlinearfeasible’ |{‘gacreationuniformint’}I* for ga | {‘gacreationsobol’}I* for gamultiobj | Custom creation function |
3 | CrossoverFcn | 算法用于创建交叉子代(crossover children)的函数。 指定为内置交叉函数或函数句柄的名称。See Crossover Options. | {‘crossoverscattered’} for ga, {‘crossoverintermediate’}* for gamultiobj |{‘crossoverlaplace’}I* | ‘crossoverheuristic’ |‘crossoversinglepoint’ | ‘crossovertwopoint’ | ‘crossoverarithmetic’| Custom crossover function |
4 | CrossoverFraction | 交叉函数产生的下一代人口比例(不包括精英子代) | Positive scalar | {0.8} |
5 | Display | Level of display. | ‘off’ | ‘iter’ |‘diagnose’ | {‘final’} |
6 | DistanceMeasureFcn | 计算个体距离度量的函数。 指定为内置距离测量函数或函数句柄的名称。 The value applies to the decision variable or design space (genotype) or to function space (phenotype). The default ‘distancecrowding’ is in function space (phenotype). For gamultiobj only. See Multiobjective Options. For an options structure, use a function handle, not a name. | {‘distancecrowding’} means the same as {@distancecrowding,‘phenotype’} | {@distancecrowding,‘genotype’} | Custom distance function |
7 | EliteCount | NM 指定当前一代中有多少个体可以保证生存到下一代,必须是正整数。Not used in gamultiobj. | Positive integer | {ceil(0.05PopulationSize)} | {0.05(default PopulationSize)} for mixed-integer problems |
8 | FitnessLimit | NM 如果适应度函数达到 FitnessLimit 的值,算法将停止。(我理解,这个函数设定不取默认的 -inf ,则最后输出的 exitflag 的取值应该是 5) | Scalar | {-Inf} |
9 | FitnessScalingFcn | 该函数用以缩放适应度函数值。 指定为内置缩放函数或函数句柄的名称。 Option unavailable for gamultiobj. | {‘fitscalingrank’} | ‘fitscalingshiftlinear’ | ‘fitscalingprop’ | ‘fitscalingtop’ | Custom fitness scaling function |
10 | FunctionTolerance | (与表格第17项关联)翻译: 如果 MaxStallGenerations 代以后,最佳适应度函数值的平均相对变化小于或等于 FunctionTolerance,则算法停止。 如果 StallTest 为“geometricWeighted”,则当加权平均相对变化小于或等于 FunctionTolerance 时,算法将停止。原文: The algorithm stops if the average relative change in the best fitness function value over MaxStallGenerations generations is less than or equal to FunctionTolerance. If StallTest is ‘geometricWeighted’, then the algorithm stops if the weighted average relative change is less than or equal to FunctionTolerance. For gamultiobj, the algorithm stops when the geometric average of the relative change in value of the spread over options.MaxStallGenerations generations is less than options.FunctionTolerance, and the final spread is less than the mean spread over the past options.MaxStallGenerations generations. See gamultiobj Algorithm. For an options structure, use TolFun. | Positive scalar | {1e-6} for ga, {1e-4} for gamultiobj |
11 | HybridFcn | I* 翻译: ga 终止后继续优化的函数。 指定为名称或函数句柄。 原文: Function that continues the optimization after ga terminates. (我理解,此参数用以保留当前子代,留之用以在此子代的基础上二次优化) Alternatively, a cell array specifying the hybrid function and its options. See ga Hybrid Function. For gamultiobj, the only hybrid function is @fgoalattain. See gamultiobj Hybrid Function. When the problem has integer constraints, you cannot use a hybrid function. See When to Use a Hybrid Function. | Function name or handle | ‘fminsearch’ | ‘patternsearch’ | ‘fminunc’ | ‘fmincon’ | {[]} or 1-by-2 cell array |
12 | InitialPenalty | NM I* Initial value of the penalty parameter | Positive scalar | {10} |
13 | InitialPopulationMatrix | 调用遗传算法的初始Population。 最多具有 “PopulationSize ” 行 N 列,其中 N 是变量数。 您可以传递部分Population,即行数少于 PopulationSize 的总体。 在这种情况下,遗传算法使用 CreationFcn 来生成剩余的Population。See Population Options. For an options structure, use InitialPopulation. | Matrix | {[]} |
14 | InitialPopulationRange | 指定初始Population中个体的范围,该参数是一个矩阵或向量。 适用于 gacreationuniform 创建功能。ga shifts and scales the default initial range to match any finite bounds. For an options structure, use PopInitRange. | Matrix or vector | {[-10;10]} for unbounded components, {[-1e4+1;1e4+1]} for unbounded components of integer-constrained problems, {[lb;ub]} for bounded components, with the default range modified to match one-sided bounds |
15 | InitialScoresMatrix | Initial scores used to determine fitness. 最多有“PopulationSize ”行和 Nf 列,其中 Nf 是适应度函数的数量(即:单目标的 ga 函数中为 1,多目标的 gamultiobj 函数则大于 1)。 You can pass a partial scores matrix, meaning one with fewer than PopulationSize rows. In that case, the solver fills in the scores when it evaluates the fitness functions. For an options structure, use InitialScores. | Column vector for single objective| matrix for multiobjective | {[]} |
16 | MaxGenerations | (重要!!!) 算法停止之前的最大迭代次数。 For an options structure, use Generations. | Positive integer | {100numberOfVariables} for ga, {200numberOfVariables} for gamultiobj |
17 | MaxStallGenerations | The algorithm stops if the average relative change in the best fitness function value over MaxStallGenerations generations is less than or equal to FunctionTolerance. If StallTest is ‘geometricWeighted’, then the algorithm stops if the weighted average relative change is less than or equal to FunctionTolerance. For gamultiobj, the algorithm stops when the geometric average of the relative change in value of the spread over options.MaxStallGenerations generations is less than options.FunctionTolerance, and the final spread is less than the mean spread over the past options.MaxStallGenerations generations. See gamultiobj Algorithm. For an options structure, use StallGenLimit. | Positive integer | {50} for ga, {100} for gamultiobj |
18 | MaxStallTime | NM 如果目标函数在 MaxStallTime 秒(通过 tic 和 toc 测量)内没有改善,则算法停止。 For an options structure, use StallTimeLimit. | Positive scalar | {Inf} |
19 | MaxTime | 算法在运行 MaxTime 秒后停止(通过 tic 和 toc 测量)。 每次迭代后都会强制执行此限制,因此当迭代花费大量时间时 ga 可能会超出此限制。 For an options structure, use TimeLimit. | Positive scalar | {Inf} |
20 | MigrationDirection | Direction of migration. See Migration Options. | ‘both’ | {‘forward’} |
21 | MigrationFraction | Scalar from 0 through 1 specifying the fraction of individuals in each subpopulation that migrates to a different subpopulation. See Migration Options. | Scalar | {0.2} |
22 | MigrationInterval | 翻译: 指定了个体(individuals )在 subpopulations之间迁移之间发生的代数,该参量是正整数。原文: Positive integer specifying the number of generations that take place between migrations of individuals between subpopulations. See Migration Options. | Positive integer | {20} |
23 | MutationFcn | Function that produces mutation children. Specify as a name of a built-in mutation function or a function handle. See Mutation Options. | {‘mutationgaussian’} for ga without constraints | {‘mutationadaptfeasible’}* for gamultiobj and for ga with constraints | {‘mutationpower’}I* | ‘mutationpositivebasis’ | ‘mutationuniform’ | Custom mutation function |
24 | NonlinearConstraintAlgorithm | Nonlinear constraint algorithm. See Nonlinear Constraint Solver Algorithms for Genetic Algorithm. Option unchangeable for gamultiobj. For an options structure, use NonlinConAlgorithm. | {‘auglag’} for ga, {‘penalty’} for gamultiobj |
25 | OutputFcn | 翻译: ga 在每次迭代时调用的函数。 原文: Functions that ga calls at each iteration. Specify as a function handle or a cell array of function handles. See Output Function Options. For an options structure, use OutputFcns. | Function handle or cell array of function handles | {[]} |
26 | ParetoFraction | Scalar from 0 through 1 specifying the fraction of individuals to keep on the first Pareto front while the solver selects individuals from higher fronts, for gamultiobj only. See Multiobjective Options. | Scalar | {0.35} |
27 | PenaltyFactor | NM I* Penalty update parameter. | Positive scalar | {100} |
28 | PlotFcn | Function that plots data computed by the algorithm. Specify as a name of a built-in plot function, a function handle, or a cell array of built-in names or function handles. See Plot Options. For an options structure, use PlotFcns. | ga or gamultiobj: {[]} | ‘gaplotdistance’ | ‘gaplotgenealogy’ | ‘gaplotselection’ | ‘gaplotscorediversity’ | ‘gaplotscores’ | ‘gaplotstopping’ | ‘gaplotmaxconstr’ | Custom plot function ga only: ‘gaplotbestf’ | ‘gaplotbestindiv’ | ‘gaplotexpectation’ | ‘gaplotrange’ gamultiobj only: ‘gaplotpareto’ | ‘gaplotparetodistance’ | ‘gaplotrankhist’ | ‘gaplotspread’ |
29 | PlotInterval | Positive integer specifying the number of generations between consecutive calls to the plot functions. | Positive integer | {1} |
30 | PopulationSize | (重要!!!) Size of the population. | Positive integer | {50} when numberOfVariables <= 5, {200} otherwise |{min(max(10*nvars,40),100)} for mixed-integer problems |
31 | PopulationType | Data type of the population. Must be ‘doubleVector’ for mixed-integer problems. | ‘bitstring’ | ‘custom’ | {‘doubleVector’} ga ignores all constraints when PopulationType is set to ‘bitString’ or ‘custom’. See Population Options. |
32 | SelectionFcn | Function that selects parents of crossover and mutation children. Specify as a name of a built-in selection function or a function handle. gamultiobj uses only ‘selectiontournament’. | {‘selectionstochunif’} for ga, {‘selectiontournament’} for gamultiobj | ‘selectionremainder’ | ‘selectionuniform’ | ‘selectionroulette’ | Custom selection function |
33 | StallTest | NM Stopping test type. | ‘geometricWeighted’ | {‘averageChange’} |
34 | UseParallel | Compute fitness and nonlinear constraint functions in parallel. See Vectorize and Parallel Options (User Function Evaluation) and How to Use Parallel Processing in Global Optimization Toolbox. | true | {false} |
35 | UseVectorized | Specifies whether functions are vectorized. See Vectorize and Parallel Options (User Function Evaluation) and Vectorize the Fitness Function. For an options structure, use Vectorized with the values ‘on’ or ‘off’. | true | {false} |
注:上表内容为部分翻译版本,因为担心自己的翻译失真于原始文献,所以表格中会存在中英文混写的情况,完整版的英文原文参见 [2]
参考网址:
更多推荐
所有评论(0)