frogfish 发表于 2007-7-19 07:28

用遗传算法优化BP神经网络的Matlab编程实例(转)

由于BP网络的权值优化是一个无约束优化问题,而且权值要采用实数编码,所以直接利用Matlab遗传算法工具箱。以下贴出的代码是为一个19输入变量,1个输出变量情况下的非线性回归而设计的,如果要应用于其它情况,只需改动编解码函数即可。
程序一:GA训练BP权值的主函数
function net=GABPNET(XX,YY)
%--------------------------------------------------------------------------
%GABPNET.m
%使用遗传算法对BP网络权值阈值进行优化,再用BP算法训练网络
%--------------------------------------------------------------------------
%数据归一化预处理
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
%创建网络
net=newff(minmax(XX),,{'tansig','tansig','purelin'},'trainlm');
%下面使用遗传算法对网络进行优化
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
aa=ones(S,1)*[-1,1];
popu=50;%种群规模
initPpp=initializega(popu,aa,'gabpEval');%初始化种群
gen=100;%遗传代数
%下面调用gaot工具箱,其中目标函数定义为gabpEval
=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
'normGeomSelect',,['arithXover'],,'nonUnifMutation',);
%绘收敛曲线图
figure(1)
plot(trace(:,1),1./trace(:,3),'r-');
hold on
plot(trace(:,1),1./trace(:,2),'b-');
xlabel('Generation');
ylabel('Sum-Squared Error');
figure(2)
plot(trace(:,1),trace(:,3),'r-');
hold on
plot(trace(:,1),trace(:,2),'b-');
xlabel('Generation');
ylabel('Fittness');
%下面将初步得到的权值矩阵赋给尚未开始训练的BP网络
=gadecod(x);
net.LW{2,1}=W1;
net.LW{3,2}=W2;
net.b{2,1}=B1;
net.b{3,1}=B2;
XX=P;
YY=T;
%设置训练参数
net.trainParam.show=1;
net.trainParam.lr=1;
net.trainParam.epochs=50;
net.trainParam.goal=0.001;
%训练网络
net=train(net,XX,YY);


程序二:适应值函数
function = gabpEval(sol,options)
% val - the fittness of this individual
% sol - the individual, returned to allow for Lamarckian evolution
% options -
load data2
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
for i=1:S,
   x(i)=sol(i);
end;
=gadecod(x);

程序三:编解码函数
function =gadecod(x)
load data2
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
% 前R*S1个编码为W1
for i=1:S1,
    for k=1:R,
      W1(i,k)=x(R*(i-1)+k);
    end
end
% 接着的S1*S2个编码(即第R*S1个后的编码)为W2
for i=1:S2,
   for k=1:S1,
      W2(i,k)=x(S1*(i-1)+k+R*S1);
   end
end
% 接着的S1个编码(即第R*S1+S1*S2个后的编码)为B1
for i=1:S1,
   B1(i,1)=x((R*S1+S1*S2)+i);
end
% 接着的S2个编码(即第R*S1+S1*S2+S1个后的编码)为B2
for i=1:S2,
   B2(i,1)=x((R*S1+S1*S2+S1)+i);
end
% 计算S1与S2层的输出
A1=tansig(W1*P,B1);
A2=purelin(W2*A1,B2);
% 计算误差平方和
SE=sumsqr(T-A2);
val=1/SE; % 遗传算法的适应值

上述程序需要调用gaot工具箱

来自:2nsoft.cn

花如月 发表于 2007-7-19 12:10

楼主辛苦了,多谢!

mcx8305 发表于 2007-8-31 08:35

请问frogfish,您能否上传initializega 函数的代码

请问frogfish,您能否上传initializega 函数的代码,我的是gads工具箱,没有这个函数。谢谢啦,在线等哦~

mcx8305 发表于 2007-8-31 09:40

上面的函数我有了,不过还是谢谢!

mcx8305 发表于 2007-8-31 09:43

还有一个问题,见下:

=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
'normGeomSelect',,['arithXover'],,'nonUnifMutation',);
这一句等号后面的怎么多项都是什么意思啊?我运行后出现:
??? Error using ==> ga
Too many input arguments.

Error in ==> GABPNET at 24
=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
谢谢解答!

mcx8305 发表于 2007-10-24 19:35

没人回吗?

=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
'normGeomSelect',,['arithXover'],,'nonUnifMutation',);
这一句等号后面的怎么多项都是什么意思啊?我运行后出现:
??? Error using ==> ga
Too many input arguments.

