matlab使用神经网络工具箱和全局优化工具箱编写粒子群优化的BPNN
时间: 2023-10-30 17:07:27 浏览: 105
这里给出一个使用MATLAB神经网络工具箱和全局优化工具箱编写粒子群优化的BPNN的示例代码。
首先,我们需要导入数据,并将其分为训练集和测试集。
```
load iris_dataset.mat
inputs = irisInputs;
targets = irisTargets;
[trainInd,valInd,testInd] = dividerand(size(inputs,2),0.6,0,0.4);
trainInputs = inputs(:,trainInd);
trainTargets = targets(:,trainInd);
testInputs = inputs(:,testInd);
testTargets = targets(:,testInd);
```
然后,我们定义神经网络的结构和参数,并将其作为一个函数传递给全局优化工具箱(Particle Swarm Optimization Toolbox)。
```
net = feedforwardnet([5 3]);
net.trainParam.showWindow = 0;
net.trainParam.showCommandLine = 0;
net.trainParam.show = NaN;
net.trainParam.epochs = 100;
net.trainParam.goal = 0;
net.divideFcn = 'divideind';
net.divideParam.trainInd = 1:size(trainInputs,2);
net.divideParam.valInd = [];
net.divideParam.testInd = [];
net.performFcn = 'mse';
net.layers{2}.transferFcn = 'logsig';
fitnessFunc = @(x) train_bpnn(x, net, trainInputs, trainTargets);
```
在fitnessFunc函数中,我们将粒子群优化算法所需要的参数x传递给神经网络的训练函数train_bpnn,计算出训练误差作为适应度函数返回。
```
function fitness = train_bpnn(x, net, inputs, targets)
net = setwb(net,x);
net = train(net,inputs,targets);
outputs = net(inputs);
fitness = mse(net,targets,outputs);
end
```
最后,我们调用全局优化函数进行训练,并使用测试集进行评估。
```
options = optimoptions('particleswarm','SwarmSize',100);
[x, fval, exitflag] = particleswarm(fitnessFunc,net.numWeightElements,[],[],options);
net = setwb(net,x);
outputs = net(testInputs);
errors = gsubtract(testTargets,outputs);
mseError = mse(net,testTargets,outputs);
```
完整代码如下:
```
load iris_dataset.mat
inputs = irisInputs;
targets = irisTargets;
[trainInd,valInd,testInd] = dividerand(size(inputs,2),0.6,0,0.4);
trainInputs = inputs(:,trainInd);
trainTargets = targets(:,trainInd);
testInputs = inputs(:,testInd);
testTargets = targets(:,testInd);
net = feedforwardnet([5 3]);
net.trainParam.showWindow = 0;
net.trainParam.showCommandLine = 0;
net.trainParam.show = NaN;
net.trainParam.epochs = 100;
net.trainParam.goal = 0;
net.divideFcn = 'divideind';
net.divideParam.trainInd = 1:size(trainInputs,2);
net.divideParam.valInd = [];
net.divideParam.testInd = [];
net.performFcn = 'mse';
net.layers{2}.transferFcn = 'logsig';
fitnessFunc = @(x) train_bpnn(x, net, trainInputs, trainTargets);
function fitness = train_bpnn(x, net, inputs, targets)
net = setwb(net,x);
net = train(net,inputs,targets);
outputs = net(inputs);
fitness = mse(net,targets,outputs);
end
options = optimoptions('particleswarm','SwarmSize',100);
[x, fval, exitflag] = particleswarm(fitnessFunc,net.numWeightElements,[],[],options);
net = setwb(net,x);
outputs = net(testInputs);
errors = gsubtract(testTargets,outputs);
mseError = mse(net,testTargets,outputs);
```
阅读全文