当前位置:首页 » 操作系统 » 遗传算法神经网络matlab

遗传算法神经网络matlab

发布时间: 2024-04-23 11:57:43

① MATLAB线性神经网络的程序,跪求。。

美国Michigan 大学的 Holland 教授提出的遗传算法(GeneticAlgorithm, GA)是求解复杂的组合优化问题的有效方法 ,其思想来自于达尔文进化论和门德尔松遗传学说 ,它模拟生物进化过程来从庞大的搜索空间中筛选出较优秀的解,是戚镇一种高效而且具有强鲁棒性方法。所以,遗传算法在求解TSP和 MTSP问题中得到了广泛的应用。

matlab程序如下:

function[opt_rte,opt_brk,min_dist] =mtspf_ga(xy,dmat,salesmen,min_tour,pop_size,num_iter)

%%

%实例

% n = 20;%城市个数

% xy = 10*rand(n,2);%城市坐标 随机产生,也可以自己设定

% salesmen = 5;%旅行商个数

% min_tour = 3;%每个旅行商最少访问的城市数

% pop_size = 80;%种群个数

% num_iter = 200;%迭代次数

% a = meshgrid(1:n);

% dmat =reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);

% [opt_rte,opt_brk,min_dist] = mtspf_ga(xy,dmat,salesmen,min_tour,...

% pop_size,num_iter);%函数

%%

[N,dims]= size(xy); %城市矩阵大小

[nr,nc]= size(dmat); %城市距离矩阵大小

n = N -1;% 除去起始的城市后剩余的城市的数

% 初始化路线、断点的选择

num_brks= salesmen-1;

dof = n- min_tour*salesmen; %初始化路线、断点的选择

addto =ones(1,dof+1);

for k =2:num_brks

addto = cumsum(addto);

end

cum_prob= cumsum(addto)/sum(addto);

%% 初始化种群

pop_rte= zeros(pop_size,n); % 种群路径

pop_brk= zeros(pop_size,num_brks); % 断点集合的种群

for k =1:pop_size

pop_rte(k,:) = randperm(n)+1;

pop_brk(k,:) = randbreaks();

end

% 画图路径曲线颜色

clr =[1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0];

ifsalesmen > 5

clr = hsv(salesmen);

end

%%

% 基于遗传算法的MTSP

global_min= Inf; %初始化最短路径

total_dist= zeros(1,pop_size);

dist_history= zeros(1,num_iter);

tmp_pop_rte= zeros(8,n);%当前的路径设置

tmp_pop_brk= zeros(8,num_brks); %当前的断点设置

new_pop_rte= zeros(pop_size,n);%更新的路径设置

new_pop_brk= zeros(pop_size,num_brks);%更新的断点设置

foriter = 1:num_iter

% 计算适应值

for p = 1:pop_size

d = 0;

p_rte = pop_rte(p,:);

p_brk = pop_brk(p,:);

rng = [[1 p_brk+1];[p_brk n]]';

for s = 1:salesmen

d = d + dmat(1,p_rte(rng(s,1)));% 添加开始的路径

for k = rng(s,1):rng(s,2)-1

d = d + dmat(p_rte(k),p_rte(k+1));

end

渗旁 d = d + dmat(p_rte(rng(s,2)),1); % 添加结束的的路径

end

丛仔橡 total_dist(p) = d;

end

% 找到种群中最优路径

[min_dist,index] = min(total_dist);

dist_history(iter) = min_dist;

if min_dist < global_min

global_min = min_dist;

opt_rte = pop_rte(index,:); %最优的最短路径

opt_brk = pop_brk(index,:);%最优的断点设置

rng = [[1 opt_brk+1];[opt_brk n]]';%设置记录断点的方法

figure(1);

for s = 1:salesmen

rte = [1 opt_rte(rng(s,1):rng(s,2))1];

plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:));

title(sprintf('城市数目为 = %d,旅行商数目为 = %d,总路程 = %1.4f, 迭代次数 =%d',n+1,salesmen,min_dist,iter));

