声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 15316|回复: 29

[人工智能] 用遗传算法优化BP神经网络的Matlab编程实例(转)

[复制链接]
发表于 2007-7-19 07:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
由于BP网络的权值优化是一个无约束优化问题,而且权值要采用实数编码,所以直接利用Matlab遗传算法工具箱。以下贴出的代码是为一个19输入变量,1个输出变量情况下的非线性回归而设计的,如果要应用于其它情况,只需改动编解码函数即可。
  1. 程序一:GA训练BP权值的主函数
  2. function net=GABPNET(XX,YY)
  3. %--------------------------------------------------------------------------
  4. %  GABPNET.m
  5. %  使用遗传算法对BP网络权值阈值进行优化,再用BP算法训练网络
  6. %--------------------------------------------------------------------------
  7. %数据归一化预处理
  8. nntwarn off
  9. XX=premnmx(XX);
  10. YY=premnmx(YY);
  11. %创建网络
  12. net=newff(minmax(XX),[19,25,1],{'tansig','tansig','purelin'},'trainlm');
  13. %下面使用遗传算法对网络进行优化
  14. P=XX;
  15. T=YY;
  16. R=size(P,1);
  17. S2=size(T,1);
  18. S1=25;%隐含层节点数
  19. S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
  20. aa=ones(S,1)*[-1,1];
  21. popu=50;%种群规模
  22. initPpp=initializega(popu,aa,'gabpEval');%初始化种群
  23. gen=100;%遗传代数
  24. %下面调用gaot工具箱,其中目标函数定义为gabpEval
  25. [x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
  26.   'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2 gen 3]);
  27. %绘收敛曲线图
  28. figure(1)
  29. plot(trace(:,1),1./trace(:,3),'r-');
  30. hold on
  31. plot(trace(:,1),1./trace(:,2),'b-');
  32. xlabel('Generation');
  33. ylabel('Sum-Squared Error');
  34. figure(2)
  35. plot(trace(:,1),trace(:,3),'r-');
  36. hold on
  37. plot(trace(:,1),trace(:,2),'b-');
  38. xlabel('Generation');
  39. ylabel('Fittness');
  40. %下面将初步得到的权值矩阵赋给尚未开始训练的BP网络
  41. [W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x);
  42. net.LW{2,1}=W1;
  43. net.LW{3,2}=W2;
  44. net.b{2,1}=B1;
  45. net.b{3,1}=B2;
  46. XX=P;
  47. YY=T;
  48. %设置训练参数
  49. net.trainParam.show=1;
  50. net.trainParam.lr=1;
  51. net.trainParam.epochs=50;
  52. net.trainParam.goal=0.001;
  53. %训练网络
  54. net=train(net,XX,YY);


  55. 程序二:适应值函数
  56. function [sol, val] = gabpEval(sol,options)
  57. % val - the fittness of this individual
  58. % sol - the individual, returned to allow for Lamarckian evolution
  59. % options - [current_generation]
  60. load data2
  61. nntwarn off
  62. XX=premnmx(XX);
  63. YY=premnmx(YY);
  64. P=XX;
  65. T=YY;
  66. R=size(P,1);
  67. S2=size(T,1);
  68. S1=25;%隐含层节点数
  69. S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
  70. for i=1:S,
  71.    x(i)=sol(i);
  72. end;
  73. [W1, B1, W2, B2, P, T, A1, A2, SE, val]=gadecod(x);

  74. 程序三:编解码函数
  75. function [W1, B1, W2, B2, P, T, A1, A2, SE, val]=gadecod(x)
  76. load data2
  77. nntwarn off
  78. XX=premnmx(XX);
  79. YY=premnmx(YY);
  80. P=XX;
  81. T=YY;
  82. R=size(P,1);
  83. S2=size(T,1);
  84. S1=25;%隐含层节点数
  85. S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
  86. % 前R*S1个编码为W1
  87. for i=1:S1,
  88.     for k=1:R,
  89.       W1(i,k)=x(R*(i-1)+k);
  90.     end
  91. end
  92. % 接着的S1*S2个编码(即第R*S1个后的编码)为W2
  93. for i=1:S2,
  94.    for k=1:S1,
  95.       W2(i,k)=x(S1*(i-1)+k+R*S1);
  96.    end
  97. end
  98. % 接着的S1个编码(即第R*S1+S1*S2个后的编码)为B1
  99. for i=1:S1,
  100.    B1(i,1)=x((R*S1+S1*S2)+i);
  101. end
  102. % 接着的S2个编码(即第R*S1+S1*S2+S1个后的编码)为B2
  103. for i=1:S2,
  104.    B2(i,1)=x((R*S1+S1*S2+S1)+i);
  105. end
  106. % 计算S1与S2层的输出
  107. A1=tansig(W1*P,B1);
  108. A2=purelin(W2*A1,B2);
  109. % 计算误差平方和
  110. SE=sumsqr(T-A2);
  111. val=1/SE; % 遗传算法的适应值
复制代码


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

来自:2nsoft.cn

评分

1

查看全部评分

回复
分享到:

使用道具 举报

发表于 2007-7-19 12:10 | 显示全部楼层
楼主辛苦了,多谢!
发表于 2007-8-31 08:35 | 显示全部楼层

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

请问frogfish,您能否上传initializega 函数的代码,我的是gads工具箱,没有这个函数。谢谢啦,在线等哦~
发表于 2007-8-31 09:40 | 显示全部楼层

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

发表于 2007-8-31 09:43 | 显示全部楼层

还有一个问题,见下:

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

Error in ==> GABPNET at 24
[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
谢谢解答!
发表于 2007-10-24 19:35 | 显示全部楼层

没人回吗?

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

Error in ==> GABPNET at 24
[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
谢谢解答!
发表于 2007-11-8 20:41 | 显示全部楼层
我用你那程序算出来的为什么没办法收敛呀
发表于 2008-3-12 20:25 | 显示全部楼层
to mcx8305::


[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
  'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2 gen 3]);

去掉那三个省略号!!:loveliness:
发表于 2008-3-14 12:01 | 显示全部楼层
每次结果都不完全一致,但误差都应该在合理的范围内.
发表于 2008-4-8 09:55 | 显示全部楼层
下载下来,好好的研究,可能对我的硕士论文很大的帮助!谢谢lz
发表于 2008-5-7 10:18 | 显示全部楼层
下载下来,好好的研究,感谢感谢....
发表于 2008-5-17 18:21 | 显示全部楼层
一点也不懂。新手该如何开始呢?在线等待指教:handshake
 楼主| 发表于 2008-5-21 10:45 | 显示全部楼层

  1. function [pop] = initializega(num, bounds, evalFN,evalOps,options)
  2. % function [pop]=initializega(populationSize, variableBounds,evalFN,
  3. %                           evalOps,options)
  4. %    initializega creates a matrix of random numbers with
  5. %    a number of rows equal to the populationSize and a number
  6. %    columns equal to the number of rows in bounds plus 1 for
  7. %    the f(x) value which is found by applying the evalFN.
  8. %    This is used by the ga to create the population if it
  9. %    is not supplied.
  10. %
  11. % pop            - the initial, evaluated, random population
  12. % populatoinSize - the size of the population, i.e. the number to create
  13. % variableBounds - a matrix which contains the bounds of each variable, i.e.
  14. %                  [var1_high var1_low; var2_high var2_low; ....]
  15. % evalFN         - the evaluation fn, usually the name of the .m file for
  16. %                  evaluation
  17. % evalOps        - any options to be passed to the eval function defaults []
  18. % options        - options to the initialize function, ie.
  19. %                  [type prec] where eps is the epsilon value
  20. %                  and the second option is 1 for float and 0 for binary,
  21. %                  prec is the precision of the variables defaults [1e-6 1]

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

  40. if nargin<5
  41.   options=[1e-6 1];
  42. end
  43. if nargin<4
  44.   evalOps=[];
  45. end

  46. if any(evalFN<48) %Not a .m file
  47.   if options(2)==1 %Float GA
  48.     estr=['x=pop(i,1); pop(i,xZomeLength)=', evalFN ';'];  
  49.   else %Binary GA
  50.     estr=['x=b2f(pop(i,:),bounds,bits); pop(i,xZomeLength)=', evalFN ';'];
  51.   end
  52. else %A .m file
  53.   if options(2)==1 %Float GA
  54.     estr=['[ pop(i,:) pop(i,xZomeLength)]=' evalFN '(pop(i,:),[0 evalOps]);'];
  55.   else %Binary GA
  56.     estr=['x=b2f(pop(i,:),bounds,bits);[x v]=' evalFN ...
  57.         '(x,[0 evalOps]); pop(i,:)=[f2b(x,bounds,bits) v];'];  
  58.     end
  59. end


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

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

  72. for i=1:num
  73.   eval(estr);
  74. end
复制代码
 楼主| 发表于 2008-5-21 10:47 | 显示全部楼层
原帖由 tianyoume 于 2008-3-14 12:01 发表
每次结果都不完全一致,但误差都应该在合理的范围内.


初始化每次都不是一样,这是必然的
 楼主| 发表于 2008-5-21 10:48 | 显示全部楼层
原帖由 xxzhao 于 2008-5-17 18:21 发表
一点也不懂。新手该如何开始呢?在线等待指教:handshake


这不动就无能为力了,自己去看看matlab吧
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-11-10 15:57 , Processed in 0.070059 second(s), 19 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表