Error in ==> GABPNET at 24
=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
谢谢解答!

freeman0502609 发表于 2007-11-8 20:41

我用你那程序算出来的为什么没办法收敛呀

ziyanghh152 发表于 2008-3-12 20:25

to mcx8305::


=ga(aa,'gabpEval',[],initPpp,,'maxGenTerm',gen,...
'normGeomSelect',,['arithXover'],,'nonUnifMutation',);

去掉那三个省略号!!:loveliness:

tianyoume 发表于 2008-3-14 12:01

每次结果都不完全一致,但误差都应该在合理的范围内.

liujiadong0220 发表于 2008-4-8 09:55

下载下来,好好的研究,可能对我的硕士论文很大的帮助!谢谢lz

chg555 发表于 2008-5-7 10:18

下载下来,好好的研究,感谢感谢....

xxzhao 发表于 2008-5-17 18:21

一点也不懂。新手该如何开始呢?在线等待指教:handshake

frogfish 发表于 2008-5-21 10:45

原帖由 mcx8305 于 2007-8-31 08:35 发表 http://www.chinavib.com/forum/images/common/back.gif
请问frogfish,您能否上传initializega 函数的代码,我的是gads工具箱,没有这个函数。谢谢啦,在线等哦~

function = initializega(num, bounds, evalFN,evalOps,options)
% function =initializega(populationSize, variableBounds,evalFN,
%                           evalOps,options)
%    initializega creates a matrix of random numbers with
%    a number of rows equal to the populationSize and a number
%    columns equal to the number of rows in bounds plus 1 for
%    the f(x) value which is found by applying the evalFN.
%    This is used by the ga to create the population if it
%    is not supplied.
%
% pop            - the initial, evaluated, random population
% populatoinSize - the size of the population, i.e. the number to create
% variableBounds - a matrix which contains the bounds of each variable, i.e.
%                  
% evalFN         - the evaluation fn, usually the name of the .m file for
%                  evaluation
% evalOps      - any options to be passed to the eval function defaults []
% options      - options to the initialize function, ie.
%                   where eps is the epsilon value
%                  and the second option is 1 for float and 0 for binary,
%                  prec is the precision of the variables defaults

% Binary and Real-Valued Simulation Evolution for Matlab GAOT V2
% Copyright (C) 1998 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 copy of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

if nargin<5
options=;
end
if nargin<4
evalOps=[];
end

if any(evalFN<48) %Not a .m file
if options(2)==1 %Float GA
    estr=['x=pop(i,1); pop(i,xZomeLength)=', evalFN ';'];
else %Binary GA
    estr=['x=b2f(pop(i,:),bounds,bits); pop(i,xZomeLength)=', evalFN ';'];
end
else %A .m file
if options(2)==1 %Float GA
    estr=['[ pop(i,:) pop(i,xZomeLength)]=' evalFN '(pop(i,:),);'];
else %Binary GA
    estr=['x=b2f(pop(i,:),bounds,bits);=' evalFN ...
        '(x,); pop(i,:)=;'];
    end
end


numVars   = size(bounds,1);                 %Number of variables
rng         = (bounds(:,2)-bounds(:,1))'; %The variable ranges'

if options(2)==1 %Float GA
xZomeLength = numVars+1;                 %Length of string is numVar + fit
pop         = zeros(num,xZomeLength);         %Allocate the new population
pop(:,1:numVars)=(ones(num,1)*rng).*(rand(num,numVars))+...
    (ones(num,1)*bounds(:,1)');
else %Binary GA
bits=calcbits(bounds,options(1));
xZomeLength = sum(bits)+1;                 %Length of string is numVar + fit
pop = round(rand(num,sum(bits)+1));
end

for i=1:num
eval(estr);
end

frogfish 发表于 2008-5-21 10:47

原帖由 tianyoume 于 2008-3-14 12:01 发表 http://www.chinavib.com/forum/images/common/back.gif
每次结果都不完全一致,但误差都应该在合理的范围内.

初始化每次都不是一样,这是必然的

frogfish 发表于 2008-5-21 10:48

原帖由 xxzhao 于 2008-5-17 18:21 发表 http://www.chinavib.com/forum/images/common/back.gif
一点也不懂。新手该如何开始呢?在线等待指教:handshake

这不动就无能为力了,自己去看看matlab吧
页: [1] 2
查看完整版本: 用遗传算法优化BP神经网络的Matlab编程实例(转)