hold on

grid on

end

plot(xy(1,1),xy(1,2),'ko');

hold off

end

% 遗传操作

rand_grouping = randperm(pop_size);

for p = 8:8:pop_size

rtes = pop_rte(rand_grouping(p-7:p),:);

brks = pop_brk(rand_grouping(p-7:p),:);

dists =total_dist(rand_grouping(p-7:p));

[ignore,idx] = min(dists);

best_of_8_rte = rtes(idx,:);

best_of_8_brk = brks(idx,:);

rte_ins_pts = sort(ceil(n*rand(1,2)));

I = rte_ins_pts(1);

J = rte_ins_pts(2);

for k = 1:8 %产生新种群

tmp_pop_rte(k,:) = best_of_8_rte;

tmp_pop_brk(k,:) = best_of_8_brk;

switch k

case 2% 倒置操作

tmp_pop_rte(k,I:J) =fliplr(tmp_pop_rte(k,I:J));

case 3 % 互换操作

tmp_pop_rte(k,[I J]) =tmp_pop_rte(k,[J I]);

case 4 % 滑动平移操作

tmp_pop_rte(k,I:J) =tmp_pop_rte(k,[I+1:J I]);

case 5% 更新断点

tmp_pop_brk(k,:) = randbreaks();

case 6 % 倒置并更新断点

tmp_pop_rte(k,I:J) =fliplr(tmp_pop_rte(k,I:J));

tmp_pop_brk(k,:) =randbreaks();

case 7 % 互换并更新断点

tmp_pop_rte(k,[I J]) =tmp_pop_rte(k,[J I]);

tmp_pop_brk(k,:) =randbreaks();

case 8 % 评议并更新断点

tmp_pop_rte(k,I:J) =tmp_pop_rte(k,[I+1:J I]);

tmp_pop_brk(k,:) =randbreaks();

otherwise

end

end

new_pop_rte(p-7:p,:) = tmp_pop_rte;

new_pop_brk(p-7:p,:) = tmp_pop_brk;

end

pop_rte = new_pop_rte;

pop_brk = new_pop_brk;

end

figure(2)

plot(dist_history,'b','LineWidth',2);

title('历史最优解');

xlabel('迭代次数')

ylabel('最优路程')

% 随机产生一套断点 的集合

function breaks = randbreaks()

if min_tour == 1 % 一个旅行商时,没有断点的设置

tmp_brks = randperm(n-1);

breaks =sort(tmp_brks(1:num_brks));

else % 强制断点至少找到最短的履行长度

num_adjust = find(rand <cum_prob,1)-1;

spaces =ceil(num_brks*rand(1,num_adjust));

adjust = zeros(1,num_brks);

for kk = 1:num_brks

adjust(kk) = sum(spaces == kk);

end

breaks = min_tour*(1:num_brks) +cumsum(adjust);

end

end

disp('最优路径为:/n')

disp(opt_rte);

disp('其中断点为为:/n')

disp(opt_brk);

end


② 运行遗基于遗传算法的BP神经网络MATLAB代码程序时总是出错!!!

