matlab遗传算法学习和全局化算法
更新时间:2023-10-05 03:54:01 阅读量:3 综合文库 文档下载
- Matlab遗传算法推荐度:
- 相关推荐
1 遗传算法步骤
1 根据具体问题选择编码方式,随机产生初始种群,个体数目一定,每个个体表现为染色体的基因编码
2 选择合适的适应度函数,计算并评价群体中各个体的适应。
3 选择(selection)。根据各个个体的适应度,按照一定的规则或方法,从当前群体中选择出一些优良的个体遗传到下一代群体
4 交叉(crossover)。将选择过后的群体内的各个个体随机搭配成对,对每一对个体,以一定概率(交叉概率)交换它们中的部分基因。
5 变异(mutation)。对交叉过后的群体中的每一个个体,以某个概率(称为变异概率)改n 变某一个或某一些基因位上的基因值为其他的等位基因
6 终止条件判断。若满足终止条件,则以进化过程中得到的具有最大适应度的个体作为最优解输出,终止运算。否则,迭代执行Step2 至Step5。
适应度是评价群体中染色体个体好坏的标准,是算法进化的驱动力,是自然选择的唯一依据,改变种群结构的操作皆通过适应度函数来控制。在遗传算法中,以个体适应度的大小来确定该个体被遗传到下一代群体中的概率。个体的适应度越大,被遗传到下一代的概率就越大,相反,被遗传到下一代的概率就越小。
1 [a,b,c]=gaopt(bound,fun)其中,bound=[xm,xM]为求解区间上届和下届构成的矩阵。Fun为用户编写的函数。a为搜索的结果向量,由搜索的出的最优x向量与目标函数构成,b为最终搜索种群,c为中间搜索过程变参数,其第一列为代数,后边列分别为该代最好的的个体与目标函数的值,可以认为寻优的中间结果。
2 ga函数。[X,F, FLAG,OUTPUT] = GA(fun, n,opts).n为自变量个数,opts为遗传算法控制选项,用gaoptimset()函数设置各种选项,InitialPopulation可以设置初始种群,用PopulationSize可以设置种群规模,SelectionFcn可以定义选择函数,
3 gatool 函数用于打开,GATOOL is now included in OPTIMTOOL。 2.2 通过GUI 使用遗传算法
在Matlab 工作窗口键入下列命令>>gatool, 或通过Start 打开其下子菜单Genetic Algorithm Tool,如图1。只要在相应的窗格选择相应的选项便可进行遗传算法的计算。其中fitnessfun 窗格为适应度函数, 填写形式为@fitnessfun,Number of variable 窗格为变量个数。其它窗格参数根据情况填入。填好各窗格内容,单击Start 按钮,便可运行遗传算法 例子1 应用实例
已知某一生物的总量y(单位:万个)与时间t(月)之间的关系为y=k0(1-exp(-k1*t)), 统计十个月得到数据见表1,试求关系式中的k0,k1。先编写目标函数,并以文件名myfung.m
存盘。
function y=myfung(x)
TOT=[2.0567 3.6904 4.9881 6.0189 6.8371 7.4881 8.0047 8.4151 8.7411 9.0000]; t=1:10;[r,s]=size(TOT);y=0; for i=1:s
y=y+(TOT(i)-x(:,1)*(1-exp(-x(:,2)*t(i))))^2 %最小估计原则 end
打开遗传算法的GUI,在Fitness function 窗格中输入@myfung,在Number of variables 窗格中输入数字2,在Stopping criteria 选项中设置generations 为300,fitness limit 为0.001,stall generations 为100,其它参数为缺省值,然后单击Start 运行遗传算法得到k0=9.99559,k1=0.23018,即 例子2
2 matlab 7 GA工具箱_木子一车(转载)
例子1求f?21.5?x1sin(4?pi?x1)?x2?sin(20?pi?x2)的最大值;也就是求负函数的最小值 最大值为-38.8503,在点 xmin=[11.6255 5.7250];
clear
f=@(x1,x2)(-(21.5+x1.*sin(4*pi*x1)+x2.*sin(20*pi*x2))) t1=-3:0.1:12.1; t2=4:1.8/(length(t1)-1):5.8;
[x,y]=meshgrid(t1,t2); mesh(x,y,f(x,y)) 方法1 遗传算法
f=@(x)-(21.5+x(1)*sin(4*pi*x(1))+x(2)*sin(20*pi*x(2))); opt1 = gaoptimset;
opt1.PopInitRange = [[-3.0 4.1];[12.1 5.8]]; opt1.PopulationSize = 1000;
opt1.MutationFcn=@mutationuniform; [x, fval] = ga(f,2,opt1)
[x,fval] = ga(f,2,[],[],[],[], [-3.0;4.1],[12.1;5.8]); 方法2 gatool 的用法
在matlab7命令行输入 gatool,见附图。
在 PopulationSize=10000; 请注意Mutation函数的选择。 f(x1*,x2*)=-my_func1(x1*,x2*)=38.84741978236206, where x1*=11.62378; x2*=5.72501 方法3 全局优化算法
gs = GlobalSearch('Display','iter');
f=@(x)-(21.5+x(1)*sin(4*pi*x(1))+x(2)*sin(20*pi*x(2))); opts = optimset('Algorithm','interior-point');
problem = createOptimProblem('fmincon','objective',f,'x0',[1/2 1/3],'lb',[-3 4.1],'ub',[12.1 5.8],'options',opts);
[xming,fming,flagg,outptg,manyminsg] = run(gs,problem) 方法4 multistart 方法
ms =MultiStart('TolFun',1e-10,'TolX',1e-10); opts=optimset('Algorithm', 'interior-point');
f=@(x)-(21.5+x(1)*sin(4*pi*x(1))+x(2)*sin(20*pi*x(2)));
problem=createOptimProblem('fmincon','x0',[0,0],'objective',f,'lb',[-3,4.1],'ub',[12.1,5.8],'options',opts);
[xminm,fminm,flagm,outptm,someminsm]=run(ms,problem,300); %stpoints=RandomStartPointSet;%默认产生10个起始点 此方法得不到最优解;
查看局部解的分布范围 enter hist([someminsm.Fval]).
方法4.1 对上个方法的改进;首先根据上个方法搜索的最佳点,取现在的方法的搜索范围为上个最优解的周围区域,缩小搜索范围 clear
ms=MultiStart;
opts=optimset('Algorithm','interior-point');
f=@(x)(-(21.5+x(1).*sin(4*pi*x(1))+x(2).*sin(20*pi*x(2))));
problem=createOptimProblem('fmincon','x0',[12,5],'objective',f,'lb',[10,4],'ub',[12.1,5.8],'options',opts);
[xminm,fminm,flagm,outptm,manyminsm]=run(ms,problem,200) xminm = 11.6255 5.7250 fminm = -38.8503
flagm = 1
outptm = funcCount: 8660 localSolverTotal: 200 localSolverSuccess: 200 localSolverIncomplete: 0 localSolverNoSolution: 0
message: [1x129 char] manyminsm = 1x78 GlobalOptimSolution Properties: X Fval Exitflag Output
X0
方法4.2
pts = -4*rand(200,2) + 13*rand(200,2); tpoints = CustomStartPointSet(pts);
rpts = RandomStartPointSet('NumStartPoints',200); allpts = {tpoints,rpts}; ms=MultiStart;
opts=optimset('Algorithm', 'interior-point','LargeScale','off'); f=@(x)(-(21.5+x(1).*sin(4*pi*x(1))+x(2).*sin(20*pi*x(2))));
problem=createOptimProblem('fmincon','x0',[12.1,5.6],'objective',f,'lb',[9,4],'ub',[12.1,5.8],'options',opts);
[xmin,fmin,flag,outpt,allmins] = run(ms,problem,allpts)
3 【问题】求f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中0<=x<=9 f=@(x)-(x+10*sin(5*x)+7*cos(4*x)); fplot(f,[0 9]); [x,fv]=ga(f,[0;9])
options = gaoptimset('PopulationSize', 100)
[x fval]=ga(@fitnessfun,nvars,[],[],[],[],[],[lb],[ub],options); x = ga(fitnessfcn,nvars,A,b,Aeq,beq,LB,UB,nonlcon,options);
nvars为变量数目,
5 全局化算法 (GlobalSearch)
createOptimProblem
problem = createOptimProblem('solverName','ParameterName',ParameterValue,...) Parameter Name/Value Pairs Aeq
Matrix for linear equality constraints. The
Aineq
beq
bineq
lb nonlcon
objective
options
ub
constraints have the form: Aeq x = beq
Matrix for linear inequality constraints. The constraints have the form: Aineq x ≤ bineq
Vector for linear equality constraints. The constraints have the form: Aeq x = beq
Vector for linear inequality constraints. The constraints have the form: Aineq x ≤ bineq Vector of lower bounds.
Function handle to the nonlinear constraint function. The constraint function must accept a vector x and return two vectors: c, the nonlinear inequality constraints, and ceq, the nonlinear equality constraints. If one of these constraint functions is empty, nonlcon must return [] for that function.
If the GradConstr option is 'on', then in addition nonlcon must return two additional outputs, gradc and gradceq. The gradc parameter is a matrix with one column for the gradient of each constraint, as is gradceq.
For more information, see Constraints.
Function handle to the objective function. For all solvers except lsqnonlin and lsqcurvefit, the objective function must accept a vector x and return a scalar. If the GradObj option is 'on', then the objective function must return a second output, a vector, representing the gradient of the objective. For lsqnonlin, the objective function must accept a vector x and return a vector. lsqnonlin sums the squares of the objective function values. For lsqcurvefit, the objective function must accept two inputs, x and xdata, and return a vector.
For more information, see Computing Objective Functions.
Options structure. Create this structure with optimset, or by exporting from the Optimization Tool.
Vector of upper bounds.
x0
A vector, a potential starting point for the optimization. Gives the dimensionality of the problem.
Vector of data points for lsqcurvefit. Vector of data points for lsqcurvefit.
For GlobalSearch: 'fmincon' For MultiStart the choices are: 'fmincon' 'fminunc' 'lsqcurvefit' 'lsqnonlin'
xdata ydata
where solver is the name of your local solver: ?
o ?
o o o o
例子1 f=@(x)(100*(x(2) - x(1)^2)^2 + (1-x(1))^2);求最小值 gs=GlobalSearch;
anonrosen=@(x)(100*(x(2)-x(1)^2)^2+(1-x(1))^2); opts=optimset('Algorithm','interior-point');
problem=createOptimProblem('fmincon','x0',randn(2,1),'objective',anonrosen,'lb',[-2;-2],'ub',[2;2],'options',opts);
[x,fval,exitflag,output,solutions]=run(gs,problem) ans x=[1.0000;1.0000];fval=2.3801e-011 例子2: 有约束遗传优化
%sixmin=4x2–2.1x4+x6/3+xy–4y2+4y4. x1 + 2x2≥4. gs = GlobalSearch;
sixmin=@(x)(4*x(1)^2-2.1*x(1)^4+x(1)^6/3+x(1)*x(2)-4*x(2)^2+4*x(2)^4); A=[-1,-2];b=-4;
opts=optimset('Algorithm','interior-point');
problem=createOptimProblem('fmincon','x0',[2;3],'objective',sixmin,'Aineq',A,'bineq',b,'options',opts);
[x,fval,exitflag,output,solutions] = run(gs,problem)
例子3 基于模拟退火算法minf(x)=(4-2.1*x1^2+x1^4/3)*x1^2+x1*x2+(-4+4*x2^2)*x2^2; function y =simple_objective(x)
y=(4-2.1*x(1)^2+x(1)^4/3)*x(1)^2+x(1)*x(2)+(-4+4*x(2)^2)*x(2)^2; ObjectiveFunction = @simple_objective; X0 = [0.5 0.5];% Starting point lb=[];ub=[]
[x,fval,exitFlag,output] = simulannealbnd(ObjectiveFunction,X0,lb,ub) 3.2 参数化的最小
function y = parameterized_objective(x,a,b,c)
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2) +(-c + c*x(2)^2)*x(2)^2; a = 4; b = 2.1; c = 4; % define constant values
ObjectiveFunction = @(x) parameterized_objective(x,a,b,c); X0 = [0.5 0.5];
[x,fval] = simulannealbnd(ObjectiveFunction,X0)
例子4使用工具箱
This example minimizes the function from Run the Solver, subject to the constraint
x1 + 2x2 ≥ 4. The objective is
sixmin = 4x2 – 2.1x4 + x6/3 + xy – 4y2 + 4y4.
sixmin = @(x)(4*x(1)^2 - 2.1*x(1)^4 + x(1)^6/3 + x(1)*x(2) - 4*x(2)^2 + 4*x(2)^4); A = [-1,-2]; b = -4;
1. Best practice: run the problem to verify the setup.
The problem runs successfully.
2. Choose File > Export to Workspace and select Export problem and options to a MATLAB structure named
例子5 多起始点优化(MultiStart Global Optimization)) gs = GlobalSearch; ms = MultiStart; xstart = randn(3,1);
options = optimset('Algorithm','interior-point');
假设你想解决一个问题并假设局部解相邻0.01之内,并且函数值在函数精度之内;求解时间少于2000s;
gs = GlobalSearch('TolX',0.01,'MaxTime',2000); gs = GlobalSearch; ms = MultiStart;
[xmin,fmin,flag,outpt,allmins] = run(ms,problem,k);%k为要使用的起点数目,k可以由RandomStartPointSet函数产生;
5.1 RandomStartPointSet Object for Start Points
stpoints = RandomStartPointSet;%默认产生10个起始点,如果想产生 stpoints = RandomStartPointSet('NumStartPoints',40);
Running a solver is nearly identical for GlobalSearch and MultiStart. The only difference in syntax is MultiStart takes an additional input describing the start points.
startpts = RandomStartPointSet('ArtificialBound',100,'NumStartPoints',50); [x fval eflag output manymins] = run(ms,problem,startpts) 5.2 CustomStartPointSet Object for Start Points
To use a specific set of starting points, package them in a CustomStartPointSet as follows: Place the starting points in a matrix. Each row of the matrix represents one starting point. MultiStart runs all the rows of the matrix, subject to filtering with the StartPointsToRun property. For more information, see MultiStart Algorithm. Create a CustomStartPointSet object from the matrix: tpoints = CustomStartPointSet(ptmatrix);
For example, create a set of 40 five-dimensional points, with each component of a point equal to 10 plus an exponentially distributed variable with mean 25: pts = -25*log(rand(40,5)) + 10;
tpoints = CustomStartPointSet(pts);
To get the original matrix of points from a CustomStartPointSet object, use the list method:
pts = list(tpoints); % Assumes tpoints is a CustomStartPointSet
A CustomStartPointSet has two properties: DimStartPoints and NumStartPoints. You can use these properties to query a CustomStartPointSet object. For example, the tpoints object in the example has the following properties: tpoints.DimStartPoints ans =5
tpoints.NumStartPoints ans =40
5.3 Cell Array of Objects for Start Points
To use a specific set of starting points along with some randomly generated points, pass a cell array of RandomStartPointSet or CustomStartPointSet objects. For example, to use both the 40 specific five-dimensional points of
CustomStartPointSet Object for Start Points and 40 additional five-dimensional points from RandomStartPointSet: pts = -25*log(rand(40,5)) + 10;
tpoints = CustomStartPointSet(pts);
rpts = RandomStartPointSet('NumStartPoints',40); allpts = {tpoints,rpts};
Run MultiStart with the allpts cell array: % Assume ms and problem exist
[xmin,fmin,flag,outpt,allmins] = run(ms,problem,allpts); 例子6 小值优化(基于全局算法和多起点算法的比较) sixmin = 4x – 2.1x + x/3 + xy – 4y + 4y.
2
4
6
2
4
[X Y] = meshgrid(-2:.1:2,-1:.05:1);
Z = 4*X.^2 - 2.1*X.^4 + X.^6./3 + X.*Y - 4*Y.^2 + 4*Y.^4; surf(X,Y,Z);view(-44,14) xlabel('x');ylabel('y') title('sixmin(x,y)')
[X Y] = meshgrid(-2:.1:2,-1:.05:1);
Z = 4*X.^2 - 2.1*X.^4 + X.^6./3 + X.*Y - 4*Y.^2 + 4*Y.^4; surf(X,Y,Z);view(-44,14) xlabel('x');ylabel('y') title('sixmin(x,y)')
This function is also called the six-hump camel back function [3]. All the local minima lie in the region –3 ≤ x,y ≤ 3. 6.1 gobalSearch
gs = GlobalSearch('Display','iter');
opts = optimset('Algorithm','interior-point'); sixmin = @(x)(4*x(1)^2 - 2.1*x(1)^4 + x(1)^6/3 ... + x(1)*x(2) - 4*x(2)^2 + 4*x(2)^4);
problem=createOptimProblem('fmincon','x0',[-1,2],'objective',sixmin,'lb',[-3,-3],'ub',[3,3],'options',opts);
[xming,fming,flagg,outptg,manyminsg] = run(gs,problem); xming,fming,flagg,outptg,manyminsg xming = -0.0898 0.7127 fming =-1.0316 flagg = 1 outptg =
funcCount: 2245 localSolverTotal: 8 localSolverSuccess: 8 localSolverIncomplete: 0
localSolverNoSolution: 0
message: [1x137 char] manyminsg = 1x4 GlobalOptimSolution Properties: X Fval Exitflag Output X0
6.2 Run with MultiStart
To find several local minima of the problem described in Run the Solver using 50 runs of fmincon with MultiStart, enter: ms=MultiStart;
opts=optimset('Algorithm','interior-point');
sixmin=@(x)(4*x(1)^2-2.1*x(1)^4+x(1)^6/3+x(1)*x(2)-4*x(2)^2+4*x(2)^4);
problem=createOptimProblem('fmincon','x0',[-1,2],'objective',sixmin,'lb',[-3,-3],'ub',[3,3],'options',opts);
[xminm,fminm,flagm,outptm,manyminsm]=run(ms,problem,50);
The output of the run (which varies based on the random seed): xminm,fminm,flagm,outptm,manyminsm xminm =-0.0898 0.7127 fminm = -1.0316 flagm = 1
outptm = funcCount: 2035 localSolverTotal: 50 localSolverSuccess: 50 localSolverIncomplete: 0 localSolverNoSolution: 0
message: [1x128 char]
manyminsm = 1x6 GlobalOptimSolution Properties: X Fval Exitflag Output X0
在这个例子中multistart方法找个6个局部最优解,而globalsearch方法找到4个 Example: Visualizing the Basins of Attraction. ms = MultiStart('TolFun',0.01,'TolX',0.01); opts = optimset('Algorithm','active-set');
sixmin = @(x)(4*x(1)^2 - 2.1*x(1)^4 + x(1)^6/3 ... + x(1)*x(2) - 4*x(2)^2 + 4*x(2)^4);
problem = createOptimProblem('fmincon','x0',[-1,2],... 'objective',sixmin,'lb',[-3,-3],'ub',[3,3],... 'options',opts);
[xminm,fminm,flagm,outptm,someminsm] = run(ms,problem,50);
7 优化结果的改进
7.1 要判断一个解是否为全局解,首先确定是否为局部解,使用pattern search函数 x = patternsearch(@fun,x0,A,b,Aeq,beq,LB,UB,nonlcon,options) x = patternsearch(problem)%求函数的最小值; problem.solver = 'patternsearch'; 其次把刚才求得的解设置为初始点 problem.x0 = x;
例子1 ffun = @(x)(x(1)-(x(1)-x(2))^2)
options = optimset('Algorithm','active-set'); % 'active-set','trust-region-reflective',
'interior-point','levenberg-marquardt', 'trust-region-dogleg','lm-line-search', or 'sqp'.
ffun = @(x)(x(1)-(x(1)-x(2))^2);
problem = createOptimProblem('fmincon','objective',ffun,'x0',[1/2 1/3],'lb',[0 -1],'ub',[1 1],'options',options); [x fval exitflag] = fmincon(problem) x = 0;1.6143e-008 fval =-2.6059e-016 exitflag = 1
% 把求解值设为pattersearch起始值搜索到一个更小的值-3 problem.x0 = x;
problem.solver = 'patternsearch';
[xp fvalp exitflagp] = patternsearch(problem) xp =1.0000 -1.0000 fvalp =-3.0000 exitflagp =1
7.2 对于用globalsearch方法到multistart方法的一些改变 1 Change the solver field to 'fminunc': problem.solver = 'fminunc';
To avoid a warning if your objective function does not compute a gradient, change the local options structure to have LargeScale set to 'off': problem.options.LargeScale = 'off';
2 Add an artificial constraint, retaining fmincon as the local solver: problem.lb = -Inf;
7.3 如果你能确定最优值的取值范围的情况下,缩小搜索范围
f=@(x,y)x^6+y^6+sin(x+y)*(x^2+y^2)-cos(x^2/(1+y^2))*(2+x^4+x^2y^2+y^4); –10 ≤ x,y ≤ 10, 因为106 远大于104,所以如果把搜索范围改在最佳值所在的范围[-2,2]将会取得较好的结果
f=@(x)x(1)^6+x(2)^6+sin(x(1)+x(2))*(x(1)^2+x(2)^2)-cos(x(1)^2/(1+x(2)^2))*(2+x(1)^4+x(1)^2x(2)^2+x(2)^4);
startpts = RandomStartPointSet('ArtificialBound',100,'NumStartPoints',50); [x fval eflag output manymins] = run(ms,problem,startpts)
7.4 改进搜索起始值(使得起始值更散开一些);或者增加起始点数目(multistart) Uniform Grid. To generate a uniform grid of start points:
1 Generate multidimensional arrays with ndgrid. Give the lower bound, spacing, and upper bound for each component.
For example, to generate a set of three-dimensional arrays with 1 First component from –2 through 0, spacing 0.5 2 Second component from 0 through 2, spacing 0.25 3 Third component from –10 through 5, spacing 1 [X,Y,Z] = ndgrid(-2:.5:0,0:.25:2,-10:5);
2 Place the arrays into a single matrix, with each row representing one start point. For example:
W = [X(:),Y(:),Z(:)];
In this example, W is a 720-by-3 matrix.
3. Put the matrix into a CustomStartPointSet object. For example: custpts = CustomStartPointSet(W);
8 GlobalSearch and MultiStart Examples
f(r,t) = g(r)h(t),
g(r)=(sin(r)-sin(2*r)/2+sin(3*r)/3-sin(4*r)/4+4)*r^2/(r+1); h(t)=2+cos(t)+cos(2*t-1)/2;
f=@(r,t)((sin(r)-sin(2*r)/2+sin(3*r)/3-sin(4*r)/4+4)*r^2/(r+1))*(2+cos(t)+cos(2*t-1)/2)
全局最优解在r=0;函数g近似和r成直线振荡关系,函数h有两个局部解,其中一个为全局最佳解;
functionf=sawtoothxy(x,y)
[t r]=cart2pol(x,y); % change to polar coordinates
h =cos(2*t-1/2)/2+cos(t)+2;
g=(sin(r)-sin(2*r)/2+sin(3*r)/3-sin(4*r)/4+4).*r.^2./(r+1); f=g.*h; end
subplot(1,2,1);
ezplot(@(r)(sin(r) - sin(2*r)/2 + sin(3*r)/3 - sin(4*r)/4 + 4) .* r.^2./(r+1),[0,20]) title(''); ylabel('g') subplot(1,2,2);
ezplot(@(t)2 + cos(t) + cos(2*t-1/2)/2,[0,2*pi]) title(''); ylabel('h') figure
ezsurf(@(x,y)sawtoothxy(x,y),[-20,20])
% sawtoothxy is defined in the first step below view(-18,52)
1 使用globalsearch方法
problem=createOptimProblem('fmincon','objective',@(x)sawtoothxy(x(1),x(2)),'x0',[100,-50],'options',optimset('Algorithm','sqp')); problem.lb = -Inf;
[x fval] = fmincon(problem)
gs = GlobalSearch('Display','iter'); [x fval] = run(gs,problem)
2 使用multistart方法
problem=createOptimProblem('fminunc','objective',@(x)sawtoothxy(x(1),x(2))'x0',[100,-50],'options',optimset('LargeScale','off')); [x fval] = fminunc(problem); ms = MultiStart;
[x fval eflag output manymins] = run(ms,problem,50);%求解器没有找到全局解,找到16个局部解。
hist([manymins.Fval]);
bestf = [manymins.Fval];% Plot the function values at the three best points hist(bestf(1:3))
9 Example: Isolated Global Minimum
The function –sech(x) is nearly 0 for all |x| > 5, and –sech(0) = –1. The example is a two-dimensional version of the sech function, with one minimum at [1,1], the other at [1e5,-1e5]:
f(x,y) = –10sech(|x – (1,1)|) – 20sech(.0003(|x – (1e5,–1e5)|) – 1. f has a global minimum of –21 at (1e5,–1e5), and a local minimum of –11 at (1,1). % f is a vectorized version of the objective function % Each row of an input matrix x is one point to evaluate
f = @(x)-10*sech(sqrt((x(:,1)-x1(1)).^2+(x(:,2)-x1(2)).^2)) ... -20*sech(3e-4*sqrt((x(:,1)-x2(1)).^2+(x(:,2)-x2(2)).^2))-1; hndl = ezsurf(@(x,y)f([x,y]),[-1e6 1e6],1000); set(hndl,'LineStyle','none') view(-45,10) hold on
annotation('textarrow',...
[0.71 0.56],[0.48 0.21],'TextEdgeColor','none',... 'String',{'Global Minimum'}); hold off
9.1 Default Settings Cannot Find the Global Minimum — Add Bounds
GlobalSearch and MultiStart cannot find the global minimum using default global options, since the default start point components are in the range (–9999,10001) for GlobalSearch and (–1000,1000) for MultiStart.
With additional bounds of –1e6 and 1e6 in problem, GlobalSearch usually does not find the global minimum:
x1 = [1;1];x2 = [1e5;-1e5];
f = @(x)-10*sech(norm(x(:)-x1)) -20*sech((norm(x(:)-x2))*3e-4) -1; problem = createOptimProblem('fmincon','x0',[0,0],'objective',f,... 'lb',[-1e6;-1e6],'ub',[1e6;1e6]); gs = GlobalSearch;
[xfinal fval] = run(gs,problem)
GlobalSearch stopped because it analyzed all the trial points. All 57 local solver runs converged with a positive local solver exit flag.
xfinal = 1.0000 1.0000
fval = -11.0000
9.2 GlobalSearch with Bounds and More Start Points
To find the global minimum, you can search more points. This example uses 1e5 start points, and a MaxTime of 300 s: gs.NumTrialPoints = 1e5; gs.MaxTime = 300;
[xg fvalg] = run(gs,problem)
MultiStart Without Bounds, Widely Dispersed Start Points
You can also use MultiStart to search an unbounded region to find the global minimum. Again, you need many start points to have a good chance of finding the global minimum.
The first five lines of code generate 10,000 widely dispersed random start points using the method described in Widely Dispersed Points for Unconstrained Components. newprob is a problem structure using the fminunc local solver and no bounds: u = rand(1e4,1); u = 1./u;
u = exp(u) - exp(1); s = rand(1e4,1)*2*pi;
stpts = [u.*cos(s),u.*sin(s)];
startpts = CustomStartPointSet(stpts);
newprob = createOptimProblem('fminunc','x0',[0;0],'objective',f); [xcust fcust] = run(ms,newprob,startpts) MultiStart with a Regular Grid of Start Points
You can also use a grid of start points instead of random start points. To learn how to construct a regular grid for more dimensions, or one that has small perturbations, see Uniform Grid or Perturbed Grid. xx = -1e6:1e4:1e6;
[xxx yyy] = meshgrid(xx,xx); z = [xxx(:),yyy(:)];
bigstart = CustomStartPointSet(z);
[xgrid fgrid] = run(ms,newprob,bigstart)
MultiStart completed the runs from all start points.
All 10000 local solver runs converged with a positive local solver exit flag. xcust =
1.0e+004 *
10.0000 -10.0000
fcust = -21.0000
In this case, MultiStart found the global minimum. MultiStart with Regular Grid and Promising Start Points
Making a regular grid of start points, especially in high dimensions, can use an inordinate amount of memory or time. You can filter the start points to run only those with small objective function value.
To perform this filtering most efficiently, write your objective function in a vectorized fashion. For information, see Example: Writing a Vectorized Function or Vectorizing the Objective and Constraint Functions. The following function handle computes a vector of objectives based on an input matrix whose rows represent start points:
x1 = [1;1];x2 = [1e5;-1e5];
g = @(x) -10*sech(sqrt((x(:,1)-x1(1)).^2 + (x(:,2)-x1(2)).^2)) ...
-20*sech(sqrt((x(:,1)-x2(1)).^2 + (x(:,2)-x2(2)).^2))-1;
Suppose you want to run the local solver only for points where the value is less than –2. Start with a denser grid than in MultiStart with a Regular Grid of Start Points, then filter out all the points with high function value: xx = -1e6:1e3:1e6;
[xxx yyy] = meshgrid(xx,xx); z = [xxx(:),yyy(:)];
idx = g(z) < -2; % index of promising start points zz = z(idx,:);
smallstartset = CustomStartPointSet(zz);
newprobg = createOptimProblem('fminunc','x0',[0,0],... 'objective',g); % row vector x0 since g expects rows [xfew ffew] = run(ms,newprobg,smallstartset)
MultiStart completed the runs from all start points.
All 2 local solver runs converged with a positive local solver exit flag.
xfew =
100000 -100000
ffew = -21
Using Parallel Computing with fmincon, fgoalattain, and fminimax
% Increase the total candidate points, but filter out the infeasible ones gs = GlobalSearch(gs,'StartPointsToRun','bounds-ineqs', ... 'MaxWaitCycle',3,'BasinRadiusFactor',0.3);
ms = MultiStart(ms,'UseParallel','always'); matlabpool open
If you have a multicore processor, you might see speedup using parallel processing. You can establish a matlabpool of several parallel workers with a Parallel Computing Toolbox license. For a description of Parallel Computing Toolbox software, and the maximum number of parallel workers, see Product Overview.
Suppose you have a dual-core processor, and want to use parallel computing: Enter matlabpool open 2
at the command line. The 2 specifies the number of MATLAB processes to start. options = optimset('UseParallel','always');
For Optimization Tool, check Options > Approximated derivatives > Evaluate in parallel.
matlabpool close
GlobalSearch
GlobalSearch does not distribute a problem and start points to multiple processes or processors. However, when GlobalSearch runs the fmincon local solver, fmincon can estimate gradients by parallel finite differences. fmincon uses parallel computing when you:
? ? ? ? ?
Have a license for Parallel Computing Toolbox software.
Enable parallel computing with matlabpool, a Parallel Computing Toolbox function.
Set the UseParallel option to 'always' with optimset. Set this option in the problem structure:
opts = optimset('UseParallel','always','Algorithm','sqp'); problem = createOptimProblem('fmincon','objective',@myobj,... 'x0',startpt,'options',opts);
正在阅读:
matlab遗传算法学习和全局化算法10-05
黔西南州2014年初中毕业生学业暨升学统一考试试卷10-22
地质勘查规划数据库建设规范 - 图文06-01
课程目的_培养批判性思维习惯09-04
2018-2019学年高中数学 第2章 平面解析几何初步 2.1 直线与方程03-22
基于单片机的任意波形发生器的-设计07-07
谈消失模铸造涂料的价值所在08-29
散文标题11-05
第1章_Excel_2003初体验08-14
- 多层物业服务方案
- (审判实务)习惯法与少数民族地区民间纠纷解决问题(孙 潋)
- 人教版新课标六年级下册语文全册教案
- 词语打卡
- photoshop实习报告
- 钢结构设计原理综合测试2
- 2014年期末练习题
- 高中数学中的逆向思维解题方法探讨
- 名师原创 全国通用2014-2015学年高二寒假作业 政治(一)Word版
- 北航《建筑结构检测鉴定与加固》在线作业三
- XX县卫生监督所工程建设项目可行性研究报告
- 小学四年级观察作文经典评语
- 浅谈110KV变电站电气一次设计-程泉焱(1)
- 安全员考试题库
- 国家电网公司变电运维管理规定(试行)
- 义务教育课程标准稿征求意见提纲
- 教学秘书面试技巧
- 钢结构工程施工组织设计
- 水利工程概论论文
- 09届九年级数学第四次模拟试卷
- 算法
- 全局
- 遗传
- matlab
- 学习
- 浅析中国乡村旅游发展现状及前景
- 做慈善应该低调还是高调 资料补充
- 01--tutorial01--HTML基本标签
- 2019建筑工程全套质量管理手册
- 《市场营销与网络营销》第11章
- 山西省书画家通讯录
- 六年级语文上七单元教材分析
- 《Internet应用》复习题(1)(含答案)
- 全国中考英语汇编解析:阅读理解
- 2013-2017年中国建筑节能行业发展前景与投资战略规划分析报告
- 读赵江萍《别对爱要求完美》想到的
- 2014年高考化学核心考点总结
- 检验科常规检查项目及主要临床意义
- 井巷维修管理制度
- 现代文阅读:轻轻的拥抱母亲
- 233067 北交《液压与气压传动》在线作业二 15秋答案
- 审计(2014) 第八章 风险应对 课后作业(下载版)
- 中考数学试卷解析分类汇编(第1期)专题24 多边形与平行四边形
- 1浅谈农民法律意识的现状及对策研究
- 微博营销利弊及策略分析毕业论文