遗传算法MATLAB完整代码(不用工具箱)

合集下载

基于遗传算法的BP神经网络MATLAB代码

基于遗传算法的BP神经网络MATLAB代码

基于遗传算法的BP神经网络MATLAB代码以下是基于遗传算法的BP神经网络的MATLAB代码,包括网络初始化、适应度计算、交叉运算、突变操作和迭代训练等。

1.网络初始化:```matlabfunction net = initialize_network(input_size, hidden_size, output_size)net.input_size = input_size;net.hidden_size = hidden_size;net.output_size = output_size;net.hidden_weights = rand(hidden_size, input_size);net.output_weights = rand(output_size, hidden_size);net.hidden_biases = rand(hidden_size, 1);net.output_biases = rand(output_size, 1);end```2.适应度计算:```matlabfunction fitness = calculate_fitness(net, data, labels)output = forward_propagation(net, data);fitness = sum(sum(abs(output - labels)));end```3.前向传播:```matlabfunction output = forward_propagation(net, data)hidden_input = net.hidden_weights * data + net.hidden_biases;hidden_output = sigmoid(hidden_input);output_input = net.output_weights * hidden_output +net.output_biases;output = sigmoid(output_input);endfunction result = sigmoid(x)result = 1 ./ (1 + exp(-x));end```4.交叉运算:```matlabfunction offspring = crossover(parent1, parent2)point = randi([1 numel(parent1)]);offspring = [parent1(1:point) parent2((point + 1):end)]; end```5.突变操作:```matlabfunction mutated = mutation(individual, mutation_rate) for i = 1:numel(individual)if rand < mutation_ratemutated(i) = rand;elsemutated(i) = individual(i);endendend```6.迭代训练:```matlabfunction [best_individual, best_fitness] =train_network(data, labels, population_size, generations, mutation_rate)input_size = size(data, 1);hidden_size = round((input_size + size(labels, 1)) / 2);output_size = size(labels, 1);population = cell(population_size, 1);for i = 1:population_sizepopulation{i} = initialize_network(input_size, hidden_size, output_size);endbest_individual = population{1};best_fitness = calculate_fitness(best_individual, data, labels);for i = 1:generationsfor j = 1:population_sizefitness = calculate_fitness(population{j}, data, labels);if fitness < best_fitnessbest_individual = population{j};best_fitness = fitness;endendselected = selection(population, data, labels);for j = 1:population_sizeparent1 = selected{randi([1 numel(selected)])};parent2 = selected{randi([1 numel(selected)])};offspring = crossover(parent1, parent2);mutated_offspring = mutation(offspring, mutation_rate);population{j} = mutated_offspring;endendendfunction selected = selection(population, data, labels) fitnesses = zeros(length(population), 1);for i = 1:length(population)fitnesses(i) = calculate_fitness(population{i}, data, labels);end[~, indices] = sort(fitnesses);selected = population(indices(1:floor(length(population) / 2)));end```这是一个基于遗传算法的简化版BP神经网络的MATLAB代码,使用该代码可以初始化神经网络并进行迭代训练,以获得最佳适应度的网络参数。

利用MATLAB编制的遗传算法代码

利用MATLAB编制的遗传算法代码

function gaTSPCityNum=30;[dislist,Clist]=tsp(CityNum);inn=100; %初始种群大小¡gnmax=1000; %最大概率pc=0.8; %交叉概率pm=0.8; %变异概率%产生初始种群for i=1:inns(i,:)=randperm(CityNum);end[f,p]=objf(s,dislist);gn=1;while gn<gnmax+1for j=1:2:innseln=sel(s,p); %选择操作scro=cro(s,seln,pc); %交叉操作scnew(j,:)=scro(1,:);scnew(j+1,:)=scro(2,:);smnew(j,:)=mut(scnew(j,:),pm); %变异操作smnew(j+1,:)=mut(scnew(j+1,:),pm);ends=smnew; %产生了新的种群[f,p]=objf(s,dislist); %计算新种群的适应度%记录当前代最好和平均的适应度[fmax,nmax]=max(f);ymean(gn)=1000/mean(f);ymax(gn)=1000/fmax;%记录当前代的最佳个体x=s(nmax,:);drawTSP(Clist,x,ymax(gn),gn,0);gn=gn+1;%pause;endgn=gn-1;figure(2);plot(ymax,'r'); hold on;plot(ymean,'b');grid;title('ËÑË÷¹ý³Ì');legend('×îÓŽâ','ƽ¾ù½â');end%------------------------------------------------%计算适应度函数function [f,p]=objf(s,dislist);inn=size(s,1); %读取种群大小¡for i=1:innf(i)=CalDist(dislist,s(i,:)); %计算函数值,即适应度endf=1000./f';%计算选择概率fsum=0;for i=1:innfsum=fsum+f(i)^15;endfor i=1:innps(i)=f(i)^15/fsum;end%计算累积概率p(1)=ps(1);for i=2:innp(i)=p(i-1)+ps(i);endp=p';end%--------------------------------------------------function pcc=pro(pc);test(1:100)=0;l=round(100*pc);test(1:l)=1;n=round(rand*99)+1;pcc=test(n);end%--------------------------------------------------%“选择”操作function seln=sel(s,p);inn=size(p,1);%从种群中选择两个个体for i=1:2r=rand; %产生一个随机数prand=p-r;j=1;while prand(j)<0j=j+1;endseln(i)=j; %选中个体的序号endend%------------------------------------------------%“交叉”操作function scro=cro(s,seln,pc);bn=size(s,2);pcc=pro(pc); %根据交叉概率决定是否进行交叉操作,1则是,0则否scro(1,:)=s(seln(1),:);scro(2,:)=s(seln(2),:);if pcc==1c1=round(rand*(bn-2))+1; %在[1,bn-1]范围内随机产生一个交叉位 c2=round(rand*(bn-2))+1;chb1=min(c1,c2);chb2=max(c1,c2);middle=scro(1,chb1+1:chb2);scro(1,chb1+1:chb2)=scro(2,chb1+1:chb2);scro(2,chb1+1:chb2)=middle;for i=1:chb1while find(scro(1,chb1+1:chb2)==scro(1,i))zhi=find(scro(1,chb1+1:chb2)==scro(1,i));y=scro(2,chb1+zhi);scro(1,i)=y;endwhile find(scro(2,chb1+1:chb2)==scro(2,i))zhi=find(scro(2,chb1+1:chb2)==scro(2,i));y=scro(1,chb1+zhi);scro(2,i)=y;endendfor i=chb2+1:bnwhile find(scro(1,1:chb2)==scro(1,i))zhi=find(scro(1,1:chb2)==scro(1,i));y=scro(2,zhi);scro(1,i)=y;endwhile find(scro(2,1:chb2)==scro(2,i))zhi=find(scro(2,1:chb2)==scro(2,i));y=scro(1,zhi);scro(2,i)=y;endendendend%--------------------------------------------------%“变异”操作function snnew=mut(snew,pm);bn=size(snew,2);snnew=snew;pmm=pro(pm); %¸根据变异概率决定是否进行变异操作,1则是,0则否if pmm==1c1=round(rand*(bn-2))+1; %在[1,bn-1]范围内随机产生一个变异位 c2=round(rand*(bn-2))+1;chb1=min(c1,c2);chb2=max(c1,c2);x=snew(chb1+1:chb2);snnew(chb1+1:chb2)=fliplr(x); endend。

遗传算法详解(含MATLAB代码)

遗传算法详解(含MATLAB代码)