这个问题也困扰了我好久,终于解决了。给你个ga.m程序,新建m文件复制进去,再运行程序试试。
%ga.m
function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,
% termFN,termOps,selectFN,selectOps,
% xOverFNs,xOverOps,mutFNs,mutOps)
%
% Output Arguments:
% x - the best solution found ring the course of the run
% endPop - the final population
% bPop - a trace of the best population
% traceInfo - a matrix of best and means of the ga for each generation
%
% Input Arguments:
% bounds - a matrix of upper and lower bounds on the variables
% evalFN - the name of the evaluation .m function
% evalOps - options to pass to the evaluation function ([NULL])
% startPop - a matrix of solutions that can be initialized
% from initialize.m
% opts - [epsilon prob_ops display] change required to consider two
% solutions different, prob_ops 0 if you want to apply the
% genetic operators probabilisticly to each solution, 1 if
% you are supplying a deterministic number of operator
% applications and display is 1 to output progress 0 for
% quiet. ([1e-6 1 0])
% termFN - name of the .m termination function (['maxGenTerm'])
% termOps - options string to be passed to the termination function
% ([100]).
% selectFN - name of the .m selection function (['normGeomSelect'])
% selectOpts - options string to be passed to select after
% select(pop,#,opts) ([0.08])
% xOverFNS - a string containing blank seperated names of Xover.m
% files (['arithXover heuristicXover simpleXover'])
% xOverOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([2 0;2 3;2 0])
% mutFNs - a string containing blank seperated names of mutation.m
% files (['boundaryMutation multiNonUnifMutation ...
% nonUnifMutation unifMutation'])
% mutOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])

% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 1, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. A of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

%%$Log: ga.m,v $
%Revision 1.10 1996/02/02 15:03:00 jjoine
% Fixed the ordering of imput arguments in the comments to match
% the actual order in the ga function.
%
%Revision 1.9 1995/08/28 20:01:07 chouck
% Updated initialization parameters, updated mutation parameters to reflect
% b being the third option to the nonuniform mutations
%
%Revision 1.8 1995/08/10 12:59:49 jjoine
%Started Logfile to keep track of revisions
%

n=nargin;
if n<2 | n==6 | n==10 | n==12
disp('Insufficient arguements')
end
if n<3 %Default evalation opts.
evalOps=[];
end
if n<5
opts = [1e-6 1 0];
end
if isempty(opts)
opts = [1e-6 1 0];
end

if any(evalFN<48) %Not using a .m file
if opts(2)==1 %Float ga
e1str=['x=c1; c1(xZomeLength)=', evalFN ';'];
e2str=['x=c2; c2(xZomeLength)=', evalFN ';'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...
evalFN ';'];
end
else %Are using a .m file
if opts(2)==1 %Float ga
e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);'];
e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ...
'(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];
end
end

if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<12 %Default muatation information
if opts(2)==1 %Float GA
mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'];
mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];
else %Binary GA
mutFNs=['binaryMutation'];
mutOps=[0.05];
end
end
if n<10 %Default crossover information
if opts(2)==1 %Float GA
xOverFNs=['arithXover heuristicXover simpleXover'];
xOverOps=[2 0;2 3;2 0];
else %Binary GA
xOverFNs=['simpleXover'];
xOverOps=[0.6];
end
end
if n<9 %Default select opts only i.e. roullete wheel.
selectOps=[];
end
if n<8 %Default select info
selectFN=['normGeomSelect'];
selectOps=[0.08];
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<4 %No starting population passed given
startPop=[];
end
if isempty(startPop) %Generate a population at random
%startPop=zeros(80,size(bounds,1)+1);
startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2));
end

if opts(2)==0 %binary
bits=calcbits(bounds,opts(1));
end

xOverFNs=parse(xOverFNs);
mutFNs=parse(mutFNs);

xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness
numVar = xZomeLength-1; %Number of variables
popSize = size(startPop,1); %Number of indivials in the pop
endPop = zeros(popSize,xZomeLength); %A secondary population matrix
c1 = zeros(1,xZomeLength); %An indivial
c2 = zeros(1,xZomeLength); %An indivial
numXOvers = size(xOverFNs,1); %Number of Crossover operators
numMuts = size(mutFNs,1); %Number of Mutation operators
epsilon = opts(1); %Threshold for two fittness to differ
oval = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn = 1; %Number of times best has changed
done = 0; %Done with simulated evolution
gen = 1; %Current Generation Number
collectTrace = (nargout>3); %Should we collect info every gen
floatGA = opts(2)==1; %Probabilistic application of ops
display = opts(3); %Display progress

