文档库 最新最全的文档下载
当前位置:文档库 › matlab遗传算法学习和全局化算法

matlab遗传算法学习和全局化算法

matlab遗传算法学习和全局化算法
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求)20sin()4sin(5.212211x pi x x pi x f ???+??+=的最大值;也就是求负函数的最小值 最大值为-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],'u b',[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

constraints have the form:

Aeq x = beq

Aineq Matrix for linear inequality constraints. The

constraints have the form:

Aineq x ≤ bineq

beq Vector for linear equality constraints. The

constraints have the form:

Aeq x = beq

bineq Vector for linear inequality constraints. The

constraints have the form:

Aineq x ≤ bineq

lb Vector of lower bounds.

nonlcon 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.

objective 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 Options structure. Create this structure with

optimset, or by exporting from the Optimization

Tool.

ub Vector of upper bounds.

x0 A vector, a potential starting point for the

optimization. Gives the dimensionality of the

problem.

xdata Vector of data points for lsqcurvefit.

ydata Vector of data points for lsqcurvefit.

where solver is the name of your local solver: o ?For GlobalSearch: 'fmincon' ?For MultiStart the choices are: o 'fmincon'

o 'fminunc'

o 'lsqcurvefit'

o 'lsqnonlin'

例子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 x

+ 2x2≥ 4. The objective is

1

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 = 4x2– 2.1x4 + x6/3 + xy– 4y2 + 4y4.

[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':

https://www.wendangku.net/doc/db9125542.html,rgeScale = '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完整代码(不用工具箱)

遗传算法解决简单问题 %主程序:用遗传算法求解y=200*exp(-0.05*x).*sin(x)在区间[-2,2]上的最大值clc; clear all; close all; global BitLength global boundsbegin global boundsend bounds=[-2,2]; precision=0.0001; boundsbegin=bounds(:,1); boundsend=bounds(:,2); %计算如果满足求解精度至少需要多长的染色体 BitLength=ceil(log2((boundsend-boundsbegin)'./precision)); popsize=50; %初始种群大小 Generationmax=12; %最大代数 pcrossover=0.90; %交配概率 pmutation=0.09; %变异概率 %产生初始种群 population=round(rand(popsize,BitLength)); %计算适应度,返回适应度Fitvalue和累计概率cumsump [Fitvalue,cumsump]=fitnessfun(population); Generation=1; while Generation

基于遗传算法的matlab源代码

function youhuafun D=code; N=50;%Tunable maxgen=50;%Tunable crossrate=0.5;%Tunable muterate=0.08;%Tunable generation=1; num=length(D); fatherrand=randint(num,N,3); score=zeros(maxgen,N); while generation<=maxgen ind=randperm(N-2)+2;%随机配对交叉 A=fatherrand(:,ind(1:(N-2)/2)); B=fatherrand(:,ind((N-2)/2+1:end)); %多点交叉 rnd=rand(num,(N-2)/2); ind=rnd tmp=A(ind); A(ind)=B(ind); B(ind)=tmp; %%两点交叉 %for kk=1:(N-2)/2 %rndtmp=randint(1,1,num)+1; %tmp=A(1:rndtmp,kk); %A(1:rndtmp,kk)=B(1:rndtmp,kk); %B(1:rndtmp,kk)=tmp; %end fatherrand=[fatherrand(:,1:2),A,B]; %变异 rnd=rand(num,N); ind=rnd[m,n]=size(ind); tmp=randint(m,n,2)+1; tmp(:,1:2)=0; fatherrand=tmp+fatherrand; fatherrand=mod(fatherrand,3); %fatherrand(ind)=tmp; %评价、选择 scoreN=scorefun(fatherrand,D);%求得N个个体的评价函数 score(generation,:)=scoreN; [scoreSort,scoreind]=sort(scoreN); sumscore=cumsum(scoreSort); sumscore=sumscore./sumscore(end); childind(1:2)=scoreind(end-1:end); for k=3:N tmprnd=rand; tmpind=tmprnd difind=[0,diff(t mpind)]; if~any(difind) difind(1)=1; end childind(k)=scoreind(logical(difind)); end fatherrand=fatherrand(:,childind); generation=generation+1; end %score maxV=max(score,[],2); minV=11*300-maxV; plot(minV,'*');title('各代的目标函数值'); F4=D(:,4); FF4=F4-fatherrand(:,1); FF4=max(FF4,1); D(:,5)=FF4; save DData D function D=code load youhua.mat %properties F2and F3 F1=A(:,1); F2=A(:,2); F3=A(:,3); if(max(F2)>1450)||(min(F2)<=900) error('DATA property F2exceed it''s range (900,1450]') end %get group property F1of data,according to F2value F4=zeros(size(F1)); for ite=11:-1:1 index=find(F2<=900+ite*50); F4(index)=ite; end D=[F1,F2,F3,F4]; function ScoreN=scorefun(fatherrand,D) F3=D(:,3); F4=D(:,4); N=size(fatherrand,2); FF4=F4*ones(1,N); FF4rnd=FF4-fatherrand; FF4rnd=max(FF4rnd,1); ScoreN=ones(1,N)*300*11; %这里有待优化

遗传算法的原理及MATLAB程序实现

1 遗传算法的原理 1.1 遗传算法的基本思想 遗传算法(genetic algorithms,GA)是一种基于自然选择和基因遗传学原理,借鉴了生物进化优胜劣汰的自然选择机理和生物界繁衍进化的基因重组、突变的遗传机制的全局自适应概率搜索算法。 遗传算法是从一组随机产生的初始解(种群)开始,这个种群由经过基因编码的一定数量的个体组成,每个个体实际上是染色体带有特征的实体。染色体作为遗传物质的主要载体,其内部表现(即基因型)是某种基因组合,它决定了个体的外部表现。因此,从一开始就需要实现从表现型到基因型的映射,即编码工作。初始种群产生后,按照优胜劣汰的原理,逐代演化产生出越来越好的近似解。在每一代,根据问题域中个体的适应度大小选择个体,并借助于自然遗传学的遗传算子进行组合交叉和变异,产生出代表新的解集的种群。这个过程将导致种群像自然进化一样,后代种群比前代更加适应环境,末代种群中的最优个体经过解码,可以作为问题近似最优解。 计算开始时,将实际问题的变量进行编码形成染色体,随机产生一定数目的个体,即种群,并计算每个个体的适应度值,然后通过终止条件判断该初始解是否是最优解,若是则停止计算输出结果,若不是则通过遗传算子操作产生新的一代种群,回到计算群体中每个个体的适应度值的部分,然后转到终止条件判断。这一过程循环执行,直到满足优化准则,最终产生问题的最优解。图1-1给出了遗传算法的基本过程。 1.2 遗传算法的特点 1.2.1 遗传算法的优点 遗传算法具有十分强的鲁棒性,比起传统优化方法,遗传算法有如下优点: 1. 遗传算法以控制变量的编码作为运算对象。传统的优化算法往往直接利用控制变量的实际值的本身来进行优化运算,但遗传算法不是直接以控制变量的值,而是以控制变量的特定形式的编码为运算对象。这种对控制变量的编码处理方式,可以模仿自然界中生物的遗传和进化等机理,也使得我们可以方便地处理各种变量和应用遗传操作算子。 2. 遗传算法具有内在的本质并行性。它的并行性表现在两个方面,一是遗传

遗传算法的MATLAB程序实例讲解学习

遗传算法的M A T L A B 程序实例

遗传算法的程序实例 如求下列函数的最大值 f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] 一、初始化(编码) initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度), 长度大小取决于变量的二进制编码的长度(在本例中取10位)。 代码: %Name: initpop.m %初始化 function pop=initpop(popsize,chromlength) pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵, % roud对矩阵的每个单元进行圆整。这样产生的初始种群。 二、计算目标函数值 1、将二进制数转化为十进制数(1) 代码: %Name: decodebinary.m %产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制 function pop2=decodebinary(pop) [px,py]=size(pop); %求pop行和例数 for i=1:py pop1(:,i)=2.^(py-1).*pop(:,i); py=py-1; end pop2=sum(pop1,2); %求pop1的每行之和 2、将二进制编码转化为十进制数(2) decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置。(对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),参数1ength表示所截取的长度(本例为10)。 代码: %Name: decodechrom.m %将二进制编码转换成十进制 function pop2=decodechrom(pop,spoint,length) pop1=pop(:,spoint:spoint+length-1); pop2=decodebinary(pop1); 3、计算目标函数值 calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。

简单的遗传算法MATLAB实现

遗传算法是对达尔文生物进化理论的简单模拟,其遵循“适者生存”、“优胜略汰”的原理。遗传算法模拟一个人工种群的进化过程,并且通过选择、杂交以及变异等机制,种群经过若干代以后,总是达到最优(或近最优)的状态。 自从遗传算法被提出以来,其得到了广泛的应用,特别是在函数优化、生产调度、模式识别、神经网络、自适应控制等领域,遗传算法更是发挥了重大的作用,大大提高了问题求解的效率。遗传算法也是当前“软计算”领域的重要研究课题。 本文首先结合MATLAB对遗传算法实现过程进行详细的分析,然后通过1个实际的函数优化案例对其应用进行探讨。 1. 遗传算法实现过程 现实生活中很多问题都可以转换为函数优化问题,所以本文将以函数优化问题作为背景,对GA的实现过程进行探讨。大部分函数优化问题都可以写成求最大值或者最小值的形式,为了不是一般性,我们可以将所有求最优值的情况都转换成求最大值的形式,例如,求函数f(x)的最大值,

若是求函数f(x)的最小值,可以将其转换成 g(x)=-f(x),然后求g(x)的最大值, 这里x可以是一个变量,也可是是一个由k个变量组成的向量,x=(x1, x2, …, x k)。每个x i,i=1,2,…,k, 其定义域为D i,D i=[a i, b i]。 一般规定f(x)在其定义域内只取正值,若不满足,可以将其转换成以下形式, 其中C是一个正常数。 1.1 编码与解码 要实现遗传算法首先需要弄清楚如何对求解问题进行编码和解码。对于函数优化问题,一般来说,有两种编码方式,一是实数编码,一是二进制编码,两者各有优缺点,二进制编码具有稳定性高、种群多样性大等优点,但是需要的存储空间大,需要解码过程并且难以理解;而实数编码直接用实数表示基因,容易理解并且不要解码过程,但是容易过早收敛,从而陷入局部最优。本文以最常用的二进制编码为例,说明遗传编码的过程。

使用MATLAB遗传算法工具实例(详细) (1)【精品毕业设计】(完整版)

最新发布的MA TLAB 7.0 Release 14已经包含了一个专门设计的遗传算法与直接搜索工具箱(Genetic Algorithm and Direct Search Toolbox,GADS)。使用遗传算法与直接搜索工具箱,可以扩展MATLAB及其优化工具箱在处理优化问题方面的能力,可以处理传统的优化技术难以解决的问题,包括那些难以定义或不便于数学建模的问题,可以解决目标函数较复杂的问题,比如目标函数不连续、或具有高度非线性、随机性以及目标函数没有导数的情况。 本章8.1节首先介绍这个遗传算法与直接搜索工具箱,其余各节分别介绍该工具箱中的遗传算法工具及其使用方法。 8.1 遗传算法与直接搜索工具箱概述 本节介绍MATLAB的GADS(遗传算法与直接搜索)工具箱的特点、图形用户界面及运行要求,解释如何编写待优化函数的M文件,且通过举例加以阐明。 8.1.1 工具箱的特点 GADS工具箱是一系列函数的集合,它们扩展了优化工具箱和MA TLAB数值计算环境的性能。遗传算法与直接搜索工具箱包含了要使用遗传算法和直接搜索算法来求解优化问题的一些例程。这些算法使我们能够求解那些标准优化工具箱范围之外的各种优化问题。所有工具箱函数都是MATLAB的M文件,这些文件由实现特定优化算法的MATLAB语句所写成。 使用语句 type function_name 就可以看到这些函数的MATLAB代码。我们也可以通过编写自己的M文件来实现来扩展遗传算法和直接搜索工具箱的性能,也可以将该工具箱与MATLAB的其他工具箱或Simulink结合使用,来求解优化问题。 工具箱函数可以通过图形界面或MA TLAB命令行来访问,它们是用MATLAB语言编写的,对用户开放,因此可以查看算法、修改源代码或生成用户函数。 遗传算法与直接搜索工具箱可以帮助我们求解那些不易用传统方法解决的问题,譬如表查找问题等。 遗传算法与直接搜索工具箱有一个精心设计的图形用户界面,可以帮助我们直观、方便、快速地求解最优化问题。 8.1.1.1 功能特点 遗传算法与直接搜索工具箱的功能特点如下: 图形用户界面和命令行函数可用来快速地描述问题、设置算法选项以及监控进程。 具有多个选项的遗传算法工具可用于问题创建、适应度计算、选择、交叉和变异。 直接搜索工具实现了一种模式搜索方法,其选项可用于定义网格尺寸、表决方法和搜索方法。 遗传算法与直接搜索工具箱函数可与MATLAB的优化工具箱或其他的MATLAB程序结合使用。 支持自动的M代码生成。 8.1.1.2 图形用户界面和命令行函数 遗传算法工具函数可以通过命令行和图形用户界面来使用遗传算法。直接搜索工具函数也可以通过命令行和图形用户界面来进行访问。图形用户界面可用来快速地定义问题、设置算法选项、对优化问题进行详细定义。 133

(完整版)三个遗传算法matlab程序实例

遗传算法程序(一): 说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作! function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation) % Finds a maximum of a function of several variables. % fmaxga solves problems of the form: % max F(X) subject to: LB <= X <= UB % BestPop - 最优的群体即为最优的染色体群 % Trace - 最佳染色体所对应的目标函数值 % FUN - 目标函数 % LB - 自变量下限 % UB - 自变量上限 % eranum - 种群的代数,取100--1000(默认200) % popsize - 每一代种群的规模;此可取50--200(默认100) % pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8) % pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1) % pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2) % options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编 %码,option(2)设定求解精度(默认1e-4) % % ------------------------------------------------------------------------ T1=clock; if nargin<3, error('FMAXGA requires at least three input arguments'); end if nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end if nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end if nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end if nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];end if nargin==7, pInversion=0.15;options=[0 1e-4];end if find((LB-UB)>0) error('数据输入错误,请重新输入(LB

遗传算法MATLAB实现代码

%%以下代码可直接复制粘贴到m文档运行 clc; clear all; %输入数据 for i=1:4000 input(i,:)=10*rand(1,2)-5; output(i)=input(i,1)^2+input(i,2)^2; end output=output'; k = rand(1,4000); [m,n] = sort(k);%m是数值排序,n是对应的位置 %找出训练数据和预测数据 input_train = input(n(1:3900),:)'; output_train = output(n(1:3900),:)'; input_test = input(n(3901:4000),:)'; output_test = output(n(3901:4000),:)'; %%数据归一化 [gui_1_input,gui_1_inputs] = mapminmax(input_train);%gui_1_inputs是一个包含最大最小值等信息的结构体 [gui_1_output,gui_1_outputs] = mapminmax(output_train); %构建神经网络 net = newff(gui_1_input,gui_1_output,5); %5是隐含层节点数net.trainParam.epochs = 100;%训练次数 net.trainParam.lr = 0.1;%学习速率 net.trainParam.goal = 0.0000004;%训练目标最小误差 %%bp神经网络训练 net = train(net,gui_1_input,gui_1_output); %测试样本归一化 gui_1_input_test = mapminmax('apply',input_test,gui_1_inputs);%"apply"根据

遗传算法及其MATLAB程序代码

遗传算法及其MATLAB实现 主要参考书: MATLAB 6.5 辅助优化计算与设计飞思科技产品研发中心编著电子工业出版社2003.1 遗传算法及其应用陈国良等编著 人民邮电出版社1996.6 主要内容: 遗传算法简介 遗传算法的MATLAB实现 应用举例 在工业工程中,许多最优化问题性质十分复杂,很难用 传统的优化方法来求解.自1960年以来,人们对求解这类难 解问题日益增加.一种模仿生物自然进化过程的、被称为“ 进化算法(evolutionary algorithm)”的随机优化技术在解这 类优化难题中显示了优于传统优化算法的性能。目前,进化 算法主要包括三个研究领域:遗传算法、进化规划和进化 策略。其中遗传算法是迄今为止进化算法中应用最多、比较 成熟、广为人知的算法。 一、遗传算法简介 遗传算法(Genetic Algorithm, GA)最先是由美国Mic- hgan大学的John Holland于1975年提出的。遗传算法是 模拟达尔文的遗传选择和自然淘汰的生物进化过程的计算 模型。它的思想源于生物遗传学和适者生存的自然规律, 是具有“生存+检测”的迭代过程的搜索算法。遗传算法 以一种群体中的所有个体为对象,并利用随机化技术指 导对一个被编码的参数空间进行高效搜索。其中,选择、 交叉和变异构成了遗传算法的遗传操作;参数编码、初始 群体的设定、适应度函数的设计、遗传操作设计、控制参 数设定等5个要素组成了遗传算法的核心内容。 遗传算法的基本步骤: 遗传算法是一种基于生物自然选择与遗传机理的随机 搜索算法,与传统搜索算法不同,遗传算法从一组随机产 生的称为“种群(Population)”的初始解开始搜索过程。种 群中的每个个体是问题的一个解,称为“染色体(chromos ome)”。染色体是一串符号,比如一个二进制字符串。这 些染色体在后续迭代中不断进化,称为遗传。在每一代中 用“适值(fitness)”来测量染色体的好坏,生成的下一代染 色体称为后代(offspring)。后代是由前一代染色体通过交 叉(crossover)或者变异(mutation)运算形成的。 在新一代形成过程中,根据适度的大小选择部分后代,淘 汰部分后代。从而保持种群大小是常数。适值高的染色体 被选中的概率较高,这样经过若干代之后,算法收敛于最 好的染色体,它很可能就是问题的最优解或次优解。 主要步骤如下所示: (1)编码:GA在进行搜索之前先将解空间的解数据表示成 遗传空间的基因型串结构数据,这些串结构数据的不同组 合便构成了不同的点。 (2)初始群体的生成:随机产生N个初始串结构数据,每个 串结构数据称为一个个体,N个个体构成了—个群体。 GA以这N个串结构数据作为初始点开始迭代。

遗传算法matlab

% 下面举例说明遗传算法% % 求下列函数的最大值% % f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] % % 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。% % 将变量域[0,10] 离散化为二值域[0,1023], x=0+10*b/1023, 其中b 是[0,1023] 中的一个二值数。 % % % %--------------------------------------------------------------------------------------------------------------% %--------------------------------------------------------------------------------------------------------------% % 编程 %----------------------------------------------- % 2.1初始化(编码) % initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二 值数的长度), % 长度大小取决于变量的二进制编码的长度(在本例中取10位)。 %遗传算法子程序 %Name: initpop.m %初始化 function pop=initpop(popsize,chromlength) pop=round(rand(popsize,chromlength)); % rand随机产生每个单元为{0,1} 行数为popsize,列数为 chromlength的矩阵, % roud对矩阵的每个单元进行圆整。这样产生的初始种群。 % 2.2 计算目标函数值 % 2.2.1 将二进制数转化为十进制数(1) %遗传算法子程序 %Name: decodebinary.m %产生[2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制 function pop2=decodebinary(pop) [px,py]=size(pop); %求pop行和列数 for i=1:py pop1(:,i)=2.^(py-i).*pop(:,i); end pop2=sum(pop1,2); %求pop1的每行之和 % 2.2.2 将二进制编码转化为十进制数(2) % decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制 串的起始位置 % (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一 个变量从11开始。本例为1), % 参数1ength表示所截取的长度(本例为10)。 %遗传算法子程序

基于遗传算法的最短路径问题及其MATLAB实现_张书源

TRANSPOWORLD 2009 No.12 (Jun) 104前言 在现实生活中,我们经常遇到最短路问题,例如寻找两点之间总长度最短或者费用最低的路径。在运输、物流、设施选址以及人员调度问题中,最短路径是很常见的问题。解决最短路问题的方法有很多,例如迪杰斯特拉算法、福特算法。在这里我们介绍基于遗传算法的最短路径问题的解决方案。 模型 遗传算法基本模型 遗传算法是模仿生物进化过程,针对复杂问题开发出来的非常有效的方 基于遗传算法的最短路径问题及其MATLAB 实现 文/张书源 郭 聪 法。根据生物进化过程中的选择机制,在问题的解空间中进行选择,实现“物竞天择,适者生存”。在遗传算法中,一条染色体代表问题的一个可行解,该染色体的适应值即为对应于该可行解的函数值。一般来说,遗传算法包括以下几个主要组成部分。编码 即将问题的解表示成一个编码串(染色体),每一染色体对应问题的一 个解。遗传过程 对染色体进行操作,以产生新的染色体,通常有不同染色体之间的交叉 操作以及一条染色体的变异操作。评价与选择 对每条染色体计算其适应值,用以评价染色体的优劣,从而从父代和子代中选择较优的染色体,进入下一代的繁殖。 初试种群的创建方法 其作为问题可行解的集合。初始种群中染色体个数称为种群规模。 遗传算法的流程图如图1所示。算法过程如下: 第一步初始化种群p(t);第二步对种群进行评价; 第三步利用交叉和变异重组p(t)以产生c(t) 第四步评价c(t),从p(t)和c(t)选择出p(t+1),令t=t+1;若达到繁殖代数,转第五步;否则,回第四步; 第五步返回结果。 问题描述 在图2所示的算例中,我们要找到从节点①到节点⑨的最短路径。基于优先权的编码方式 例如,一条可能的染色体如表1。路径生长 路径生长即为根据一条染色体来得到其对应的一条路。在表1的例子中,路径生长的过程如下: 初试路径上只有节点①; 与①相连且不在当前路径上的节点有②和③,其中节点③的权较大,为6,将节点③加入当前路径,当前路径变为:①—③; 与③相连且不在当前路径上的节 点有④和⑤,其中节点⑤的权较大,为 图2 C OLUMNS 特别企划

遗传算法-matlab

4.2遗传算法MATLAB程序设计 4.2.1程序设计流程及参数选取 4.2.1.1遗传算法程序设计伪代码 BEGIN t = 0 ; %Generations NO. 初始化P(t) ; %Initial Population or Chromosomes 计算P(t) 的适应值; while (不满足停止准则) do begin t = t+1 ; 从P(t-1)中选择P(t) ; % Selection 重组P(t) ; % Crossover and Mutation 计算P(t) 的适应值; end END 4.2.1.2遗传算法的参数设计原则 在单纯的遗传算法当中,也并不总是收敛,即使在单峰或单调也是如此。这是因为种群的进化能力已经基本丧失,种群早熟。为了避免种群的早熟,参数的设计一般遵从以下原则[5]: (1)种群的规模:当群体规模太小时,很明显会出现近亲交配,产生病态基因。而且造成有效等位基因先天缺乏,即使采用较大概率的变异算子,生成具有竞争力高阶模式的可能性仍很小,况且大概率变异算子对已有模式的破坏作用极大。同时遗传算子存在随机误差(模式采样误差),妨碍小群体中有效模式的正确传播,使得种群进化不能按照模式定理产生所预测的期望数量;种群规模太大,结果难以收敛且浪费资源,稳健性下降。种群规模的一个建议值为0~100。 (2)变异概率:当变异概率太小时,种群的多样性下降太快,容易导致有效基因的迅速丢失且不容易修补;当变异概率太大时,尽管种群的多样性可以得到保证,但是高阶模式被破坏的概率也随之增大。变异概率一般取0.0001~0.2。 (3)交配概率:交配是生成新种群最重要的手段。与变异概率类似,交配概率太大容易破坏已有的有利模式,随机性增大,容易错失最优个体;交配概率太小不能有效更新种群。交配概率一般取0.4~0.99。 (4)进化代数:进化代数太小,算法不容易收敛,种群还没有成熟;代数太大,算法已经熟练或者种群过于早熟不可能再收敛,继续进化没有意义,只会增加时间开支和资源浪费。进化代数一般取100~500。 (5)种群初始化:初始种群的生成是随机的;在初始种群的赋予之前,尽量进行一个大概的区间估计,以免初始种群分布在远离全局最优解的编码空间,导致遗传算法的搜索范围受到限制,同时也为算法减轻负担。

标准遗传算法的MATLAB实现

%标准遗传算法 %优化函数为f=-(x-1)^2+4,其中,0<=x<=3 %编码长度为10位,编码精度为0.0029 %种群规模设为40,遗传算子分别为比例选择,单点交叉和单点变异。交叉概率0.7,变异概率0.1 %最大进化代数为200代,保优操作。 main.m initial; global G; for G=1:200 crossover; mutation; adapting; keepbest; selection; end result; %初始化函数,随机形成规模为40初始种群 initial.m pop(40,10)=0; best_individual(10)=0; %最优个体 adapt_ave(200)=0; %种群平均适应值 for i=1:40 for j=1:10 if rand>0.5 pop(i,j)=1; else pop(i,j)=0; end end end % pop clear i; clear j; %交叉操作,概率为0.7,单点交叉 crossover.m for i=1:2:39 cross_P=rand; %随机产生一个数,以比较交叉概率 if cross_P<0.9 %交叉概率为0.9 cross_pos=round(10*rand); %交叉位置为0~9,若位置为0或9,则不进行交叉操作if or(cross_pos==0,cross_pos==9) continue; end

for j=cross_pos:10 temp=pop(i,j); pop(i,j)=pop(i+1,j); pop(i+1,j)=temp; end end end clear i; clear j; clear temp; clear cross_P; clear cross_pos; %变异操作,单点变异,变异概率为0.1 mutation.m for i=1:40 if rand<0.1 %通过变异概率 M_pos=round(10*rand); if M_pos~=0 %若变异位为0则无意义 pop(i,M_pos)=1-pop(i,M_pos); end end end clear M_pos; clear i; %计算适应值 adapting.m for i=1:40 adapt(i)=0; end for i=1:40 for j=1:10 if pop(i,j)==1 adapt(i)=adapt(i)+2^(10-j); end end adapt(i)=adapt(i)*0.0029; adapt(i)=-(adapt(i)-1).^2+4; end global adapt_best; global best_pos; adapt_best=0; %最佳个体 best_pos=0; %最佳个体在种群中的位置

遗传算法matlab实现源程序

附页: 一.遗传算法源程序: clc; clear; population; %评价目标函数值 for uim=1:popsize vector=population(uim,:); obj(uim)=hanshu(hromlength,vector,phen); end %obj %min(obj)

clear uim; objmin=min(obj); for sequ=1:popsize if obj(sequ)==objmin opti=population(sequ,:); end end clear sequ; fmax=22000; %== for gen=1:maxgen %选择操作 %将求最小值的函数转化为适应度函数 for indivi=1:popsize obj1(indivi)=1/obj(indivi); end clear indivi; %适应度函数累加总合 total=0; for indivi=1:popsize total=total+obj1(indivi); end clear indivi; %每条染色体被选中的几率

for indivi=1:popsize fitness1(indivi)=obj1(indivi)/total; end clear indivi; %各条染色体被选中的范围 for indivi=1:popsize fitness(indivi)=0; for j=1:indivi fitness(indivi)=fitness(indivi)+fitness1(j); end end clear j; fitness; %选择适应度高的个体 for ranseti=1:popsize ran=rand; while (ran>1||ran<0) ran=rand; end ran; if ran<=fitness(1) newpopulation(ranseti,:)=population(1,:); else for fet=2:popsize if (ran>fitness(fet-1))&&(ran<=fitness(fet))

遗传算法优化相关MATLAB算法实现

遗传算法 1、案例背景 遗传算法(Genetic Algorithm , GA)是一种进化算法,其基本原理是仿效生物界中的"物竞大择、适者生存”的演化法则。遗传算法的做法是把问题参数编码为染色体,再利用迭代的 方式进行选择、交叉以及变异等运算来交换种群中染色体的信息,最终生成符合优化目标的 染色体。 在遗传算法中,染色体对应的是数据或数组,通常是由一维的串结构数据来表示,串上各个位置对应基因的取值。基因组成的串就是染色体,或者叫基因型个体(Individuals)。一定数量的个体组成了群体(Population)。群体中个体的数目称为群体大小( Population Size),也叫群体规模。而各个个体对环境的适应程度叫做适应度(Fitness)。 2、遗传算法中常用函数 1) 创建种群函数一crtbp 2) 适应度计算函数一ranking 3) 选择函数一select 4) 交叉算子函数一recombin 5) 变异算子函数一mut 6) 选择函数一reins 7) 实用函数一bs2rv 8) 实用函数一rep 3、主程序: 1. 简单一元函数优化: clc clear all close all %%画出函数图 figure(1); hold on; lb=1;ub=2; %函数自变量范围【1,2】 ezplot('sin(10*pi*X)/X',[lb,ub]); % 画出函数曲线xlabel('自变量/X') ylabel('函数值/Y') %%定义遗传算法参数 NIND=40; %个体数目 MAXGEN=20; %最大遗传代数 PRECI=20;寇量的二进制位数 GGAP=0.95;妣沟 px=0.7; %交叉概率 pm=0.01; %变异概率

遗传算法经典MATLAB代码

遗传算法经典学习Matlab代码 下面举例说明遗传算法 求下列函数的最大值 f(x)=10*sin(5x)+7*cos(4x)x∈[0,10] 将x的值用一个10位的二值形式表示为二值问题,一个10位的二 值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01 将变量域[0,10]离散化为二值域[0,1023],x=0+10*b/1023,其中b是[0,1023]中的一个二值数。 编程 2.1初始化(编码) initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度), 长度大小取决于变量的二进制编码的长度(在本例中取10位)。 遗传算法子程序 Name:initpop.m 初始化 functionpop=initpop(popsize,chromlength) pop=round(rand(popsize,chromlength));%rand随机产生每个单元 为{0,1}行数为popsize,列数为chromlength的矩阵, %roud对矩阵的每个单元进行圆整。这样产生的初始种群。pop每个元素为0或1 2.2计算目标函数值 2.2.1将二进制数转化为十进制数(1) 遗传算法子程序 Name:decodebinary.m 产生[2^n2^(n-1)...1]的行向量,然后求和,将二进制转化为十进制

