How to take negative of the neural network function for maximization?

2 views (last 30 days)
I have created a neural network in matlab using the nntool and now I using the trained neural network as a fitness function for my genetic algorithm to maximize the output of my function given 3 input variables. Optimization in matlab is by default used for minimization but as i want to maximize my function i understand that I need to take negative of the function but I am not able to take a negative of the neural network function as we do for normal functions.

Answers (1)

Hornett
Hornett on 27 Sep 2024
To maximize the output of a neural network using a genetic algorithm (GA) in MATLAB, where optimization defaults to minimization, you can define a custom fitness function that negates the output of the neural network
Step 1: Define a Custom Fitness Function
Create a function that takes the inputs for your neural network, evaluates the network, and negates the output:
function negatedOutput = customFitnessFunction(inputs)
% Evaluate the neural network (assuming 'net' is your trained network)
nnOutput = net(inputs);
% Negate the output
negatedOutput = -nnOutput;
end
Step 2: Use the Custom Fitness Function in GA
Set up and run the genetic algorithm with your custom fitness function:
nVars = 3; % Number of input variables to the neural network
[x, fval] = ga(@customFitnessFunction, nVars);
This approach effectively transforms the maximization problem into a minimization problem suitable for MATLAB's GA function, allowing you to maximize the output of your neural network.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!