while(~done)
%Elitist Model
[bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
best = startPop(bindx,:);

if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
traceInfo(gen,4)=std(startPop(:,xZomeLength));
end

if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
if display
fprintf(1,'\n%d %f\n',gen,bval); %Update the display
end
if floatGA
bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix
else
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
end
bFoundIn=bFoundIn+1; %Update number of changes
oval=bval; %Update the best val
else
if display
fprintf(1,'%d ',gen); %Otherwise just update num gen
end
end

endPop = feval(selectFN,startPop,[gen selectOps]); %Select

if floatGA %Running with the model where the parameters are numbers of ops
for i=1:numXOvers,
for j=1:xOverOps(i,1),
a = round(rand*(popSize-1)+1); %Pick a parent
b = round(rand*(popSize-1)+1); %Pick another parent
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
[c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]);

if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new
c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating
elseif c1(1:numVar)==endPop(b,(1:numVar))
c1(xZomeLength)=endPop(b,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
if c2(1:numVar)==endPop(a,(1:numVar))
c2(xZomeLength)=endPop(a,xZomeLength);
elseif c2(1:numVar)==endPop(b,(1:numVar))
c2(xZomeLength)=endPop(b,xZomeLength);
else
%[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]);
eval(e2str);
end

endPop(a,:)=c1;
endPop(b,:)=c2;
end
end

for i=1:numMuts,
for j=1:mutOps(i,1),
a = round(rand*(popSize-1)+1);
c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar))
c1(xZomeLength)=endPop(a,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
endPop(a,:)=c1;
end
end

else %We are running a probabilistic model of genetic operators
for i=1:numXOvers,
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
cp=find(rand(popSize,1)<xOverOps(i,1)==1);
if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
cp=reshape(cp,size(cp,1)/2,2);
for j=1:size(cp,1)
a=cp(j,1); b=cp(j,2);
[endPop(a,:) endPop(b,:)] = feval(xN,endPop(a,:),endPop(b,:),...
bounds,[gen xOverOps(i,:)]);
end
end
for i=1:numMuts
mN=deblank(mutFNs(i,:));
for j=1:popSize
endPop(j,:) = feval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);
eval(e1str);
end
end
end

gen=gen+1;
done=feval(termFN,[gen termOps],bPop,endPop); %See if the ga is done
startPop=endPop; %Swap the populations

[bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
startPop(bindx,:) = best; %replace it with the worst
end

[bval,bindx] = max(startPop(:,xZomeLength));
if display
fprintf(1,'\n%d %f\n',gen,bval);
end

x=startPop(bindx,:);
if opts(2)==0 %binary
x=b2f(x,bounds,bits);
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
else
bPop(bFoundIn,:)=[gen startPop(bindx,:)];
end

if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
end

③ 如何使用遗传算法或神经网络在MATLAB 中求二元函数最小值

你最好能提供具体的二元函数表达式,这样就可以有目的去帮你解决。一般遗传算法可以用ga()函数来求解。例如:
fun = @(x) (x(1) - 0.2)^2 + (x(2) - 1.7)^2
x = ga(fun,2)

执行结果
x = 0.20208 1.6766

④ 遗传算法优化概率神经网络的matlab代码

原理大概是,设置一个初始种群,种群里的个体就是平滑因子,经过遗传算法的选择、交叉、变异后,逐渐找到一个最佳的spread,即为最终结果。

附件是一个GA-BP算法的程序,虽然不同,但是原理是相近的,可以参考。

遗传算法的基本运算过程如下:

a)初始化:设置进化代数计数器t=0,设置最大进化代数T,随机生成M个个体作为初始群体P(0)。

b)个体评价:计算群体P(t)中各个个体的适应度。

c)选择运算:将选择算子作用于群体。选择的目的是把优化的个体直接遗传到下一代或通过配对交叉产生新的个体再遗传到下一代。选择操作是建立在群体中个体的适应度评估基础上的。

d)交叉运算:将交叉算子作用于群体。遗传算法中起核心作用的就是交叉算子。

e)变异运算:将变异算子作用于群体。即是对群体中的个体串的某些基因座上的基因值作变动。

