程序一:GA训练BP权值的主函数
function net=GABPNET(XX,YY)
%--------------------------------------------------------------------------
% GABPNET.m
% 使用遗传算法对BP网络权值阈值进行优化,再用BP算法训练网络
%--------------------------------------------------------------------------
%数据归一化预处理
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
%创建网络
net=newff(minmax(XX),[19,25,1],{'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
[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2 gen 3]);
%绘收敛曲线图
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网络
[W1,B1,W2,B2,P,T,A1,A2,SE,val]=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);