姓名:李嘉蔚 学号16020520034
【嵌牛导读】:简单地说,遗传算法是一种解决问题的方法。它模拟大自然中种群在选择压力下的演化,从而得到问题的一个近似解。在二十世纪五十年代,生物学家已经知道基因在自然演化过程中的作用了,而他们也希望能在新出现的计算机上模拟这个过程,用以尝试定量研究基因与进化之间的关系。这就是遗传算法的滥觞。后来,有人将其用于解决优化问题,于是就产生了遗传算法。无论如何,如果我们要将遗传算法的发明归功于一个人的话,我会将它归功于达尔文,进化论的奠基人。如果我们不知道自然演化的过程,我们也不可能在电脑中模拟它,更不用说将它应用于实际了。
向达尔文致敬!
【嵌牛鼻子】:⑴ 选择 ⑵ 交叉 ⑶ 变异;遗传算子;繁殖;种群;
【嵌牛提问】:什么是遗传算法?有什么简单应用?
【嵌牛正文】:
智能优化算法又称为现代启发式算法,
是一种具有全局优化性能、通用性强、
且适合于并行处理的算法。这种算法一
般具有严密的理论依据,而不是单纯凭
借专家经验,理论上可以在一定的时间
内找到最优解或近似最优解。
常用的智能优化算法
(1)遗传算法
(Genetic Algorithm, 简称GA)
(2)模拟退火算法
(Simulated Annealing, 简称SA)
(3)禁忌搜索算法
(Tabu Search, 简称TS)
蚁群算法,粒子群算法,……
智能优化算法的特点
它们的共同特点:都是从任一解出发,按
照某种机制,以一定的概率在整个求解空
间中探索最优解。由于它们可以把搜索空
间扩展到整个问题空间,因而具有全局优
化性能。
遗传算法是解决搜索问题的一种通用算法,
对于各种通用问题都可以使用。
搜索算法的共同特征为:
① 首先组成一组候选解;
② 依据某些适应性条件测算这些候选解
的适应度;
③ 根据适应度保留某些候选解,放弃其
他候选解;
④ 对保留的候选解进行某些操作,生成
新的候选解。
遗传算法:模拟生物在自然环境中的遗传
和进化过程,对设计变量经编码形成的基因种
群反复进行选择、交叉和变异运算,按适应度
函数(目标函数)值的大小实行优胜劣汰的演
变,最后保留适应度最大,即目标函数最大的
个体作为优化问题的最优解。
编码运算演变最优化:求解,分类,聚类
遗传算法基本原理
模拟自然界优胜劣汰的进化现象,把搜索空间映射为遗传
空间,把可能的解进行编码形成一个向量——染色体,向量的每
个元素称为基因。
通过不断计算各染色体的适应值,选择最好的染色体,获 得最优解。
遗传算法的基本运算
⑴ 选择
⑵ 交叉
⑶ 变异
![](https://img.haomeiwen.com/i7939256/287e6568c912d08e.png)
遗传算法的本质
遗传算法本质上是对染色体模式所进行
的一系列运算,即通过选择算子将当前种群
中的优良模式遗传到下一代种群中,利用交
叉算子进行模式重组,利用变异算子进行模
式突变。通过这些遗传操作,模式逐步向较
好的方向进化,最终得到问题的最优解。
遗传算法的应用领域
(1)组合优化 (2)函数优化
(3)自动控制 (4)生产调度
(5)图像处理 (6)机器学习
(7)人工生命 (8)数据挖掘
![](https://img.haomeiwen.com/i7939256/c73e6354c14928b0.png)
遗传算法基本要素
遗传算法中包含了如下五个基本要素:
1)问题编码
2)初始群体的设定
3)适应值函数的设计
4)遗传操作设计
5)控制参数设定(主要是指群体大小和使用遗传
操作的概率等)
这五个要素构成了遗传算法的核心内容。
适应值函数的确定
适应值函数是根据目标函数确定的。适应值总是
非负的,任何情况下总是希望越大越好。
适应值函数的选取至关重要,它直接影响到算法
的收敛速度即最终能否找到最优解。
函数优化问题可直接将目标函数本身作为适应值 函数。
控制参数
参数主要有个体编码长度、群体大小M、
交叉概率Pc、变异概率Pm、终止代数T等
这些参数对遗传算法的运行影响很大,
需要认真选择。
遗传算法实例
问题:求发f(x)=x
2在[0,31]上的最大值(当然是31 ^2)
一、初始种群
1.编码:用五位二进制表示x,有
x=0 → 0 0 0 0 0 x=31 → 1 1 1 1 1
2.初始种群
随机产生4个个体:13 , 24 , 8 ,19
3.适应值fi
直接用目标函数作为适应值:f i =xi
其适应度函数特点
(1)非负 ; (2)逐步增大
4.选择率ps和期望值
选择率: ps=fi/∑fi
平均适应值: f =∑fi/n 期望值: fi/f
5.实选值期望值取整数 .
下面来看三个遗传算法程序。
遗传算法程序(一):
说明: 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<UB):');
end
s=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));
disp(s);
global m n NewPop children1 children2 VarNum
bounds=[LB;UB]';bits=[];VarNum=size(bounds,1);
precision=options(2);%由求解精度确定二进制编码长度
bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间
[Pop]=InitPopGray(popsize,bits);%初始化种群
[m,n]=size(Pop);
NewPop=zeros(m,n);
children1=zeros(1,n);
children2=zeros(1,n);
pm0=pMutation;
BestPop=zeros(eranum,n);%分配初始解空间BestPop,Trace
Trace=zeros(eranum,length(bits)+1);
i=1;
while i<=eranum
for j=1:m
value(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度
end
[MaxValue,Index]=max(value);
BestPop(i,:)=Pop(Index,:);
Trace(i,1)=MaxValue;
Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);
[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择
[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));
%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率
%round(unidrnd(eranum-i)/eranum)
[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异
[InversionPop]=Inversion(MutationPop,pInversion);%倒位
Pop=InversionPop;%更新
pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);
%随着种群向前进化,逐步增大变异率至1/2交叉率
p(i)=pMutation;
i=i+1;
end
t=1:eranum;
plot(t,Trace(:,1)');
title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');
[MaxFval,I]=max(Trace(:,1));
X=Trace(I,(2:length(bits)+1));
hold on; plot(I,MaxFval,'*');
text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);
str1=sprintf ('进化到 %d 代 ,自变量为 %s 时,得本次求解的最优值 %f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:)));
disp(str1);
%figure(2);plot(t,p);%绘制变异值增大过程
T2=clock;
elapsed_time=T2-T1;
if elapsed_time(6)<0
elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;
end
if elapsed_time(5)<0
elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;
end %像这种程序当然不考虑运行上小时啦
str2=sprintf('程序运行耗时 %d 小时 %d 分钟 %.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));
disp(str2);
%初始化种群
%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点
function [initpop]=InitPopGray(popsize,bits)
len=sum(bits);
initpop=zeros(popsize,len);%The whole zero encoding individual
for i=2:popsize-1
pop=round(rand(1,len));
pop=mod(([0 pop]+[pop 0]),2);
%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)
%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)
initpop(i,:)=pop(1:end-1);
end
initpop(popsize,:)=ones(1,len);%The whole one encoding individual
%解码
function [fval] = b2f(bval,bounds,bits)
% fval - 表征各变量的十进制数
% bval - 表征各变量的二进制编码串
% bounds - 各变量的取值范围
% bits - 各变量的二进制编码长度
scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variables
numV=size(bounds,1);
cs=[0 cumsum(bits)];
for i=1:numV
a=bval((cs(i)+1):cs(i+1));
fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);
end
%选择操作
%采用基于轮盘赌法的非线性排名选择
%各个体成员按适应值从大到小分配选择概率:
%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中 P(0)>P(1)>...>P(n), sum(P(i))=1
function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)
global m n
selectpop=zeros(m,n);
fit=zeros(m,1);
for i=1:m
fit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据
end
selectprob=fit/sum(fit);%计算各个体相对适应度(0,1)
q=max(selectprob);%选择最优的概率
x=zeros(m,2);
x(:,1)=[m:-1:1]';
[y x(:,2)]=sort(selectprob);
r=q/(1-(1-q)^m);%标准分布基值
newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率
newfit=cumsum(newfit);%计算各选择概率之和
rNums=sort(rand(m,1));
fitIn=1;newIn=1;
while newIn<=m
if rNums(newIn)<newfit(fitIn)
selectpop(newIn,:)=pop(fitIn,:);
newIn=newIn+1;
else
fitIn=fitIn+1;
end
end
%交叉操作
function [NewPop]=CrossOver(OldPop,pCross,opts)
%OldPop为父代种群,pcross为交叉概率
global m n NewPop
r=rand(1,m);
y1=find(r<pCross);
y2=find(r>=pCross);
len=length(y1);
if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数
y2(length(y2)+1)=y1(len);
y1(len)=[];
end
if length(y1)>=2
for i=0:2:length(y1)-2
if opts==0
[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));
else
[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:));
end
end
end
NewPop(y2,:)=OldPop(y2,:);
%采用均匀交叉
function [children1,children2]=EqualCrossOver(parent1,parent2)
global n children1 children2
hidecode=round(rand(1,n));%随机生成掩码
crossposition=find(hidecode==1);
holdposition=find(hidecode==0);
children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因
children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因
children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因
children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因
%采用多点交叉,交叉点数由变量数决定
function [Children1,Children2]=MultiPointCross(Parent1,Parent2)
global n Children1 Children2 VarNum
Children1=Parent1;
Children2=Parent2;
Points=sort(unidrnd(n,1,2*VarNum));
for i=1:VarNum
Children1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));
Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));
end
%变异操作
function [NewPop]=Mutation(OldPop,pMutation,VarNum)
global m n NewPop
r=rand(1,m);
position=find(r<=pMutation);
len=length(position);
if len>=1
for i=1:len
k=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点
for j=1:length(k)
if OldPop(position(i),k(j))==1
OldPop(position(i),k(j))=0;
else
OldPop(position(i),k(j))=1;
end
end
end
end
NewPop=OldPop;
%倒位操作
function [NewPop]=Inversion(OldPop,pInversion)
global m n NewPop
NewPop=OldPop;
r=rand(1,m);
PopIn=find(r<=pInversion);
len=length(PopIn);
if len>=1
for i=1:len
d=sort(unidrnd(n,1,2));
if d(1)~=1&d(2)~=n
NewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);
NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1));
NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);
end
end
end
遗传算法程序(二):
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(tmpind)];
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 F2 and F3
F1=A(:,1);
F2=A(:,2);
F3=A(:,3);
if (max(F2)>1450)||(min(F2)<=900)
error('DATA property F2 exceed it''s range (900,1450]')
end
% get group property F1 of data, according to F2 value
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;
% 这里有待优化
for k=1:N
FF4k=FF4rnd(:,k);
for ite=1:11
F0index=find(FF4k==ite);
if ~isempty(F0index)
tmpMat=F3(F0index);
tmpSco=sum(tmpMat);
ScoreBin(ite)=mod(tmpSco,300);
end
end
Scorek(k)=sum(ScoreBin);
end
ScoreN=ScoreN-Scorek;
遗传算法程序(三):
%IAGA
function best=ga
clear
MAX_gen=200; %最大迭代步数
best.max_f=0; %当前最大的适应度
STOP_f=14.5; %停止循环的适应度
RANGE=[0 255]; %初始取值范围[0 255]
SPEEDUP_INTER=5; %进入加速迭代的间隔
advance_k=0; %优化的次数
popus=init; %初始化
for gen=1:MAX_gen
fitness=fit(popus,RANGE); %求适应度
f=fitness.f;
picked=choose(popus,fitness); %选择
popus=intercross(popus,picked); %杂交
popus=aberrance(popus,picked); %变异
if max(f)>best.max_f
advance_k=advance_k+1;
x_better(advance_k)=fitness.x;
best.max_f=max(f);
best.popus=popus;
best.x=fitness.x;
end
if mod(advance_k,SPEEDUP_INTER)==0
RANGE=minmax(x_better);
RANGE
advance=0;
end
end
return;
function popus=init%初始化
M=50;%种群个体数目
N=30;%编码长度
popus=round(rand(M,N));
return;
function fitness=fit(popus,RANGE)%求适应度
[M,N]=size(popus);
fitness=zeros(M,1);%适应度
f=zeros(M,1);%函数值
A=RANGE(1);B=RANGE(2);%初始取值范围[0 255]
for m=1:M
x=0;
for n=1:N
x=x+popus(m,n)*(2^(n-1));
end
x=x*((B-A)/(2^N))+A;
for k=1:5
f(m,1)=f(m,1)-(k*sin((k+1)*x+k));
end
end
f_std=(f-min(f))./(max(f)-min(f));%函数值标准化
fitness.f=f;fitness.f_std=f_std;fitness.x=x;
return;
function picked=choose(popus,fitness)%选择
f=fitness.f;f_std=fitness.f_std;
[M,N]=size(popus);
choose_N=3; %选择choose_N对双亲
picked=zeros(choose_N,2); %记录选择好的双亲
p=zeros(M,1); %选择概率
d_order=zeros(M,1);
%把父代个体按适应度从大到小排序
f_t=sort(f,'descend');%将适应度按降序排列
for k=1:M
x=find(f==f_t(k));%降序排列的个体序号
d_order(k)=x(1);
end
for m=1:M
popus_t(m,:)=popus(d_order(m),:);
end
popus=popus_t;
f=f_t;
p=f_std./sum(f_std); %选择概率
c_p=cumsum(p)'; %累积概率
for cn=1:choose_N
picked(cn,1)=roulette(c_p); %轮盘赌
picked(cn,2)=roulette(c_p); %轮盘赌
popus=intercross(popus,picked(cn,:));%杂交
end
popus=aberrance(popus,picked);%变异
return;
function popus=intercross(popus,picked) %杂交
[M_p,N_p]=size(picked);
[M,N]=size(popus);
for cn=1:M_p
p(1)=ceil(rand*N);%生成杂交位置
p(2)=ceil(rand*N);
p=sort(p);
t=popus(picked(cn,1),p(1):p(2));
popus(picked(cn,1),p(1):p(2))=popus(picked(cn,2),p(1):p(2));
popus(picked(cn,2),p(1):p(2))=t;
end
return;
function popus=aberrance(popus,picked) %变异
P_a=0.05;%变异概率
[M,N]=size(popus);
[M_p,N_p]=size(picked);
U=rand(1,2);
for kp=1:M_p
if U(2)>=P_a %如果大于变异概率,就
变异
continue;
end
if U(1)>=0.5
a=picked(kp,1);
else
a=picked(kp,2);
end
p(1)=ceil(rand*N);%生成变异位置
p(2)=ceil(rand*N);
if popus(a,p(1))==1%0 1变换
popus(a,p(1))=0;
else
popus(a,p(1))=1;
end
if popus(a,p(2))==1
popus(a,p(2))=0;
else
popus(a,p(2))=1;
end
end
return;
function picked=roulette(c_p) %轮盘赌
[M,N]=size(c_p);
M=max([M N]);
U=rand;
if U<c_p(1)
picked=1;
return;
end
for m=1:(M-1)
if U>c_p(m) & U<c_p(m+1)
picked=m+1;
break;
end
end
全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)
遗传算法优化pid参数matlab程序
chap5_4m
%GA(Generic Algorithm) program to optimize Parameters of PID
clear all;
clear all;
global rin yout timef
G=100;
Size=30;
CodeL=10;
MinX(1)=zeros(1);
MaxX(1)=20*ones(1);
MinX(2)=zeros(1);
MaxX(2)=1.0*ones(1);
MinX(3)=zeros(1);
MaxX(3)=1.0*ones(1);
E=round(rand(Size,3*CodeL));%Initian Code!
BsJ=0;
for kg=1:1:G
time(kg)=kg;
for s=1:1:Size
m=E(s,:);
y1=0;y2=0;y3=0;
m1=m(1:1:CodeL);
for i=1:1:CodeL
y1=y1+m1(i)*2^(i-1);
end
Kpid(s,1)=(MaxX(1)-MinX(1))*y1/1023+MinX(1);
m2=m(CodeL+1:1:2*CodeL);
for i=1:1:CodeL
y2=y2+m2(i)*2^(i-1);
end
Kpid(s,2)=(MaxX(2)-MinX(2))*y2/1023+MinX(2);
m3=m(2*CodeL+1:1:3*CodeL);
for i=1:1:CodeL
y3=y3+m3(i)*2^(i-1);
end
Kpid(s,3)=(MaxX(3)-MinX(3))*y3/1023+MinX(3);
%*******Step 1:Evaluate Best J*******
Kpidi=Kpid(s,:);
[Kpidi,BsJ]=chap5_3f(Kpidi,BsJ);
BsJi(s)=BsJ;
end
[OderJi,IndexJi]=sort(BsJi);
BestJ(kg)=OderJi(1);
BJ=BestJ(kg);
Ji=BsJi+1e-10;
fi=1./Ji;
%Cm=max(Ji);
%fi=Cm-Ji; %Avoiding deviding zero
[Oderfi,Indexfi]=sort(fi);%Arranging fi small to bigger
%Bestfi=Oderfi(Size); %Let Bestfi=max(fi)
%BestS=Kpid(Indexfi(Size),:); %Let BestS=E(m),m is the Indexfi belong to
%max(fi)
Bestfi=Oderfi(Size);%Let Bestfi=max(fi)
BestS=E(Indexfi(Size),:);%Let BestS=E(m),m is the Indexfi belong to max(fi)
kg
BJ
BestS;
%****Step 2:Select and Reproduct Operation***
fi_sum=sum(fi);
fi_Size=(Oderfi/fi_sum)*Size;
fi_S=floor(fi_Size); %Selecting Bigger fi value
kk=1;
for i=1:1:Size
for j=1:1:fi_S(i) %Select and Reproduce
TempE(kk,:)=E(Indexfi(i),:);
kk=kk+1; %kk is used to reproduce
end
end
%**********Step 3:Crossover Operation******
pc=0.06;
n=ceil(20*rand);
for i=1:2:(Size-1)
temp=rand;
if pc>temp
for j=n:1:20
TempE(i,j)=E(i+1,j);
TempE(i+1,j)=E(i,j);
end
end
end
TempE(Size,:)=BestS;
E=TempE;
%***************Step 4: Mutation Operation**************
%pm=0.001;
pm=0.001-[1:1:Size]*(0.001)/Size;%Bigger fi,smaller pm
%pm=0.0; %No mutation
%pm=0.1; %Big mutation
for i=1:1:Size
for j=1:1:3*CodeL
temp=rand;
if pm>temp %Mutation Condition
if TempE(i,j)==0
TempE(i,j)=1;
else
TempE(i,j)=0;
end
end
end
end
%Guarantee TempE(Size,:)belong to the best individual
TempE(Size,:)=BestS;
E=TempE;
%***************************************************
end
Bestfi
BestS
Kpidi
Best_J=BestJ(G)
figure(1);
plot(time,BestJ);
xlabel('Time');ylabel('Best J');
figure(2);
plot(timef,rin,'r',timef,yout,'b');
xlabel('Time(s)');ylabel('ran,yout');
******************************************************
chap5_3f.m
function [Kpidi,BsJ]=pid_gaf(Kpidi,BsJ)
global rin yout timef
ts=0.001;
sys=tf(400,[1,50,0]);
dsys=c2d(sys,ts,'z');
[num,den]=tfdata(dsys,'v');
rin=1.0;
u_1=0.0;u_2=0.0;
y_1=0.0;y_2=0.0;
x=[0,0,0]';
B=0;
error_1=0;
tu=1;
s=0;
P=100;
for k=1:1:P
timef(k)=k*ts;
r(k)=rin;
u(k)=Kpidi(1)*x(1)+Kpidi(2)*x(2)+Kpidi(3)*x(3);
if u(k)>=10
u(k)=10;
end
if u(k)<=-10
u(k)=-10;
end
yout(k)=-den(2)*y_1-den(3)*y_2+num(2)*u_1+num(3)*u_2;
error(k)=r(k)-yout(k);
%-------------------Return of PID parameters----------------
u_2=u_1;u_1=u(k);
y_2=y_1;y_1=yout(k);
x(1)=error(k); % Calculating P
x(2)=(error(k)-error_1)/ts; % D
x(3)=x(3)+error(k)*ts; % I
error_2=error_1;
error_1=error(k);
if s==0
if yout(k)>0.95&yout(k)<1.05
tu=timef(k);
s=1;
end
end
end
for i=1:1:P
Ji(i)=0.999*abs(error(i))+0.01*u(i)^2*0.1;
B=B+Ji(i);
if i>1
erry(i)=yout(i)-yout(i-1);
if erry(i)<0
B=B+100*abs(erry(i));
end
end
end
Bsj=B+0.2*tu*10
再看看遗传算法的matlab程序。
此处应该有张图。
![](https://img.haomeiwen.com/i7939256/68ec213405e097d8.jpg)
clear all;
clc;
f=@(x,y)sin(x)*sin(y)/(x*y);
%f=@(x,y)0.9*exp(-((x+5)^2+(y+5)^2)/10)+0.99996*exp(-((x-5)^2+(y-5)^2)/20);
x1=(vpa(rand(1,50)+1,6)-1.5)*20; %在[-10,10]之间产生50个体的x种群,精度为0.00001
y1=(vpa(rand(1,50)+1,6)-1.5)*20; %在[-10,10]之间产生50个体的y种群,精度为0.00001
x2=floor(double((x1+10)*10000));
y2=floor(double((y1+10)*10000)); %处理数据,避免小数和负数
S=zeros(1,50);
N=zeros(1,50);
MAX=zeros(1,100); %函数最大值
Mx=zeros(1,100); %函数最大值对应x值
My=zeros(1,100); %函数最大值对应y值
Nc=[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %随机交叉位产生数组,交叉位为总位长一半
Nm=[1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %随机变异位产生数组,变异位4
for G=1:100
%以下为交叉
x2=x2(randperm(numel(x2))); %将种群个体顺序打乱,等效随机选择个体进行交叉
y2=y2(randperm(numel(y2)));
x3=x2;
y3=y2;
for j=1:22 %每次繁殖进行交叉的个体数分别为20,28,36,44
w=1; %溢出标志,0为未溢出,1为溢出
while w==1
Nc=Nc(randperm(numel(Nc))); %产生随机交叉位掩码
for k=1:18
if Nc(k)==1
temp1=bitget(x2(2*j-1),k);
temp2=bitget(x2(2*j),k);
x3(2*j-1)=bitset(x2(2*j-1),k,temp2);
x3(2*j)=bitset(x2(2*j),k,temp1);
end;
end;
for k=19:36
if Nc(k)==1
temp1=bitget(y2(2*j-1),k-18);
temp2=bitget(y2(2*j),k-18);
y3(2*j-1)=bitset(y2(2*j-1),k-18,temp2);
y3(2*j)=bitset(y2(2*j),k-18,temp1);
end;
end;
w=0;
if x3(2*j-1)>200000||x3(2*j-1)<0||y3(2*j-1)>200000||y3(2*j-1)<0||x3(2*j)>200000||x3(2*j)<0||y3(2*j)>200000||y3(2*j)<0
w=1;
end;
end;
x2=x3;
y2=y3;
end;
%以下为变异
x2=x2(randperm(numel(x2))); %将种群个体顺序打乱,等效为随机选择个体进行变异
y2=y2(randperm(numel(x2)));
x3=x2;
y3=y2;
for k=1:15 %变异个体数分别为1,5,10,15
w=1;
while w==1
Nm=Nm(randperm(numel(Nm)));
for p=1:18
if Nm(p)==1
temp3=bitget(x2(k),p);
temp3=~temp3;
x3(k)=bitset(x3(k),p,temp3);
end;
end;
for p=19:36
if Nm(p)==1
temp3=bitget(y2(k),p-18);
temp3=~temp3;
y3(k)=bitset(y2(k),p-18,temp3);
end;
end;
w=0;
if x3(k)<0||x3(k)>200000||y3(k)<0||y3(k)>200000
w=1;
end;
end;
x2=x3;
y2=y3;
end;
%以下为选择复制
x1=x2/10000-10;
y1=y2/10000-10;
for i=1:50
S(i)=f (x1(i),y1(i));
end;
sum=0;
for i=1:50
sum=sum+S(i);
end;
if sum<0
sum=sum*(-1);
end;
for i=1:50
N(i)=50*S(i)/sum;
end;
S= fliplr (sort(S)); %将适应值按从大到小排序
A=round(N); %复制个体数
A(2,:)=x2;
A(3,:)=y2;
[asort ind] = sort(A(1,:));
A = A(:,ind); %复制个体数由大到小排序,只复制适应值最大的50个个体
x2= fliplr (A(2,:));
y2= fliplr (A(3,:));
A= fliplr (A(1,:));
MAX(G)=S(1); %记录函数最大值
Mx(G)=x2(1)/10000-10; %记录函数最大值对应的x值
My(G)=y2(1)/10000-10; %记录函数最大值对应的y值
p=1;
for k=1:50
if A(k)< 0
A(k)=A(k)*(-1);
end;
for i=1:A(k)
if p>50
break;
end
x3(p)=x2(k);
y3(p)=y2(k);
p=p+1;
end;
end;
x2=x3;
y2=y3;
end;
G=1:100;
subplot(2,1,2);plot(G,MAX)
subplot(2,2,1);plot(G,Mx)
subplot(2,2,2);plot(G,My)
M=[MAX(100) Mx(100) My(100)]
网友评论