遗传算法详解(含MATLAB代码)Python遗传算法框架使用实例(一)使用Geatpy实现句子匹配在前面几篇文章中,我们已经介绍了高性能Python遗传和进化算法框架——Geatpy的使用。

本篇就一个案例进行展开讲述:pip install geatpy更新至Geatpy2的方法:pip install --upgrade --user geatpy查看版本号,在Python中执行:import geatpyprint(geatpy.__version__)我们都听过“无限猴子定理”,说的是有无限只猴子用无限的时间会产生特定的文章。

在无限猴子定理中,我们“假定”猴子们是没有像人类那样“智能”的,而且“假定”猴子不会自我学习。

因此,这些猴子需要“无限的时间"。

而在遗传算法中,由于采用的是启发式的进化搜索,因此不需要”无限的时间“就可以完成类似的工作。

当然,需要产生的文章篇幅越长,那么就需要越久的时间才能完成。

下面以产生"T om is a little boy, isn't he? Yes he is, he is a good and smart child and he is always ready to help others, all in all we all like him very much."的句子为例,讲述如何利用Geatpy实现句子的搜索。

之前的文章中我们已经讲述过如何使用Geatpy的进化算法框架实现遗传算法编程。

这里就直接用框架。

把自定义问题类和执行脚本编写在下面的"main.py”文件中:# -*- coding: utf-8 -*-import numpy as npimport geatpy as eaclass MyProblem(ea.Problem): # 继承Problem父类def __init__(self):name = 'MyProblem' # 初始化name(函数名称,可以随意设置) # 定义需要匹配的句子strs = 'Tom is a little boy, isn't he? Yes he is, he is a good and smart child and he is always ready to help others, all in all we all like him very much.'self.words = []for c in strs:self.words.append(ord(c)) # 把字符串转成ASCII码M = 1 # 初始化M(目标维数)maxormins = [1] # 初始化maxormins(目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标)Dim = len(self.words) # 初始化Dim(决策变量维数)varTypes = [1] * Dim # 初始化varTypes(决策变量的类型,元素为0表示对应的变量是连续的;1表示是离散的)lb = [32] * Dim # 决策变量下界ub = [122] * Dim # 决策变量上界lbin = [1] * Dim # 决策变量下边界ubin = [1] * Dim # 决策变量上边界# 调用父类构造方法完成实例化ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)def aimFunc(self, pop): # 目标函数Vars = pop.Phen # 得到决策变量矩阵diff = np.sum((Vars - self.words)**2, 1)pop.ObjV = np.array([diff]).T # 把求得的目标函数值赋值给种群pop的ObjV执行脚本if __name__ == "__main__":"""================================实例化问题对象============================="""problem = MyProblem() # 生成问题对象"""==================================种群设置================================"""Encoding = 'RI' # 编码方式NIND = 50 # 种群规模Field = ea.crtfld(Encoding, problem.varTypes, problem.ranges,problem.borders) # 创建区域描述器population = ea.Population(Encoding, Field, NIND) # 实例化种群对象(此时种群还没被初始化,仅仅是完成种群对象的实例化)"""================================算法参数设置=============================="""myAlgorithm = ea.soea_DE_rand_1_L_templet(problem, population) # 实例化一个算法模板对象myAlgorithm.MAXGEN = 2000 # 最大进化代数"""===========================调用算法模板进行种群进化========================="""[population, obj_trace, var_trace] = myAlgorithm.run() # 执行算法模板population.save() # 把最后一代种群的信息保存到文件中# 输出结果best_gen = np.argmin(obj_trace[:, 1]) # 记录最优种群是在哪一代best_ObjV = obj_trace[best_gen, 1]print('最优的目标函数值为:%s'%(best_ObjV))print('有效进化代数:%s'%(obj_trace.shape[0]))print('最优的一代是第 %s 代'%(best_gen + 1))print('评价次数:%s'%(myAlgorithm.evalsNum))print('时间已过 %s 秒'%(myAlgorithm.passTime))for num in var_trace[best_gen, :]:print(chr(int(num)), end = '')上述代码中首先定义了一个问题类MyProblem,然后调用Geatpy内置的soea_DE_rand_1_L_templet算法模板,它实现的是差分进化算法DE-rand-1-L,详见源码:运行结果如下:种群信息导出完毕。

11基于遗传算法的机器人路径规划MATLAB源代码

11基于遗传算法的机器人路径规划MATLAB源代码

基于遗传算法的机器人路径规划MATLAB源代码基本思路是:取各障碍物顶点连线的中点为路径点,相互连接各路径点,将机器人移动的起点和终点限制在各路径点上,利用最短路径算法来求网络图的最短路径,找到从起点P1到终点Pn的最短路径。

上述算法使用了连接线中点的条件,因此不是整个规划空间的最优路径,然后利用遗传算法对找到的最短路径各个路径点Pi (i=1,2,…n)调整,让各路径点在相应障碍物端点连线上滑动,利用Pi= Pi1+ti×(Pi2-Pi1)(ti∈[0,1] i=1,2,…n)即可确定相应的Pi,即为新的路径点,连接此路径点为最优路径。

function [L1,XY1,L2,XY2]=JQRLJGH(XX,YY)%% 基于Dijkstra和遗传算法的机器人路径规划% GreenSim团队——专业级算法设计&代写程序% 欢迎访问GreenSim团队主页→/greensim%输入参数在函数体内部定义%输出参数为% L1 由Dijkstra算法得出的最短路径长度% XY1 由Dijkstra算法得出的最短路径经过节点的坐标% L2 由遗传算法得出的最短路径长度% XY2 由遗传算法得出的最短路径经过节点的坐标%程序输出的图片有% Fig1 环境地图(包括:边界、障碍物、障碍物顶点之间的连线、Dijkstra的网络图结构)% Fig2 由Dijkstra算法得到的最短路径% Fig3 由遗传算法得到的最短路径% Fig4 遗传算法的收敛曲线(迄今为止找到的最优解、种群平均适应值)%% 画Fig1figure(1);PlotGraph;title('地形图及网络拓扑结构')PD=inf*ones(26,26);for i=1:26for j=1:26if D(i,j)==1x1=XY(i,5);y1=XY(i,6);x2=XY(j,5);y2=XY(j,6);dist=((x1-x2)^2+(y1-y2)^2)^0.5;PD(i,j)=dist;endendend%% 调用最短路算法求最短路s=1;%出发点t=26;%目标点[L,R]=ZuiDuanLu(PD,s,t);L1=L(end);XY1=XY(R,5:6);%% 绘制由最短路算法得到的最短路径figure(2);PlotGraph;hold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('由Dijkstra算法得到的初始路径')%% 使用遗传算法进一步寻找最短路%第一步:变量初始化M=50;%进化代数设置N=20;%种群规模设置Pm=0.3;%变异概率设置LC1=zeros(1,M);LC2=zeros(1,M);Yp=L1;%第二步:随机产生初始种群X1=XY(R,1);Y1=XY(R,2);X2=XY(R,3);Y2=XY(R,4);for i=1:Nfarm{i}=rand(1,aaa);end% 以下是进化迭代过程counter=0;%设置迭代计数器while counter<M%停止条件为达到最大迭代次数%% 第三步:交叉%交叉采用双亲双子单点交叉newfarm=cell(1,2*N);%用于存储子代的细胞结构Ser=randperm(N);%两两随机配对的配对表A=farm{Ser(1)};%取出父代AB=farm{Ser(2)};%取出父代BP0=unidrnd(aaa-1);%随机选择交叉点a=[A(:,1:P0),B(:,(P0+1):end)];%产生子代ab=[B(:,1:P0),A(:,(P0+1):end)];%产生子代bnewfarm{2*N-1}=a;%加入子代种群newfarm{2*N}=b;for i=1:(N-1)A=farm{Ser(i)};B=farm{Ser(i+1)};newfarm{2*i}=b;endFARM=[farm,newfarm];%新旧种群合并%% 第四步:选择复制SER=randperm(2*N);FITNESS=zeros(1,2*N);fitness=zeros(1,N);for i=1:(2*N)PP=FARM{i};FITNESS(i)=MinFun(PP,X1,X2,Y1,Y2);%调用目标函数endfor i=1:Nf1=FITNESS(SER(2*i-1));f2=FITNESS(SER(2*i));if f1<=f2elsefarm{i}=FARM{SER(2*i)};fitness(i)=FITNESS(SER(2*i));endend%记录最佳个体和收敛曲线minfitness=min(fitness);meanfitness=mean(fitness);if minfitness<Yppos=find(fitness==minfitness);Xp=farm{pos(1)};Yp=minfitness;endif counter==10PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];figure(3)PlotGraph;hold onfor i=1:(length(R)-1)x1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法第10代')hold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendendif counter==20PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];figure(4)PlotGraph;hold onfor i=1:(length(R)-1)x1=XY2(i,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法第20代')hold onx1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendendif counter==30PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];figure(5)PlotGraph;hold onfor i=1:(length(R)-1)x1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法第30代')hold onfor i=1:(length(R)-1)x1=XY1(i,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendendif counter==40PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];figure(6)PlotGraph;hold onx1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法第40代')hold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendendif counter==50PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];figure(7)PlotGraph;hold onfor i=1:(length(R)-1)x1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法第50代')hold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendendLC2(counter+1)=Yp;LC1(counter+1)=meanfitness;%% 第五步:变异for i=1:Nif Pm>rand&&pos(1)~=iAA=farm{i};AA(POS)=rand;farm{i}=AA;endendcounter=counter+1;disp(counter);end%% 输出遗传算法的优化结果PPP=[0.5,Xp,0.5]';PPPP=1-PPP;X=PPP.*X1+PPPP.*X2;Y=PPP.*Y1+PPPP.*Y2;XY2=[X,Y];L2=Yp;%% 绘制Fig3figure(8)PlotGraph;hold onhold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendfor i=1:(length(R)-1)x1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k');hold onendtitle('遗传算法最终结果')figure(9)PlotGraph;hold onfor i=1:(length(R)-1)x1=XY1(i,1);y1=XY1(i,2);x2=XY1(i+1,1);y2=XY1(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',1);hold onendhold onfor i=1:(length(R)-1)x1=XY2(i,1);y1=XY2(i,2);x2=XY2(i+1,1);y2=XY2(i+1,2);plot([x1,x2],[y1,y2],'k','LineWidth',2);hold onendtitle('遗传算法优化前后结果比较')%% 绘制Fig4figure(10);plot(LC1);hold onplot(LC2);xlabel('迭代次数');title('收敛曲线');源代码运行结果展示。

30个智能算法matlab代码

30个智能算法matlab代码

30个智能算法matlab代码以下是30个使用MATLAB编写的智能算法的示例代码: 1. 线性回归算法:matlab.x = [1, 2, 3, 4, 5];y = [2, 4, 6, 8, 10];coefficients = polyfit(x, y, 1);predicted_y = polyval(coefficients, x);2. 逻辑回归算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];model = fitglm(x, y, 'Distribution', 'binomial'); predicted_y = predict(model, x);3. 支持向量机算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [1, 1, -1, -1, -1];model = fitcsvm(x', y');predicted_y = predict(model, x');4. 决策树算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitctree(x', y');predicted_y = predict(model, x');5. 随机森林算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = TreeBagger(50, x', y');predicted_y = predict(model, x');6. K均值聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];idx = kmeans(data, 2);7. DBSCAN聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];epsilon = 2;minPts = 2;[idx, corePoints] = dbscan(data, epsilon, minPts);8. 神经网络算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];net = feedforwardnet(10);net = train(net, x', y');predicted_y = net(x');9. 遗传算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = gaoptimset('PlotFcns', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);10. 粒子群优化算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = particleswarm(fitnessFunction, nvars, lb, ub, options);11. 蚁群算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = antColonyOptimization(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);12. 粒子群-蚁群混合算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = particleAntHybrid(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);13. 遗传算法-粒子群混合算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;gaOptions = gaoptimset('PlotFcns', @gaplotbestf);psOptions = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = gaParticleHybrid(fitnessFunction, nvars, lb, ub, gaOptions, psOptions);14. K近邻算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcknn(x', y');predicted_y = predict(model, x');15. 朴素贝叶斯算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcnb(x', y');predicted_y = predict(model, x');16. AdaBoost算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [0, 0, 1, 1, 1];model = fitensemble(x', y', 'AdaBoostM1', 100, 'Tree'); predicted_y = predict(model, x');17. 高斯混合模型算法:matlab.x = [1, 2, 3, 4, 5]';y = [0, 0, 1, 1, 1]';data = [x, y];model = fitgmdist(data, 2);idx = cluster(model, data);18. 主成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = pca(x');transformed_x = x' coefficients;19. 独立成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = fastica(x');transformed_x = x' coefficients;20. 模糊C均值聚类算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; options = [2, 100, 1e-5, 0];[centers, U] = fcm(x', 2, options);21. 遗传规划算法:matlab.fitnessFunction = @(x) x^2 4x + 4; nvars = 1;lb = 0;ub = 5;options = optimoptions('ga', 'PlotFcn', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);22. 线性规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];lb = [0; 0];ub = [];[x, fval] = linprog(f, A, b, [], [], lb, ub);23. 整数规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];intcon = [1, 2];[x, fval] = intlinprog(f, intcon, A, b);24. 图像分割算法:matlab.image = imread('image.jpg');grayImage = rgb2gray(image);binaryImage = imbinarize(grayImage);segmented = medfilt2(binaryImage);25. 文本分类算法:matlab.documents = ["This is a document.", "Another document.", "Yet another document."];labels = categorical(["Class 1", "Class 2", "Class 1"]);model = trainTextClassifier(documents, labels);newDocuments = ["A new document.", "Another new document."];predictedLabels = classifyText(model, newDocuments);26. 图像识别算法:matlab.image = imread('image.jpg');features = extractFeatures(image);model = trainImageClassifier(features, labels);newImage = imread('new_image.jpg');newFeatures = extractFeatures(newImage);predictedLabel = classifyImage(model, newFeatures);27. 时间序列预测算法:matlab.data = [1, 2, 3, 4, 5];model = arima(2, 1, 1);model = estimate(model, data);forecastedData = forecast(model, 5);28. 关联规则挖掘算法:matlab.data = readtable('data.csv');rules = associationRules(data, 'Support', 0.1);29. 增强学习算法:matlab.environment = rlPredefinedEnv('Pendulum');agent = rlDDPGAgent(environment);train(agent);30. 马尔可夫决策过程算法:matlab.states = [1, 2, 3];actions = [1, 2];transitionMatrix = [0.8, 0.1, 0.1; 0.2, 0.6, 0.2; 0.3, 0.3, 0.4];rewardMatrix = [1, 0, -1; -1, 1, 0; 0, -1, 1];policy = mdpPolicyIteration(transitionMatrix, rewardMatrix);以上是30个使用MATLAB编写的智能算法的示例代码,每个算法都可以根据具体的问题和数据进行相应的调整和优化。

2020年遗传算法matlab程序实例精编版

2020年遗传算法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'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[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,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(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;endt=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)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_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 individualfor i=2:popsize-1pop=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);endinitpop(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 variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=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))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=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<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=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)=[];endif length(y1)>=2for i=0:2:length(y1)-2if 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),:));endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=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 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(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 NewPopr=rand(1,m);position=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;endendendendNewPop=OldPop;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(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);endendend遗传算法程序(二):function youhuafunD=code;N=50; % Tunablemaxgen=50; % Tunablecrossrate=0.5; %Tunablemuterate=0.08; %Tunablegeneration=1;num = length(D);fatherrand=randint(num,N,3);score = zeros(maxgen,N);while generation<=maxgenind=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;% endfatherrand=[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:Ntmprnd=rand;tmpind=tmprnd difind=[0,diff(tmpind)];if ~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind);generation=generation+1;end% scoremaxV=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 Dfunction D=codeload youhua.mat% properties F2 and F3F1=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 valueF4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[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:NFF4k=FF4rnd(:,k);for ite=1:11F0index=find(FF4k==ite);if ~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%遗传算法程序(三):%IAGAfunction best=gaclearMAX_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_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;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:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_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:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(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;endreturn;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_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand;if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%。

遗传算法MATLAB完整代码(不用工具箱)

遗传算法MATLAB完整代码(不用工具箱)

遗传算法MATLAB完整代码(不用工具箱)遗传算法解决简单问题%主程序:用遗传算法求解y=200*exp(-0.05*x).*sin(x)在区间[-2,2]上的最大值clc;clear all;close all;global BitLengthglobal boundsbeginglobal boundsendbounds=[-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< p="">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);endpopulation=scnew; %产生了新的种群%计算新种群的适应度[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((boundsend),BitLength)-1);xmax(Generation)=xx;Generation=Generation+1;endGeneration=Generation-1;Bestpopulation=xx;Besttargetfunvalue=targetfun(xx);%绘制经过遗传运算后的适应度曲线。

遗传算法matlab程序代码

遗传算法matlab程序代码

遗传算法matlab程序代码遗传算法是一种优化算法,用于在给定的搜索空间中寻找最优解。

在Matlab中,可以通过以下代码编写一个基本的遗传算法:% 初始种群大小Npop = 100;% 搜索空间维度ndim = 2;% 最大迭代次数imax = 100;% 初始化种群pop = rand(Npop, ndim);% 最小化目标函数fun = @(x) sum(x.^2);for i = 1:imax% 计算适应度函数fit = 1./fun(pop);% 选择操作[fitSort, fitIndex] = sort(fit, 'descend');pop = pop(fitIndex(1:Npop), :);% 染色体交叉操作popNew = zeros(Npop, ndim);for j = 1:Npopparent1Index = randi([1, Npop]);parent2Index = randi([1, Npop]);parent1 = pop(parent1Index, :);parent2 = pop(parent2Index, :);crossIndex = randi([1, ndim-1]);popNew(j,:) = [parent1(1:crossIndex),parent2(crossIndex+1:end)];end% 染色体突变操作for j = 1:NpopmutIndex = randi([1, ndim]);mutScale = randn();popNew(j, mutIndex) = popNew(j, mutIndex) + mutScale;end% 更新种群pop = [pop; popNew];end% 返回最优解[resultFit, resultIndex] = max(fit);result = pop(resultIndex, :);以上代码实现了一个简单的遗传算法,用于最小化目标函数x1^2 + x2^2。

遗传算法及其MATLAB程序代码

遗传算法及其MATLAB程序代码

遗传算法及其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)。

遗传算法介绍并附上Matlab代码

遗传算法介绍并附上Matlab代码

1、遗传算法介绍遗传算法,模拟达尔文进化论的自然选择和遗产学机理的生物进化构成的计算模型,一种不断选择优良个体的算法。

谈到遗传,想想自然界动物遗传是怎么来的,自然主要过程包括染色体的选择,交叉,变异(不明白这个的可以去看看生物学),这些操作后,保证了以后的个基本上是最优的,那么以后再继续这样下去,就可以一直最优了。

2、解决的问题先说说自己要解决的问题吧,遗传算法很有名,自然能解决的问题很多了,在原理上不变的情况下,只要改变模型的应用环境和形式,基本上都可以。

但是遗传算法主要还是解决优化类问题,尤其是那种不能直接解出来的很复杂的问题,而实际情况通常也是这样的。

本部分主要为了了解遗传算法的应用,选择一个复杂的二维函数来进行遗传算法优化,函数显示为y=10*sin(5*x)+7*abs(x-5)+10,这个函数图像为:怎么样,还是有一点复杂的吧,当然你还可以任意假设和编写,只要符合就可以。

那么现在问你要你一下求出最大值你能求出来吗?这类问题如果用遗传算法或者其他优化方法就很简单了,为什么呢?说白了,其实就是计算机太笨了,同时计算速度又超快,举个例子吧,我把x等分成100万份,再一下子都带值进去算,求出对应的100万个y的值,再比较他们的大小,找到最大值不就可以了吗,很笨吧,人算是不可能的,但是计算机可以。

而遗传算法也是很笨的一个个搜索,只不过加了一点什么了,就是人为的给它算的方向和策略,让它有目的的算,这也就是算法了。

3、如何开始?我们知道一个种群中可能只有一个个体吗?不可能吧,肯定很多才对,这样相互结合的机会才多,产生的后代才会多种多样,才会有更好的优良基因,有利于种群的发展。

那么算法也是如此,当然个体多少是个问题,一般来说20-100之间我觉得差不多了。

那么个体究竟是什么呢?在我们这个问题中自然就是x值了。

其他情况下,个体就是所求问题的变量,这里我们假设个体数选100个,也就是开始选100个不同的x值,不明白的话就假设是100个猴子吧。

遗传算法GA的MATLAB代码

遗传算法GA的MATLAB代码

MATLAB实现算法代码:GA(遗传算法)——整数编码function [BestGene,aa] = GA(MaxGeneration,GeneSize,GeneNum,pcross,pmute,minGene,maxGene)Parent = Init(GeneSize,GeneNum,minGene,maxGene);[BestGene,Parent] = KeepBest(Parent);aa = [];for i = 1:MaxGeneration[i 1/value(BestGene)]Child = chose(Parent);Child = cross(Child,pcross);Child = mute(Child,pmute,maxGene);[BestGene,Parent] = KeepBest(Child);aa = [aa;value(BestGene)];endfunction GeneInit = Init(GeneSize,GeneNum,minGene,maxGene)GeneInit = [];for i = 1:GeneSizex = []; x = ceil(rand(1,GeneNum).*(maxGene-minGene)) + minGene;GeneInit = [GeneInit;x];endGeneInit = [GeneInit;x];function Child = chose(Parent)GeneSize = size(Parent,1);for i = 1:GeneSizex = Parent(i,:);val(i) = value(x);endValSum = sum(val);val = val / ValSum;for i = 2:GeneSizeval(i) = val(i) + val(i-1);endfor i = 1:GeneSizerandval = rand;if randval <= val(1)Child(i,:) = Parent(1,:);endfor j = 2:GeneSizeif randval > val(j-1) && randval <= val(j)Child(i,:) = Parent(j,:);break;endendendChild(end,:) = Parent(end,:);function Child = cross(Parent,pcross)[GeneSize,GeneNum] = size(Parent);GeneSize = GeneSize - 1;Child = Parent;for i = 1:GeneSize/2if rand < pcrossflag = 0;while( flag==0 )randval1 = floor((GeneNum-1)*rand) + 1;randval2 = floor((GeneNum-1)*rand) + 1;if randval1 ~= randval2flag = 1;endendtemp = Child(2*i-1,randval1:randval2);Child(2*i-1,randval1:randval2) = Child(2*i,randval1:randval2);Child(2*i,randval1:randval2) = temp;endendfunction Child = mute(Parent,pmute,maxGene)[GeneSize,GeneNum] = size(Parent);GeneSize = GeneSize - 1;Child = Parent;for i = 1:GeneSizeif rand < pmuterandval = ceil((GeneNum-1)*rand) + 1;Child(i,randval) = maxGene(randval) - Child(i,randval) + 1;endendfunction [BestGene,Parent] = KeepBest(Child)[GeneSize,GeneNum] = size(Child);for i = 1:GeneSizex = Child(i,:);val(i) = value(x);endBigVal = val(1);flag = 1;for i = 2:GeneSizeif BigVal < val(i)BigVal = val(i);flag = i;endendBestGene = Child(flag,:); Parent = Child;Parent(1,:) = BestGene; Parent(end,:) = BestGene;。

遗传算法matlab代码

遗传算法matlab代码

function youhuafunD=code;N=50; % Tunablemaxgen=50; % Tunablecrossrate=0.5; %Tunablemuterate=0.08; %Tunablegeneration=1;num = length(D);fatherrand=randint(num,N,3);score = zeros(maxgen,N);while generation<=maxgenind=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;% endfatherrand=[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:Ntmprnd=rand;tmpind=tmprnd difind=[0,diff(tmpind)];if ~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind);generation=generation+1;end% scoremaxV=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 Dfunction D=codeload youhua.mat% properties F2 and F3F1=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:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[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:NFF4k=FF4rnd(:,k);for ite=1:11F0index=find(FF4k==ite);if ~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;遗传算法实例:% 下面举例说明遗传算法%% 求下列函数的最大值%% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01 。

21装配生产线任务平衡问题的遗传算法MATLAB源代码

21装配生产线任务平衡问题的遗传算法MATLAB源代码

装配生产线任务平衡问题的遗传算法MATLAB源代码下面的源码实现了装配生产线任务平衡优化问题(ALB问题)的遗传算法,算法主要参考下面这篇文献,并对其进行了改进。

陈永卿,潘刚,李平.基于混合遗传算法的装配线平衡[J].机电工程,2008,25(4):60-62.。

function[BestX,BestY,BestZ,AllFarm,LC1,LC2,LC3,LC4,LC5]=GSAALB(M,N,Pm,Pd,K,t0,alpha,TaskP, TaskT,TaskV,RT,RV)% GreenSim团队——专业级算法设计&代写程序% 欢迎访问GreenSim团队主页→/greensim%% 装配生产线任务平衡问题的遗传算法%% 输入参数列表% M------------遗传算法进化代数% N------------种群规模,取偶数% Pm-----------变异概率调节参数% Pd-----------变异程度调节参数,0<Pd<1,越大,变异的基因位越多% K------------同一温度下状态跳转次数% T0-----------初始温度% Alpha--------降温系数% Beta---------浓度均衡系数% TaskP--------任务优先矩阵,n×n矩阵,Pij=1表示任务i需在j之前完成,Pij=0时任务i 和j没有优先关系% TaskT--------任务时间属性,n×1向量% TaskV--------任务体积属性,n×1向量% RT-----------时间节拍约束% RV-----------工位体积约束%% 输出参数列表% BestX--------最好个体的编码% BestY--------最好个体对应的装配方案% BestZ--------最好个体的目标函数值% LC1----------最优个体适应值的收敛曲线,M×1% LC2----------种群平均适应值的收敛曲线,M×1% LC3----------工位个数收敛曲线,M×1% LC4----------时间利用率及平衡度综合度量参数收敛曲线,M×1% LC5----------空间利用率及平衡度综合度量参数收敛曲线,M×1% AllFarm------各代种群的集合,M×1的细胞结构%% -----------------------初始化----------------------------------n=size(TaskP,1);[AA,BB]=QJHJ(TaskP);%调用子函数,建立每一个任务的前任务集和后任务集farm=Initialization(N,TaskP,AA,BB);%调用子函数,种群初始化%输出参数初始化BestX=zeros(1,n);BestY=zeros(1,n);BestZ=0;LC1=zeros(M,1);LC2=zeros(M,1);LC3=zeros(M,1);LC4=zeros(M,1);LC5=zeros(M,1);AllFarm=cell(M,1);%控制参数初始化m=1;%迭代计数器t=t0;%温度指示器BestPos=1;%初始时任意指定被保护个体%% -----------------------迭代过程---------------------------------while m<=M%设置停止条件%% ----------------------变异退火算子------------------------------for i=1:Nif rand>Pm&&i~=BestPos%如果随机数大于变异概率门限值,并且不属于保护个体,就对其实施变异I=farm(i,:);%取出该个体k=1;while k<=K%每一个温度下的状态转移次数%调用变异子函数J=Mutation(I,Pd,AA,BB);%调用计算适应值子函数[YI,ZI,FI,TGWI,VGWI,f1I,f2I]=Fitness(I,TaskT,TaskV,RT,RV);[YJ,ZJ,FJ,TGWJ,VGWJ,f1J,f2J]=Fitness(J,TaskT,TaskV,RT,RV);if FJ>FIfarm(i,:)=J;elseif rand<exp((FJ-FI)/(FI*t))farm(i,:)=J;elsefarm(i,:)=I;endk=k+1;endendend%% -----------------------交叉算子---------------------------------newfarm=zeros(size(farm));Ser=randperm(N);%用这个函数保证随机配对for i=1:2:(N-1)FA=farm(Ser(i),:);FB=farm(Ser(i+1),:);[SA,SB]=CrossOver(FA,FB);newfarm(i,:)=SA;newfarm(i+1,:)=SB;end%新旧种群合并FARM=[farm;newfarm];%% -----------------------选择复制--------------------------------- FIT_Y=zeros(2*N,n);FIT_Z=zeros(2*N,1);FIT_F=zeros(2*N,1);FIT_f1=zeros(2*N,1);FIT_f2=zeros(2*N,1);fit_Y=zeros(N,n);fit_Z=zeros(N,1);fit_F=zeros(N,1);fit_f1=zeros(N,1);fit_f2=zeros(N,1);for i=1:(2*N)XX=FARM(i,:);[Y,Z,F,TGW,VGW,f1,f2]=Fitness(XX,TaskT,TaskV,RT,RV);FIT_Y(i,:)=Y;FIT_Z(i)=Z;FIT_F(i)=F;FIT_f1(i)=f1;FIT_f2(i)=f2;endSer=randperm(2*N);for i=1:Nff1=FIT_F(Ser(2*i-1));ff2=FIT_F(Ser(2*i));if ff1>=ff2farm(i,:)=FARM(Ser(2*i-1),:);fit_Y(i,:)=FIT_Y(Ser(2*i-1),:);fit_Z(i)=FIT_Z(Ser(2*i-1));fit_F(i)=FIT_F(Ser(2*i-1));fit_f1(i)=FIT_f1(Ser(2*i-1));fit_f2(i)=FIT_f2(Ser(2*i-1));elsefarm(i,:)=FARM(Ser(2*i),:);fit_Y(i,:)=FIT_Y(Ser(2*i),:);fit_Z(i)=FIT_Z(Ser(2*i));fit_F(i)=FIT_F(Ser(2*i));fit_f1(i)=FIT_f1(Ser(2*i));fit_f2(i)=FIT_f2(Ser(2*i));endend%% -----------------------记录与更新------------------------------- maxF=max(fit_F);meanF=mean(fit_F);LC1(m)=maxF;LC2(m)=meanF;pos=find(fit_F==maxF);BestPos=pos(1);BestX=farm(BestPos,:);BestY=fit_Y(BestPos,:);BestZ=fit_Z(BestPos);LC3(m)=fit_Z(BestPos);LC4(m)=fit_f1(BestPos);LC5(m)=fit_f2(BestPos);AllFarm{m}=farm;disp(m);m=m+1;t=t*alpha;end源代码运行结果展示。

遗传算法matlab代码

遗传算法matlab代码

遗传算法matlab代码以下是一个简单的遗传算法的MATLAB 代码示例:matlab复制代码% 遗传算法参数设置pop_size = 50; % 种群大小num_vars = 10; % 变量数目num_generations = 100; % 进化的代数mutation_rate = 0.01; % 变异率crossover_rate = 0.8; % 交叉率% 初始化种群population = rand(pop_size, num_vars);% 开始进化for i = 1:num_generations% 计算适应度fitness = evaluate_fitness(population);% 选择操作selected_population = selection(population, fitness);% 交叉操作offspring_population = crossover(selected_population,crossover_rate);% 变异操作mutated_population = mutation(offspring_population,mutation_rate);% 生成新种群population = [selected_population; mutated_population];end% 选择最优解best_solution = population(find(fitness == max(fitness)), :);% 适应度函数function f = evaluate_fitness(population)f = zeros(size(population));for i = 1:size(population, 1)f(i) = sum(population(i, :));endend% 选择函数function selected_population = selection(population, fitness)% 轮盘赌选择total_fitness = sum(fitness);probabilities = fitness / total_fitness;selected_indices = zeros(pop_size, 1);for i = 1:pop_sizer = rand();cumulative_probabilities = cumsum(probabilities);for j = 1:pop_sizeif r <= cumulative_probabilities(j)selected_indices(i) = j;break;endendendselected_population = population(selected_indices, :);end% 交叉函数function offspring_population = crossover(parental_population, crossover_rate)offspring_population = zeros(size(parental_population));num_crossovers = ceil(size(parental_population, 1) *crossover_rate);crossover_indices = randperm(size(parental_population, 1),num_crossovers);以下是另一个一个简单的遗传算法的MATLAB 代码示例:matlab复制代码% 初始化种群population = rand(nPopulation, nGenes);% 进化迭代for iGeneration = 1:nGeneration% 计算适应度fitness = evaluateFitness(population);% 选择父代parentIdx = selection(fitness);parent = population(parentIdx, :);% 交叉产生子代child = crossover(parent);% 变异子代child = mutation(child);% 更新种群population = [parent; child];end% 评估最优解bestFitness = -Inf;for i = 1:nPopulationf = evaluateFitness(population(i, :));if f > bestFitnessbestFitness = f;bestIndividual = population(i, :);endend% 可视化结果plotFitness(fitness);其中,nPopulation和nGenes分别是种群大小和基因数;nGeneration是迭代次数;evaluateFitness函数用于计算个体的适应度;selection函数用于选择父代;crossover函数用于交叉产生子代;mutation函数用于变异子代。

遗传算法matlab代码

遗传算法matlab代码

function youhuafunD=code;N=50; % Tunablemaxgen=50; % Tunablecrossrate=0.5; %Tunablemuterate=0.08; %Tunablegeneration=1;num = length(D);fatherrand=randint(num,N,3);score = zeros(maxgen,N);while generation<=maxgenind=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;% endfatherrand=[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:Ntmprnd=rand;tmpind=tmprnd difind=[0,diff(tmpind)];if ~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind); generation=generation+1;end% scoremaxV=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 Dfunction D=codeload youhua.mat% properties F2 and F3F1=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:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[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:NFF4k=FF4rnd(:,k);for ite=1:11F0index=find(FF4k==ite);if ~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;遗传算法实例:% 下面举例说明遗传算法%% 求下列函数的最大值%% f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] %% 将x 的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01 。

遗传算法Matlab源代码

遗传算法Matlab源代码

遗传算法Matlab源代码完整可以运行的数值优化遗传算法源代码function[X,MaxFval,BestPop,Trace]=fga(FUN,bounds,MaxEranum,PopSiz e,options,pCross,pMutation,pInversion)%[X,MaxFval,BestPop,Trace]=fga(FUN,bounds,MaxEranum,PopSiz e,options,pCross,pMutation,pInversion)% Finds a maximum of a function of several variables.% fga solves problems of the form:% max F(X) subject to: LB = X = UB (LB=bounds(:,1),UB=bounds(:,2))% X - 最优个体对应自变量值% MaxFval - 最优个体对应函数值% BestPop - 最优的群体即为最优的染色体群% Trace - 每代最佳个体所对应的目标函数值% FUN - 目标函数% bounds - 自变量范围% MaxEranum - 种群的代数,取50--500(默认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 nargin2, error('FMAXGA requires at least three input arguments'); endif nargin==2, MaxEranum=150;PopSize=100;options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==3, PopSize=100;options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==4, options=[1 1e-4];pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==5, pCross=0.85;pMutation=0.1;pInversion=0.25;endif nargin==6, pMutation=0.1;pInversion=0.25;endif nargin==7, pInversion=0.25;endif (options(1)==0|options(1)==1)find((bounds(:,1)-bounds(:,2))0)error('数据输入错误,请重新输入:');end% 定义全局变量global m n NewPop children1 children2 VarNum% 初始化种群和变量precision = options(2);bits = ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间VarNum = size(bounds,1);[Pop] = InitPop(PopSize,bounds,bits,options);%初始化种群[m,n] = size(Pop);fit = zeros(1,m);NewPop = zeros(m,n);children1 = zeros(1,n);children2 = zeros(1,n);pm0 = pMutation;BestPop = zeros(MaxEranum,n);%分配初始解空间BestPop,TraceTrace = zeros(1,MaxEranum);完整可以运行的数值优化遗传算法源代码Lb = ones(PopSize,1)*bounds(:,1)';Ub = ones(PopSize,1)*bounds(:,2)';%二进制编码采用多点交叉和均匀交叉,并逐步增大均匀交叉概率%浮点编码采用离散交叉(前期)、算术交叉(中期)、AEA重组(后期)OptsCrossOver = [ones(1,MaxEranum)*options(1);...round(unidrnd(2*(MaxEranum-[1:MaxEranum]))/MaxEranum)]';%浮点编码时采用两种自适应变异和一种随机变异(自适应变异发生概率为随机变异发生的2倍)OptsMutation = [ones(1,MaxEranum)*options(1);unidrnd(5,1,MaxEranum)]';if options(1)==3D=zeros(n);CityPosition=bounds;D = sqrt((CityPosition(:, ones(1,n)) - CityPosition(:, ones(1,n))').^2 +...(CityPosition(:,2*ones(1,n)) - CityPosition(:,2*ones(1,n))').^2 );end%========================================================================== % 进化主程序%%===================================== ===================================== eranum = 1;H=waitbar(0,'Please wait...');while(eranum=MaxEranum)for j=1:mif options(1)==1%eval(['[fit(j)]=' FUN '(Pop(j,:));']);%但执行字符串速度比直接计算函数值慢fit(j)=feval(FUN,Pop(j,:));%计算适应度elseif options(1)==0%eval(['[fit(j)]=' FUN '(b2f(Pop(j,:),bounds,bits));']);fit(j)=feval(FUN,(b2f(Pop(j,:),bounds,bits)));elsefit(j)=-feval(FUN,Pop(j,:),D);endend[Maxfit,fitIn]=max(fit);%得到每一代最大适应值Meanfit(eranum)=mean(fit);BestPop(eranum,:)=Pop(fitIn,:);Trace(eranum)=Maxfit;if options(1)==1Pop=(Pop-Lb)./(Ub-Lb);%将定义域映射到[0,1]:[Lb,Ub]--[0,1] ,Pop--(Pop-Lb)./(Ub-Lb)endswitch round(unifrnd(0,eranum/MaxEranum))%进化前期尽量使用实行锦标赛选择,后期逐步增大非线性排名选择case {0} [selectpop]=TournamentSelect(Pop,fit,bits);%锦标赛选择case {1}[selectpop]=NonlinearRankSelect(Pop,fit,bits);%非线性排名选择end完整可以运行的数值优化遗传算法源代码[CrossOverPop]=CrossOver(selectpop,pCross,OptsCrossOver(er anum,:));%交叉[MutationPop]=Mutation(CrossOverPop,fit,pMutation,VarNum,O ptsMutation(eranum,:)); %变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位%更新种群if options(1)==1Pop=Lb+InversionPop.*(Ub-Lb);%还原PopelsePop=InversionPop;endpMutation=pm0+(eranum^3)*(pCross/2-pm0)/(eranum^4); %逐步增大变异率至1/2交叉率percent=num2str(round(100*eranum/MaxEranum));waitbar(eranum/MaxEranum,H,['Evolution complete ',percent,'%']);eranum=eranum+1;endclose(H);% 格式化输出进化结果和解的变化情况t=1:MaxEranum;plot(t,Trace,t,Meanfit);legend('解的变化','种群的变化');title('函数优化的遗传算法');xlabel('进化世代数');ylabel('每一代最优适应度');[MaxFval,MaxFvalIn]=max(Trace);if options(1)==1|options(1)==3X=BestPop(MaxFvalIn,:);elseif options(1)==0X=b2f(BestPop(MaxFvalIn,:),bounds,bits);endhold on;plot(MaxFvalIn,MaxFval,'*');text(MaxFvalIn+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf(' Best generation:\n %d\n\n Best X:\n %s\n\n MaxFval\n %f\n',...MaxFvalIn,num2str(X),MaxFval);disp(str1);% -计时T2=clock;elapsed_time=T2-T1;if elapsed_time(6)0elapsed_time(6)=elapsed_time(6)+60;elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_t ime(4)-1;end完整可以运行的数值优化遗传算法源代码str2=sprintf('elapsed_time\n %d (h) %d (m) %.4f (s)',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%===================================== ===================================== % 遗传操作子程序%%===================================== ===================================== % -- 初始化种群--% 采用浮点编码和二进制Gray编码(为了克服二进制编码的Hamming悬崖缺点)function [initpop]=InitPop(popsize,bounds,bits,options)numVars=size(bounds,1);%变量数目rang=(bounds(:,2)-bounds(:,1))';%变量范围if options(1)==1initpop=zeros(popsize,numVars);initpop=(ones(popsize,1)*rang).*(rand(popsize,numVars))+(ones (popsize,1)*bounds(:,1)');elseif options(1)==0precision=options(2);%由求解精度确定二进制编码长度len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i1时,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);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individualelsefor i=1:popsizeinitpop(i,:)=randperm(numVars);%为Tsp问题初始化种群endend% -- 二进制串解码--function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=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))=1function [NewPop]=NonlinearRankSelect(OldPop,fit,bits) global m n NewPopfit=fit';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=[0 cumsum(newfit)];%计算各选择概率之和rNums=rand(m,1);newIn=1;while(newIn=m)NewPop(newIn,:)=OldPop(length(find(rNums(newIn)newfit)),:);newIn=newIn+1;end% -- 锦标赛选择(含精英选择) --function [NewPop]=TournamentSelect(OldPop,fit,bits)global m n NewPopnum=floor(m./2.^(1:10));num(find(num==0))=[];L=length(num);a=sum(num);b=m-a;PopIn=1;while(PopIn=L)r=unidrnd(m,num(PopIn),2^PopIn);[LocalMaxfit,In]=max(fit(r),[],2);SelectIn=r((In-1)*num(PopIn)+[1:num(PopIn)]');NewPop(sum(num(1:PopIn))-num(PopIn)+1:sum(num(1:PopIn)),:)=OldPop(SelectIn,:);PopIn=PopIn+1;r=[];In=[];LocalMaxfit=[];endif b1NewPop((sum(num)+1):(sum(num)+b-1),:)=OldPop(unidrnd(m,1,b-1),:);end[GlobalMaxfit,I]=max(fit);%保留每一代中最佳个体NewPop(end,:)=OldPop(I,:);% -- 交叉操作--function [NewPop]=CrossOver(OldPop,pCross,opts)global m n NewPopr=rand(1,m);完整可以运行的数值优化遗传算法源代码y1=find(rpCross);y2=find(r=pCross);len=length(y1);if len==1|(len2mod(len,2)==1)%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endi=0;if length(y1)=2if opts(1)==1%浮点编码交叉while(i=length(y1)-2)NewPop(y1(i+1),:)=OldPop(y1(i+1),:);NewPop(y1(i+2),:)=OldPop(y1(i+2),:);if opts(2)==0n1%discret crossoverPoints=sort(unidrnd(n,1,2));NewPop(y1(i+1),Points(1):Points(2))=OldPop(y1(i+2),Points(1):Po ints(2));NewPop(y1(i+2),Points(1):Points(2))=OldPop(y1(i+1),Points(1):Po ints(2));elseif opts(2)==1%arithmetical crossoverPoints=round(unifrnd(0,pCross,1,n));CrossPoints=find(Points==1);r=rand(1,length(CrossPoints));NewPop(y1(i+1),CrossPoints)=r.*OldPop(y1(i+1),CrossPoints)+(1 -r).*OldPop(y1(i+2),CrossPoints);NewPop(y1(i+2),CrossPoints)=r.*OldPop(y1(i+2),CrossPoints)+(1 -r).*OldPop(y1(i+1),CrossPoints); else %AEA recombination Points=round(unifrnd(0,pCross,1,n));CrossPoints=find(Points==1);v=unidrnd(4,1,2);NewPop(y1(i+1),CrossPoints)=(floor(10^v(1)*OldPop(y1(i+1),Cro ssPoints))+...10^v(1)*OldPop(y1(i+2),CrossPoints)-floor(10^v(1)*OldPop(y1(i+2),CrossPoints)))/10^v(1);NewPop(y1(i+2),CrossPoints)=(floor(10^v(2)*OldPop(y1(i+2),Cro ssPoints))+...10^v(2)*OldPop(y1(i+1),CrossPoints)-floor(10^v(2)*OldPop(y1(i+1),CrossPoints)))/10^v(2);endi=i+2;endelseif opts(1)==0%二进制编码交叉while(i=length(y1)-2)if opts(2)==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),:)); endi=i+2;endelse %Tsp问题次序杂交for i=0:2:length(y1)-2xPoints=sort(unidrnd(n,1,2));NewPop([y1(i+1)y1(i+2)],xPoints(1):xPoints(2))=OldPop([y1(i+2)y1(i+1)],xPoints(1):xPoints(2));完整可以运行的数值优化遗传算法源代码%NewPop(y1(i+2),xPoints(1):xPoints(2))=OldPop(y1(i+1),xPo ints(1):xPoints(2));temp=[OldPop(y1(i+1),xPoints(2)+1:n)OldPop(y1(i+1),1:xPoints(2))];for del1i=xPoints(1):xPoints(2)temp(find(temp==OldPop(y1(i+2),del1i)))=[];endNewPop(y1(i+1),(xPoints(2)+1):n)=temp(1:(n-xPoints(2)));NewPop(y1(i+1),1:(xPoints(1)-1))=temp((n-xPoints(2)+1):end);temp=[OldPop(y1(i+2),xPoints(2)+1:n)OldPop(y1(i+2),1:xPoints(2))];for del2i=xPoints(1):xPoints(2)temp(find(temp==OldPop(y1(i+1),del2i)))=[];endNewPop(y1(i+2),(xPoints(2)+1):n)=temp(1:(n-xPoints(2)));NewPop(y1(i+2),1:(xPoints(1)-1))=temp((n-xPoints(2)+1):end);endendendNewPop(y2,:)=OldPop(y2,:);% -二进制串均匀交叉算子function[children1,children2]=EqualCrossOver(parent1,parent2) global n children1 children2hidecode=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 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(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,fit,pMutation,VarNum,opts) global m n NewPopNewPop=OldPop;r=rand(1,m);MutIn=find(r=pMutation);L=length(MutIn);完整可以运行的数值优化遗传算法源代码i=1;if opts(1)==1%浮点变异maxfit=max(fit);upfit=maxfit+0.05*abs(maxfit);if opts(2)==1|opts(2)==3while(i=L)%自适应变异(自增或自减)Point=unidrnd(n);T=(1-fit(MutIn(i))/upfit)^2;q=abs(1-rand^T);%if q1%按严格数学推理来说,这段程序是不能缺少的% q=1%endp=OldPop(MutIn(i),Point)*(1-q);if unidrnd(2)==1NewPop(MutIn(i),Point)=p+q;elseNewPop(MutIn(i),Point)=p;endi=i+1;endelseif opts(2)==2|opts(2)==4%AEA变异(任意变量的某一位变异)while(i=L)Point=unidrnd(n);T=(1-abs(upfit-fit(MutIn(i)))/upfit)^2;v=1+unidrnd(1+ceil(10*T));%v=1+unidrnd(5+ceil(10*eranum/MaxEranum));q=mod(floor(OldPop(MutIn(i),Point)*10^v),10);NewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)-(q-unidrnd(9))/10^v;i=i+1;endelsewhile(i=L)Point=unidrnd(n);if round(rand)NewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)*(1-rand);elseNewPop(MutIn(i),Point)=OldPop(MutIn(i),Point)+(1-OldPop(MutIn(i),Point))*rand; endi=i+1;endendelseif opts(1)==0%二进制串变异if L=1while i=Lk=unidrnd(n,1,VarNum); %设置变异点数(=变量数)for j=1:length(k)if NewPop(MutIn(i),k(j))==1NewPop(MutIn(i),k(j))=0;else完整可以运行的数值优化遗传算法源代码NewPop(MutIn(i),k(j))=1;endendi=i+1;endendelse%Tsp变异if opts(2)==1|opts(2)==2|opts(2)==3|opts(2)==4numMut=ceil(pMutation*m);r=unidrnd(m,numMut,2);[LocalMinfit,In]=min(fit(r),[],2);SelectIn=r((In-1)*numMut+[1:numMut]');while(i=numMut)mPoints=sort(unidrnd(n,1,2));if mPoints(1)~=mPoints(2)NewPop(SelectIn(i),1:mPoints(1)-1)=OldPop(SelectIn(i),1:mPoints(1)-1);NewPop(SelectIn(i),mPoints(1):mPoints(2)-1)=OldPop(SelectIn(i),mPoints(1)+1:mPoints(2));NewPop(SelectIn(i),mPoints(2))=OldPop(SelectIn(i),mPoints(1));NewPop(SelectIn(i),mPoints(2)+1:n)=OldPop(SelectIn(i),mPoints( 2)+1:n);elseNewPop(SelectIn(i),:)=OldPop(SelectIn(i),:);endi=i+1;endr=rand(1,m);MutIn=find(r=pMutation);L=length(MutIn);while i=LmPoints=sort(unidrnd(n,1,2));rIn=randperm(mPoints(2)-mPoints(1)+1);NewPop(MutIn(i),mPoints(1):mPoints(2))=OldPop(MutIn(i),mPoin ts(1)+rIn-1);i=i+1;endendend% -- 倒位操作--function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r=pInversion);len=length(PopIn);if len=1while(i=len)d=sort(unidrnd(n,1,2));完整可以运行的数值优化遗传算法源代码NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1)); i=i+1;。

自适应遗传算法matlab代码

自适应遗传算法matlab代码
gen=0;
v=bs2rv(Chrom,FieldD);
ObjV=v.*sin(10*pi*v)+2.0;
while gen<maxgen,
FitnV=ranking(-ObjV);
SelCh=select('sus',Chrom,FitnV,GGAP);
FitnVmax=max(FitnV);
FitnVave=sum(FitnV)/NIND;
v=bs2rv(SelCh,FieldD);
ObjVSel=v.*sin(10*pi*v)+2.0;
[Chrom ObjV]=reins(Chrom,SelCh,1,1,ObjV,ObjVSel);
gen=gen+1;
variable=bs2rv(Chrom, FieldD)
[Y,I]=max(ObjV),hold on;
plot(trace(1,:)','Pr');
hold on;
plot(trace(2,:)','-.');grid;
legend('解的变化','种群均值的变化')
</maxgen,
plot(I,Y,'bo');
trace(1,gen)=max(ObjV);
trace(2,gen)=sum(ObjV)/length(ObjV);
if (gen==20)
figure(2);
plot(ObjV);hold on;
plot(ObjV,'b*');grid;
end
%end
figure(3);
else
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

遗传算法解决简单问题
%主程序:用遗传算法求解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<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=scnew; %产生了新的种群
%计算新种群的适应度
[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((boundsend),BitLength)-1);
xmax(Generation)=xx;
Generation=Generation+1;
end
Generation=Generation-1;
Bestpopulation=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]);
box off;
hold off;
%子程序:计算适应度函数,函数名称存储为fitnessfun
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((boundsend),BitLength)-1);
Fitvalue(i)=targetfun(xx);
end
%给适应度函数加上一个大小合理的数以便保证种群适应值为正数
Fitvalue=Fitvalue'+230;
%计算选择概率
fsum=sum(Fitvalue);
Pperpopulation=Fitvalue/fsum;
%计算累积概率
cumsump(1)=Pperpopulation(1);
for i=2:popsize
cumsump(i)=cumsump(i-1)+Pperpopulation(i);
end
cumsump=cumsump';
%子程序:新种群变异操作,函数名称存储为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
%子程序:新种群交叉操作,函数名存储为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
%子程序:判断遗传运算是否需要进行交叉或变异,函数名称存储为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);
%子程序:新种群选择操作,函数名称存储为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
%子程序:将二进制数转换为十进制数,函数名称存储为transform2to10.m
function x=transform2to10(Populaton)
BitLength=size(Populaton,2);
x=Populaton(BitLength);
for i=1:BitLength-1
x=x+Populaton(BitLength-i)*power(2,i);
end
%子程序:对于优化最大值或极大值函数问题,目标函数可以作为适应度函数%函数名称存储为targetfun.m
function y=targetfun(x) %目标函数
y=200*exp(-0.05*x).*sin(x);
运行结果:
Bestpopulation =
1.5764
Besttargetfunvalue =
184.8383
基本接近理论值。

相关文档
最新文档