群体P(t)经过选择、交叉、变异运算之后得到下一代群体P(t+1)。

f)终止条件判断:若t=T,则以进化过程中所得到的具有最大适应度个体作为最优解输出,终止计算。

⑤ matlab的遗传算法优化BP神经网络

对y=x1^2+x2^2非线性系统进行建模,用1500组数据对网络进行构建网络,500组数据测试网络。由于BP神经网络初始神经元之间的权值和阈值一般随机选择,因此容易陷入局部最小值。本方法使用遗传算法优化初始神经元之间的权值和阈值,并对比使用遗传算法前后的效果。
步骤:
未经遗传算法优化的BP神经网络建模
1、 随机生成2000组两维随机数(x1,x2),并计算对应的输出y=x1^2+x2^2,前1500组数据作为训练数据input_train,后500组数据作为测试数据input_test。并将数据存储在data中待遗传算法中使用相同的数据。
2、 数据预处理:归一化处理。
3、 构建BP神经网络的隐层数,次数,步长,目标。
4、 使用训练数据input_train训练BP神经网络net。

⑥ 如何使用遗传算法或神经网络在MATLAB 中求二元函数最小值

% 2008年4月12日修改
%**********************%主函数*****************************************
function main()
global chrom lchrom oldpop newpop varible fitness popsize sumfitness %定义全局变量
global pcross pmutation temp bestfit maxfit gen bestgen length epop efitness val varible2 varible1
global maxgen po pp mp np val1
length=18;
lchrom=30; %染色体长度
popsize=30; %种群大小
pcross=0.6; %交叉概率
pmutation=0.01; %变异概率
maxgen=1000; %最大代数
mp=0.1; %保护概率
%
initpop; % 初始种群
%
for gen=1:maxgen
generation;
end
%
best;
bestfit % 最佳个体适应度值输出
bestgen % 最佳个体所在代数输出
x1= val1(bestgen,1)
x2= val1(bestgen,2)
gen=1:maxgen;
figure
plot(gen,maxfit(1,gen)); % 进化曲线
title('精英保留');
%
%********************** 产生初始种群 ************************************
%
function initpop()
global lchrom oldpop popsize
oldpop=round(rand(popsize,lchrom)); %生成的oldpop为30行12列由0,1构成的矩阵
%其中popsize为种群中个体数目lchrom为染色体编码长度

%
%*************************%产生新一代个体**********************************
%
function generation()
global epop oldpop popsize mp
objfun; %计算适应度值
n=floor(mp*popsize); %需要保留的n个精英个体
for i=1:n
epop(i,:)=oldpop((popsize-n+i),:);
% efitness(1,i)=fitness(1,(popsize-n+i))
end
select; %选择操作
crossover;
mutation;
elite; %精英保留

%
%************************%计算适应度值************************************
%
function objfun()
global lchrom oldpop fitness popsize chrom varible varible1 varible2 length
global maxfit gen epop mp val1
a1=-3; b1=3;
a2=-2;b2=2;
fitness=0;
for i=1:popsize
%前一未知数X1
if length~=0
chrom=oldpop(i,1:length);% before代表节点位置
c=decimal(chrom);
varible1(1,i)=a1+c*(b1-a1)/(2.^length-1); %对应变量值

%后一未知数
chrom=oldpop(i,length+1:lchrom);% before代表节点位置
c=decimal(chrom);
varible2(1,i)=a2+c*(b2-a2)/(2.^(lchrom-length)-1); %对应变量值
else
chrom=oldpop(i,:);
c=decimal(chrom);
varible(1,i)=a1+c*(b1-a1)/(2.^lchrom-1); %对应变量值
end
%两个自变量
fitness(1,i)=4*varible1(1,i)^2-2.1*varible1(1,i)^4+1/3*varible1(1,i)^6+varible1(1,i)*varible2(1,i)-4*varible2(1,i)^2+4*varible2(1,i)^4;
%fitness(1,i) = 21.5+varible1(1,i)*sin(4*pi*varible1(1,i))+varible2(1,i) *sin(20*pi*varible2(1,i));
%一个自变量
%fitness(1,i) = 20*cos(0.25*varible(1,i))-12*sin(0.33*varible(1,i))+40 %个体适应度函数值
end
lsort; % 个体排序
maxfit(1,gen)=max(fitness); %求本代中的最大适应度值maxfit

