Good day, everyone.

I am trying to create an artificial neural network with Matlab and then optimize it with the genetic algorithm. After training the network, I saved it and created the following two script files.

function fitness = fitnessFunction(x, trainedNetwork)

% Check input values

net = trainedNetwork;

if any(x < -1) || any(x > 1)

error('Input values must be between -1 and +1.');

end

try

outputs = net(x'); % use net instead of trainedNetwork

fitness = -sum(outputs); % Negative sign, since the genetic algorithm thinks it is looking for a minimum

catch ME

rethrow(ME);

end

end

%Install trainedNetwork

load('trainedNetwork.mat', 'trainedNetwork'); % Load the file where the trainedNetwork variable is saved

inputSize = 3;

% Set genetic algorithm settings

% Set lower and upper limits (between -1 and +1)

lb = -ones(1, inputSize); % Lower limit

ub = ones(1, inputSize); % Upper limit

options = optimoptions('ga', 'Display', 'iter', 'PopulationSize', 100, 'MaxGenerations', 50);

% Run the genetic algorithm

[x, fval] = ga(@(x) fitnessFunction(x, trainedNetwork), inputSize, [], [], [], [], [], lb, ub, [], options);

% Best solution and fitness value

bestInputs = x;

bestFitness = -fval; % We return it because we have marked it negative

% Calculate outputs corresponding to the best inputs

bestOutputs = trainedNetwork(bestInputs');

disp('Best inputs:');

disp(bestInputs);

disp('The highest outputs corresponding to these inputs:');

disp(bestOutputs);

When I run the second script, I get the following error.

Array indices must be positive integers or logical values.

Error in fitnessFunction (line 8)

outputs = trainedNetwork(x');

I would be very grateful if you can help me.

Similar questions and discussions