functionpop2=decodebinary(pop) [px,py]=size(pop);%求pop行和列数 fori=1:py pop1(:,i)=2.^(py-i).*pop(:,i); end pop2=sum(pop1,2);%求pop1的每行之和 2.2.2将二进制编码转化为十进制数(2) decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置 (对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),参数1ength表示所截取的长度(本例为10)。 遗传算法子程序 Name:decodechrom.m 将二进制编码转换成十进制 functionpop2=decodechrom(pop,spoint,length) pop1=pop(:,spoint:spoint+length-1); pop2=decodebinary(pop1); 2.2.3计算目标函数值 calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。 遗传算法子程序 Name:calobjvalue.m 实现目标函数的计算 function[objvalue]=calobjvalue(pop,chromlength) temp1=decodechrom(pop,1,chromlength);%将pop每行转化成十进制数

遗传算法MATLAB仿真程序

% function [pso F] = PSO_2D() % FUNCTION PSO --------USE Particle Swarm Optimization Algorithm %global present; % close all; pop_size = 10; % pop_size 种群大小 part_size = 2; % part_size 粒子大小, ** =n-D gbest = zeros(1,part_size+1); % gbest 当前搜索到的最小的值 max_gen = 80; % max_gen 最大迭代次数 region=zeros(part_size,2); % 设定搜索空间范围 region=[-3,3;-3,3]; % **每一维设定不同范围 rand('state',sum(100*clock)); % 重置随机数发生器状态 arr_present = ini_pos(pop_size,part_size); % present 当前位置,随机初始 化,rand()的范围为0~1 v=ini_v(pop_size,part_size); % 初始化当前速度 pbest = zeros(pop_size,part_size+1); % pbest 粒子以前搜索到的最优值,最后 一列包括这些值的适应度 w_max = ; % w_max 权系数最大值 w_min = ; v_max = 2; % **最大速度,为粒子的范围宽度 c1 = 2; % 学习因子

c2 = 2; % 学习因子 best_record = zeros(1,max_gen); % best_record记录最好的粒子的适应度。 % ———————————————————————— % 计算原始种群的适应度,及初始化 % ———————————————————————— arr_present(:,end)=ini_fit(arr_present,pop_size,part_size); % for k=1:pop_size % present(k,end) = fitness(present(k,1:part_size)); %计算原始种群的适应度% end pbest = arr_present; %初始化各个粒子最优值 [best_value best_index] = min(arr_present(:,end)); %初始化全局最优,即适应度为全局最小的值,根据需要也可以选取为最大值 gbest = arr_present(best_index,:); %v = zeros(pop_size,1); % v 速度 % ———————————————————————— % 迭代 % ———————————————————————— % global m; % m = moviein(1000); %生成帧矩阵 x=[-3::3]; y=[-3::3]; z=@(x,y) 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ... - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ... - 1/3*exp(-(x+1).^2 - y.^2);

相关文档
相关文档 最新文档