val1(gen,1)=varible1(1,popsize);
val1(gen,2)=varible2(1,popsize);
%************************二进制转十进制**********************************
%
function c=decimal(chrom)
c=0;
for j=1:size(chrom,2)
c=c+chrom(1,j)*2.^(size(chrom,2)-j);
end
%
%************************* 个体排序 *****************************
% 从小到大顺序排列
%
function lsort()
global popsize fitness oldpop epop efitness mp val varible2 varible1
for i=1:popsize
j=i+1;
while j<=popsize
if fitness(1,i)>fitness(1,j)
tf=fitness(1,i); % 适应度值
tc=oldpop(i,:); % 基因代码
fitness(1,i)=fitness(1,j); % 适应度值互换
oldpop(i,:)=oldpop(j,:); % 基因代码互换
fitness(1,j)=tf;
oldpop(j,:)=tc;
end
j=j+1;
end
val(1,1)=varible1(1,popsize);
val(1,2)=varible2(1,popsize);
end

%*************************转轮法选择操作**********************************
%
function select()
global fitness popsize sumfitness oldpop temp mp np
sumfitness=0; %个体适应度之和
for i=1:popsize % 仅计算(popsize-np-mp)个个体的选择概率
sumfitness=sumfitness+fitness(1,i);
end
%
for i=1:popsize % 仅计算(popsize-np-mp)个个体的选择概率
p(1,i)=fitness(1,i)/sumfitness; % 个体染色体的选择概率
end
%
q=cumsum(p); % 个体染色体的累积概率(内部函数),共(popsize-np-mp)个
%
b=sort(rand(1,popsize)); % 产生(popsize-mp)个随机数,并按升序排列。mp为保护个体数
j=1;
k=1;
while j<=popsize % 从(popsize-mp-np)中选出(popsize-mp)个个体,并放入temp(j,:)中;
if b(1,j)<q(1,k)
temp(j,:)=oldpop(k,:);
j=j+1;
else
k=k+1;
end
end
%
j=popsize+1; % 从统一挪过来的(popsize-np-mp)以后个体——优秀个体中选择
for i=(popsize+1):popsize % 将mp个保留个体放入交配池temp(i,:),以保证群体数popsize
temp(i,:)=oldpop(j,:);
j=j+1;
end
%
%**************************%交叉操作***************************************
%
function crossover()
global temp popsize pcross lchrom mp
n=floor(pcross*popsize); %交叉发生的次数(向下取整)
if rem(n,2)~=0 % 求余
n=n+1; % 保证为偶数个个体,便于交叉操作
end
%
j=1;
m=0;
%
% 对(popsize-mp)个个体将进行随机配对,满足条件者将进行交叉操作(按顺序选择要交叉的对象)
%
for i=1:popsize
p=rand; % 产生随机数
if p<pcross % 满足交叉条件
parent(j,:)=temp(i,:); % 选出1个父本
k(1,j)=i;
j=j+1; % 记录父本个数
m=m+1 ; % 记录杂交次数
if (j==3)&(m<=n) % 满足两个父本(j==3),未超过交叉次数(m<=n)
pos=round(rand*(lchrom-1))+1; % 确定随机位数(四舍五入取整)
for i=1:pos
child1(1,i)=parent(1,i);
child2(1,i)=parent(2,i);
end
for i=(pos+1):lchrom
child1(1,i)=parent(2,i);
child2(1,i)=parent(1,i);
end
i=k(1,1);
j=k(1,2);
temp(i,:)=child1(1,:);
temp(j,:)=child2(1,:);
j=1;
end
end
end
%
%****************************%变异操作*************************************
%
function mutation()
global popsize lchrom pmutation temp newpop oldpop mp
m=lchrom*popsize; % 总的基因数
n=round(pmutation*m); % 变异发生的次数
for i=1:n % 执行变异操作循环
k=round(rand*(m-1))+1; %确定变异位置(四舍五入取整)
j=ceil(k/lchrom); % 确定个体编号(取整)
l=rem(k,lchrom); %确定个体中变位基因的位置(求余)
if l==0
temp(j,lchrom)=~temp(j,lchrom); % 取非操作
else
temp(j,l)=~temp(j,l); % 取非操作
end
end
for i=1:popsize
oldpop(i,:)=temp(i,:); %产生新的个体
end
%
%*********************%精英选择%*******************************************
%
function elite()
global epop oldpop mp popsize
objfun; %计算适应度值
n=floor(mp*popsize); %需要保留的n个精英个体
for i=1:n
oldpop(i,:)=epop(i,:);
% efitness(1,i)=fitness(1,(popsize-n+i))
end;

