遺傳演算法matlab程序
❶ 求遺傳演算法的matlab程序
function
my_ga()
options=gaoptimset;
%設置變數范圍
options=gaoptimset(options,'PopInitRange',[0;9]);
%設置種群大小
options=gaoptimset(options,'PopulationSize',100);
%設置迭代次數
options=gaoptimset(options,'Generations',100);
%選擇選擇函數
options=gaoptimset(options,'SelectionFcn',@selectionroulette);
%選擇交叉函數
options=gaoptimset(options,'CrossoverFcn',@crossoverarithmetic);
%選擇變異函數
options=gaoptimset(options,'MutationFcn',@mutationuniform);
%設置繪圖:解的變化、種群平均值的變化
options=gaoptimset(options,'PlotFcns',{@gaplotbestf});
%執行遺傳演算法,fitness.m是函數文件
[x,fval]=ga(@fitness,1,options)
❷ 求一個基本遺傳演算法的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)
%
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);
%
2.4
選擇復制
%
選擇或復制操作是決定哪些個體可以進入下一代。程序中採用賭輪盤選擇法選擇,這種方法較易實現。
%
根據方程
pi=fi/∑fi=fi/fsum
,選擇步驟:
%
1)
在第
t
代,由(1)式計算
fsum
和
pi
%
2)
產生
{0,1}
的隨機數
rand(
.),求
s=rand(
.)*fsum
%
3)
求
∑fi≥s
中最小的
k
,則第
k
個個體被選中
%
4)
進行
N
次2)、3)操作,得到
N
個個體,成為第
t=t+1
代種群
%遺傳演算法子程序
%Name:
selection.m
%選擇復制
function
[newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue);
%求適應值之和
fitvalue=fitvalue/totalfit;
%單個個體被選擇的概率
fitvalue=cumsum(fitvalue);
%如
fitvalue=[1
2
3
4],則
cumsum(fitvalue)=[1
3
6
10]
[px,py]=size(pop);
ms=sort(rand(px,1));
%從小到大排列
fitin=1;
newin=1;
while
newin<=px
if(ms(newin))
評論
0
0
載入更多
❸ 怎麼用遺傳演算法求一函數的極小值,編寫matlab程序。
需要很多的子函數
%子程序:新物種交叉操作,函數名稱存儲為crossover.m
function scro=crossover(population,seln,pc);
BitLength=size(population,2);
pcc=IfCroIfMut(pc);%根據交叉概率決定是否進行交叉操作,1則是,0則否
if pcc==1
chb=round(rand*(BitLength-2))+1;%在[1,BitLength-1]范圍內隨機產生一個交叉位
scro(1,:)=[population(seln(1),1:chb) population(seln(2),chb+1:BitLength)]
scro(2,:)=[population(seln(2),1:chb) population(seln(1),chb+1:BitLength)]
else
scro(1,:)=population(seln(1),:);
scro(2,:)=population(seln(2),:);
end
%子程序:計算適應度函數,函數名稱存儲為fitnessfun.m
function [Fitvalue,cumsump]=fitnessfun(population);
global BitLength
global boundsbegin
global boundsend
popsize=size(population,1);%有popsize個個體
for i=1:popsize
x=transform2to10(population(i,:));%將二進制轉換為十進制
%轉化為[-2,2]區間的實數
xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1);
Fitvalue(i)=targetfun(xx);%計算函數值,即適應度
end
%給適應度函數加上一個大小合理的數以便保證種群適應度值為正數
Fitvalue=Fitvalue'+203;
%計算選擇概率
fsum=sum(Fitvalue);
Pperpopulation=Fitvalue/fsum;
%計算累計概率
cumsump(1)=Pperpopulation(1);
for i=2:popsize
cumsump(i)=cumsump(i-1)+Pperpopulation(i);
end
cumsump=cumsump';
%子程序:判斷遺傳運算是否需要進行交叉或變異,函數名稱存儲為IfCroIfMut.m
function pcc=IfCroIfMut(mutORcro);
test(1:100)=0;
l=round(100*mutORcro);
test(1:l)=1;
n=round(rand*99)+1;
pcc=test(n);
%子程序:新種群變異操作,函數名稱存儲為mutation.m
function snnew=mutation(snew,pmutation);
BitLength=size(snew,2);
snnew=snew;
pmm=IfCroIfMut(pmutation);%根據變異概率決定是否進行變異操作,1則是,0則否
if pmm==1
chb=round(rand*(BitLength-1))+1;%在[1,BitLength]范圍內隨機產生一個變異位
snnew(chb)=abs(snew(chb)-1);
end
%子程序:新種群選擇操作,函數名稱存儲為selection.m
function seln=selection(population,cumsump);
%從種群中選擇兩個個體
for i=1:2
r=rand;%產生一個隨機數
prand=cumsump-r;
j=1;
while prand(j)<0
j=j+1;
end
seln(i)=j;%選中個體的序號
end
%子程序:對於優化最大值或極大值函數問題,目標函數可以作為適應度函數
%函數名稱存儲為targetfun.m
function y=targetfun(x);%目標函數
%子程序:將二進制數轉換為十進制數,函數名稱存儲為transform2to10.m
function x=transform2to10(Population);
BitLength=size(Population,2);
x=Population(BitLength);
for i=1:BitLength-1
x=x+Population(BitLength-i)*power(2,i);
end
k=[0 0.1 0.2 0.3 0.5 1];
for i=1:1:5
%主程序:用遺傳演算法求解targetfun.m中目標函數在區間[-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<Generationmax+1
for j=1:2:popsize
%選擇操作
seln=selection(population,cumsump);
%交叉操作
scro=crossover(population,seln,pcrossover);
scnew(j,:)=scro(1,:);
scnew(j+1,:)=scro(2,:);
%變異操作
smnew(j,:)=mutation(scnew(j,:),pmutation);
smnew(j+1,:)=mutation(scnew(j+1,:),pmutation);
end%產生了新種群
population=smnew;
%計算新種群的適應度
[Fitvalue,cumsump]=fitnessfun(population);
%記錄當前代最好的適應度和平均適應度
[fmax,nmax]=max(Fitvalue);
fmean=mean(Fitvalue);
ymax(Generation)=fmax;
ymean(Generation)=fmean;
%記錄當前代的最佳染色體個體
x=transform2to10(population(nmax,:));
%自變數取值范圍是[-2 2],需要把經過遺傳運算的最佳染色體整合到[-2 2]區間
xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1);
xmax(Generation)=xx;
Generation=Generation+1;
end
Generation=Generation-1;
Bestpopuation=xx;
Besttargetfunvalue=targetfun(xx);
%繪制經過遺傳運算後的適應度曲線。一般地,如果進化過程中種群的平均適應度與最大適
%應度在曲線上有相互趨同的形態,表示演算法收斂進行得很順利,沒有出現震盪;在這種前
%提下,最大適應度個體連續若干代都沒有發生進化表明種群已經成熟
figure(1);
hand1=plot(1:Generation,ymax);
set(hand1,'linestyle','-','linewidth',1.8,'marker','*','markersize',6)
hold on;
hand2=plot(1:Generation,ymean);
set(hand2,'color','r','linestyle','-','linewidth',1.8,'marker','h','markersize',6)
xlabel('進化代數');ylabel('(最大/平均適應度)');xlim([1 Generationmax]);
legend('最大適應度','平均適應度');
box off;hold off;
y=(x(i)-k(i))^2-10*sin(2*pi*(x(i)-k(i)))+10;
end
❹ matlab,遺傳演算法,求大佬幫忙
用遺傳演算法求最大值問題,可以這樣來解決。
1、將最大值問題轉換為最小值問題,即 max Z =- min Z;
2、建立其自定義函數,即
z=-(f1*40^1.5/1+f2*30^1.5/2+f2*20^1.5/2+。。。+f12*127^1.5/2+f12*5^1.5/4)
其中:f1,f2,f3,。。。f11,f12為0,1變數,可以用sign()符號函數來處理。
3、用遺傳演算法ga()函數求解,使用方法
objectivef=@ga_func;
nvars=12;
[x, fval] =ga(objectivef,nvars)
4、編程運行後得到
f1=1,f2=1,f3=1,f4=0,f5=1,f6=0,f7=1,f8=1,f9=1,f10=1,f11=1,f12=1
Zmax=27329.5018
❺ matlab遺傳演算法程序
在matlab里沒有
for
i
=
1
to
80
...
endfor
這樣的語法的
在matlab里應該是:
for
i
=
1:
1:
80
...
end
1:1:80
第一個1是初始值,第二個是每次+1的意思
當然如果是我古若寡聞那也請見諒~~哈哈~~
❻ MATLAB遺傳演算法編程(多目標優化)
多目標是通過分布性 和非劣解來進行評價的
❼ 遺傳演算法的matlab代碼實現是什麼
遺傳演算法我懂,我的論文就是用著這個演算法,具體到你要遺傳演算法是做什麼?優化什麼的。。。我給你一個標准遺傳演算法程序供你參考:
該程序是遺傳演算法優化BP神經網路函數極值尋優:
%% 該代碼為基於神經網路遺傳演算法的系統極值尋優
%% 清空環境變數
clc
clear
%% 初始化遺傳演算法參數
%初始化參數
maxgen=100; %進化代數,即迭代次數
sizepop=20; %種群規模
pcross=[0.4]; %交叉概率選擇,0和1之間
pmutation=[0.2]; %變異概率選擇,0和1之間
lenchrom=[1 1]; %每個變數的字串長度,如果是浮點變數,則長度都為1
bound=[-5 5;-5 5]; %數據范圍
indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %將種群信息定義為一個結構體
avgfitness=[]; %每一代種群的平均適應度
bestfitness=[]; %每一代種群的最佳適應度
bestchrom=[]; %適應度最好的染色體
%% 初始化種群計算適應度值
% 初始化種群
for i=1:sizepop
%隨機產生一個種群
indivials.chrom(i,:)=Code(lenchrom,bound);
x=indivials.chrom(i,:);
%計算適應度
indivials.fitness(i)=fun(x); %染色體的適應度
end
%找最好的染色體
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色體
avgfitness=sum(indivials.fitness)/sizepop; %染色體的平均適應度
% 記錄每一代進化中最好的適應度和平均適應度
trace=[avgfitness bestfitness];
%% 迭代尋優
% 進化開始
for i=1:maxgen
i
% 選擇
indivials=Select(indivials,sizepop);
avgfitness=sum(indivials.fitness)/sizepop;
%交叉
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 變異
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,[i maxgen],bound);
% 計算適應度
for j=1:sizepop
x=indivials.chrom(j,:); %解碼
indivials.fitness(j)=fun(x);
end
%找到最小和最大適應度的染色體及它們在種群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次進化中最好的染色體
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;
avgfitness=sum(indivials.fitness)/sizepop;
trace=[trace;avgfitness bestfitness]; %記錄每一代進化中最好的適應度和平均適應度
end
%進化結束
%% 結果分析
[r c]=size(trace);
plot([1:r]',trace(:,2),'r-');
title('適應度曲線','fontsize',12);
xlabel('進化代數','fontsize',12);ylabel('適應度','fontsize',12);
axis([0,100,0,1])
disp('適應度 變數');
x=bestchrom;
% 窗口顯示
disp([bestfitness x]);
❽ 關於遺傳演算法的MATLAB實現
function [x fx string]=fun_SuiJiSuanFa2(N,genLenth,Pc,Pm,downbound,upbound,generation)
%[x fx string]=fun_SuiJiSuanFa2(6,16,0.7,0.01,-3,3,100)
%f 表示函數
%N表示染色體種群大小
%genLenth表示染色體長度
%Pc表示交叉概率
%Pm表示突變概率
%downbound
%upbound
%generation循環代數
%進制編碼,此處編寫為二進制
num=2;
initdata=randi([0 num-1],N,genLenth);
%二進制編碼的權值
weight=(num).^(genLenth/2-1:-1:0);
weights=repmat(weight,N,1);
%保存每代的最好值和平均值,
meanally=zeros(1,generation);
maxally=zeros(1,generation);
Nowx=zeros(generation,genLenth);
for k=1:generation
%解碼後的整數
allx1=sum(initdata(:,1:genLenth/2).*weights,2);
allx2=sum(initdata(:,genLenth/2+1:end).*weights,2);
%映射到取值范圍
delt=(upbound-downbound)/(num^(genLenth/2)-1);
allx1=allx1.*delt+downbound;
allx2=allx2.*delt+downbound;
%染色體的適應性
ally=f(allx1,allx2);
%平均值,最大值
meanally(k)=mean(ally);
maxally(k)=max(ally);
%找下標,確定是哪條染色體
index=find(ally==maxally(k));
Nowx(k,:)=initdata(index(1),:);
%最大值沒有提高就取上次的
if(k>=2&&maxally(k)<maxally(k-1))
maxally(k)=maxally(k-1);
Nowx(k,:)=Nowx(k-1,:);
end
%染色體的適應性比率
ratio=ally./sum(ally);
%交叉,變異
%??交叉幾個,從第幾個開始。
%此處只交叉1個(總共才6個),隨機給一個。
sumRatio=cumsum(ratio);
data=zeros(N,genLenth);
for i=1:N/2
Select1=find(sumRatio>=rand);
Select2=find(sumRatio>=rand);
data(2*i-1,:)=initdata(Select1(1),:);
data(2*i,:)=initdata(Select2(1),:);
if(rand<Pc)
%交叉
location=randi([1,genLenth]);
temp=data(2*i-1,location:end);
data(2*i-1,location:end)=data(2*i,location:end);
data(2*i,location:end)=temp;
else
%變異
if(rand<Pm)
location=randi([1,genLenth]);
data(2*i-1,location)=1-data(2*i-1,location);
end
if(rand<Pm)
location=randi([1,genLenth]);
data(2*i,location)=1-data(2*i,location);
end
end
end
initdata=data;
end
fx=max(maxally);
lastIndex=find(maxally==fx);
string=Nowx(lastIndex(1),:);
x(1)=sum(string(1:genLenth/2).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;
x(2)=sum(string(1+genLenth/2:end).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;
%繪制性能圖
%figure,hold on;
clf;figure(1),hold on;
plot((1:k)',meanally,'b.-');
plot((1:k)',maxally,'r.:');
end
function fun=f(x,y)
fun=(1-x).^2.*exp(-x.^2-(1+y).^2)-(x-x.^3-y.^3).*exp(-x.^2-y.^2);
%fun=-(x-1).^2-3.*(y-2).^2+100;
end
❾ 關於在matlab里實現遺傳演算法
遺傳演算法在matlab里有兩個函數,分別是ga和gaoptimset,前者用來調用遺傳演算法,後者用來設定遺傳演算法的參數,具體內容可以doc
ga查看,遺傳演算法有哪些參數可以直接在命令窗口輸入gaoptimset查看,祝好。
❿ MATLAB遺傳演算法
function ret=Code(lenchrom,bound)
%本函數將變數編碼成染色體,用於隨機初始化一個種群
% lenchrom input : 染色體長度
% bound input : 變數的取值范圍
% ret output: 染色體的編碼值
flag=0;
while flag==0
pick=rand(1,length(lenchrom));
ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %線性插值
flag=test(lenchrom,bound,ret); %檢驗染色體的可行性
end
function ret=Cross(pcross,lenchrom,chrom,sizepop,bound)
%本函數完成交叉操作
% pcorss input : 交叉概率
% lenchrom input : 染色體的長度
% chrom input : 染色體群
% sizepop input : 種群規模
% ret output : 交叉後的染色體
for i=1:sizepop
% 隨機選擇兩個染色體進行交叉
pick=rand(1,2);
while prod(pick)==0
pick=rand(1,2);
end
index=ceil(pick.*sizepop);
% 交叉概率決定是否進行交叉
pick=rand;
while pick==0
pick=rand;
end
if pick>pcross
continue;
end
flag=0;
while flag==0
% 隨機選擇交叉位置
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick.*sum(lenchrom)); %隨機選擇進行交叉的位置,即選擇第幾個變數進行交叉,注意:兩個染色體交叉的位置相同
pick=rand; %交叉開始
v1=chrom(index(1),pos);
v2=chrom(index(2),pos);
chrom(index(1),pos)=pick*v2+(1-pick)*v1;
chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉結束
flag1=test(lenchrom,bound,chrom(index(1),:)); %檢驗染色體1的可行性
flag2=test(lenchrom,bound,chrom(index(2),:)); %檢驗染色體2的可行性
if flag1*flag2==0
flag=0;
else flag=1;
end %如果兩個染色體不是都可行,則重新交叉
end
end
ret=chrom;
clc
clear all
% warning off
%% 遺傳演算法參數
maxgen=50; %進化代數
sizepop=100; %種群規模
pcross=[0.6]; %交叉概率
pmutation=[0.1]; %變異概率
lenchrom=[1 1]; %變數字串長度
bound=[-5 5;-5 5]; %變數范圍
%% 個體初始化
indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %種群結構體
avgfitness=[]; %種群平均適應度
bestfitness=[]; %種群最佳適應度
bestchrom=[]; %適應度最好染色體
% 初始化種群
for i=1:sizepop
indivials.chrom(i,:)=Code(lenchrom,bound); %隨機產生個體
x=indivials.chrom(i,:);
indivials.fitness(i)= (x(1)*exp(-(x(1)^2 + x(2)^2)));
%-20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289
% 這個是我的測試函數
% 如果有這個函數的話,可以得到最優值
end
%找最好的染色體
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色體
avgfitness=sum(indivials.fitness)/sizepop; %染色體的平均適應度
% 記錄每一代進化中最好的適應度和平均適應度
trace=[];
%% 進化開始
for i=1:maxgen
% 選擇操作
indivials=Select(indivials,sizepop);
avgfitness=sum(indivials.fitness)/sizepop;
% 交叉操作
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 變異操作
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,[i maxgen],bound);
% 計算適應度
for j=1:sizepop
x=indivials.chrom(j,:);
indivials.fitness(j)=(x(1)*exp(-(x(1)^2 + x(2)^2)));
%-20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289
% -20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289;
end
%找到最小和最大適應度的染色體及它們在種群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次進化中最好的染色體
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;
avgfitness=sum(indivials.fitness)/sizepop;
trace=[trace;avgfitness bestfitness]; %記錄每一代進化中最好的適應度和平均適應度
end
%進化結束
%% 結果顯示
[r c]=size(trace);
figure
plot([1:r]',trace(:,1),'r-',[1:r]',trace(:,2),'b--');
title(['函數值曲線 ' '終止代數=' num2str(maxgen)],'fontsize',12);
xlabel('進化代數','fontsize',12);ylabel('函數值','fontsize',12);
legend('各代平均值','各代最佳值','fontsize',12);
ylim([-0.5 5])
disp('函數值 變數');
% 窗口顯示
disp([bestfitness x]);