遗传算法GA优化BPNN

x_train = x(1:100,:);
y_train = y(1:100,:);
x_test = x(101:end,:);
y_test = y(101:end,:);

%数据归一化
[train_input,inputps] = mapminmax(x_train’);
[train_output,outputps] = mapminmax(y_train’);

%节点设置
inputnum = size(x,2);
hiddennum = 6;
outputnum = 1;

%初始化
length = inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum; %优化参数个数
bounds = ones(length,1)*[-1,1];                                      %参数取值范围[-1,1]
sizepop = 20;
param = rand(sizepop,length);

net = newff(train_input,train_output,hiddennum);
for i = 1:sizepop
    fit(i,:) = func(param(i,:),inputnum,hiddennum,outputnum,net,train_input,train_output);
end
initPop = [param,fit];

%GA寻优
bestparam = ga(bounds,’gaEval’,[],initPop);
bestparam = bestparam(1:length);               %最后一个数值为适应度

%建立模型并预测
w1 = bestparam(1:inputnum*hiddennum);
b1 = bestparam(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);
w2 = bestparam(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum);
b2 = bestparam(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum);

net.iw{1,1} = reshape(w1,hiddennum,inputnum);
net.lw{2,1} = reshape(w2,outputnum,hiddennum);
net.b{1} = reshape(b1,hiddennum,1);
net.b{2} = b2;

net.trainParam.epochs = 100;
net.trainParam.lr=0.1;
net.trainParam.goal=0.00001;

net = train(net,train_input,train_output);
input_test = mapminmax(‘apply’,x_test’,inputps);
predict_test = sim(net,input_test);
predict_test = mapminmax(‘reverse’,predict_test,outputps);
RD = (predict_test-y_test’)./y_test’;
disp(‘相对偏差如下:’)
disp(RD)
RMSE = sqrt(sum((predict_test-y_test’).^2)/7);
disp([‘RMSE = ‘,num2str(RMSE)])

%结果可视化
figure(1)
plot(predict_test,’-b’)
hold on
plot(y_test,’–r’)
legend(‘预测输出’,’期望输出’)

    原文作者:遗传算法
    原文地址: https://blog.csdn.net/qq_42394743/article/details/81916151
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