%
%*********************%最佳个体********************************************
%
function best()
global maxfit bestfit gen maxgen bestgen
bestfit=maxfit(1,1);
gen=2;
while gen<=maxgen
if bestfit<maxfit(1,gen)
bestfit=maxfit(1,gen);
bestgen=gen;
end
gen=gen+1;
end
%**************************************************************************

⑦ 遗传算法的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宸ュ叿绠变腑镄勭炵粡缃戠粶鍜岄仐浼犵畻娉曡佹庝箞璋幂敤锛

閮芥槸链変袱绉嶈皟鐢ㄦ柟娉曪纴涓绉嶅浘褰㈢晫闱㈢殑锛岃繖涓浠庡紑濮嬭彍鍗曪纴铹跺悗宸ュ叿锛岀劧钖庝粠閲岄溃镓剧炵粡缃戠粶 neural network锛岄仐浼犵畻娉曞伐鍏锋槸 鍏ㄥ眬浼桦寲宸ュ叿绠遍噷闱㈢殑锛実lobal optimization銆
鍙﹀ 涓绉嶉氲繃锻戒护琛岃皟鐢锛岃繖涓闇瑕佷綘鐞呜В浣犻兘瑕佸仛浠涔堬纴鎴戠敤绁炵粡缃戠粶涓句緥銆傜涓姝ラ渶瑕佸厛鏁寸悊鍑鸿緭鍏ュ彉閲忓拰杈揿嚭鍙橀噺锛岀浜屾ヨ捐″苟鍒濆嫔寲绁炵粡缃戠粶锛岀涓夐儴璁缁冿纴绗锲涢儴銮峰缑缁撴灉銆
濡傛灉浣犳兂缁揿悎杩欎袱钥咃纴灏变细镟村姞澶嶆潅锛岃︾粏镄勪綘鍙浠ュ啀闂銆傛垜镟剧粡锅氲繃鐢ㄩ仐浼犵畻娉曚紭鍖栫炵粡缃戠粶镄勫伐鍏枫

热点内容
大宋脚本下载 发布:2024-11-27 16:21:01 浏览:89
sql认证培训 发布:2024-11-27 15:53:54 浏览:635
php的异常处理 发布:2024-11-27 15:53:54 浏览:417
电脑设置邮件服务器 发布:2024-11-27 15:53:07 浏览:4
安卓平板叫什么名字 发布:2024-11-27 15:48:12 浏览:172
税盘密码忘了去改需要带什么 发布:2024-11-27 15:41:10 浏览:277
拉筋要加密 发布:2024-11-27 15:38:51 浏览:324
电脑当服务器怎么降低功耗 发布:2024-11-27 15:30:45 浏览:642
苹果手机夸克缓存的视频怎么转为本地视频 发布:2024-11-27 15:24:05 浏览:811
linuxm4 发布:2024-11-27 15:15:12 浏览:322