How to include a DNN in a Genetic Algorithm searched function

2 Ansichten (letzte 30 Tage)
Cheng Qiu
Cheng Qiu am 26 Nov. 2021
Hello MathWorks Team, I want to use GA to search best input of a certain function so that the functions output could meet the desired value.
So I create a function to calculate the loss between actual output and desired value. Then I called GA to evaluate the function.Below is my loss function with a dummy function.
function Loss = ForwardPredictionLoss(SPratio,nref)
AA = reshape(nref,4,7);
A = AA*ones(7,4); % ones(7,4) is just some dummy function for test
B = SPratio;
err = (A-B).^2;
Loss = sqrt(sum(sum(err)));
end
and my main script using GA for function input searching:
SPratio = diag(ones(1,4));
nref = ones(28,1);
lb = -ones(28,1);
ub = -lb;
Options = optimoptions(@ga,'PopulationSize',25,'MaxGenerations',20);
[x,fval] = ga(@(nref)ForwardPredictionLoss1(SPratio,nref,FWNnet),28,[],[],[],[],lb,ub,[],Options);
So far, everything goes well. However when i tried to replaced the dummy function with a fixed DNN. I always get some error. Here is my code:
function Loss = ForwardPredictionLoss1(SPratio,nref,FWNnet)
nref1 = nref;
A1 = predict(FWNnet,nref1);
A2 = predict(FWNnet,nref1);
A3 = predict(FWNnet,nref1);
A4 = predict(FWNnet,nref1);
A = [A1 A2 A3 A4];
B = SPratio;
err = (A-B).^2;
Loss = sqrt(sum(sum(err)));
end
clc;clear; close all
load FWN
FWNnet = net;
SPratio = diag(ones(1,4));
nref = ones(32,1);
lb = -ones(32,1);
ub = -lb;
Options = optimoptions(@ga,'PopulationSize',25,'MaxGenerations',20);
[x,fval] = ga(@(nref)ForwardPredictionLoss1(SPratio,nref,FWNnet),32,[],[],[],[],lb,ub,[],Options);
Could you please share the right code for this.
Thanks so much.

Antworten (0)

Produkte


Version

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by