Computing fitness

The next block of code that we should look at is how we calculate our solution. Our main loop calls our fitness function as follows:

Statistics.Compute();

Now let's dive into the Fitness function. For ease, we have placed the entire function in the following snippet. We will dissect each line relative to its importance in the function. Our ultimate objective here is to compute the meta-fitness measure by passing the parameters to our optimizer. We perform optimization runs on the array of problem(s) until the fitness exceeds the fitnessLimit parameter:

public override double Fitness(double[] parameters, double fitnessLimit)
{
double fitnessSum = 0;
// Iterate over the problems.
for (int i = 0; i < ProblemIndex.Count && fitnessSum<fitnessLimit; i++)
{
// Assign the problem to the optimizer.
Optimizer.Problem = ProblemIndex.GetProblem(i);
// Get the weight associated with this problem.
double weight = ProblemIndex.GetWeight(i);
// Use another fitness summation because we need to keep
// track of the performance on each problem.
double fitnessSumInner = 0;
// Perform a number of optimization runs.
for (int j = 0; j < NumRuns && fitnessSum < fitnessLimit; j++)
{
// Perform one optimization run on the problem.
Result result = Optimizer.Optimize(parameters, fitnessLimit -fitnessSum);
// Get the best fitness result from optimization and adjust it
// by subtracting its minimum possible value.
double fitness = result.Fitness;
double fitnessAdjusted = fitness - Optimizer.MinFitness;
// Ensure adjusted fitness is non-negative, otherwise Preemptive
// Fitness Evaluation does not work.
Debug.Assert(fitnessAdjusted >= 0);
// Apply weight to the adjusted fitness.
fitnessAdjusted *= weight;
// Accumulate both fitness sums.
fitnessSumInner += fitnessAdjusted;
fitnessSum += fitnessAdjusted;
}
// Set the fitness result achieved on the problem.
// This was why we needed an extra summation variable.
ProblemIndex.SetFitness(i, fitnessSumInner);
}
// Sort the optimization problems so that the worst
// performing will be attempted optimized first, when
// this method is called again.
ProblemIndex.Sort();
return fitnessSum;
}

Now let's look at our code in action, as shown in the following screenshot:

As you can see, the goal of the program is to output the most optimal parameters so that you can tune your network using the same function optimization.

But what can you do if you have a function that is not one of those included in SwarmOps? Luckily, you can define a custom problem of your own and use it. Let's take a look at how that's used. First, let's look at the TestCustomProblem project, as shown in the following screenshot:

TestCustomProblem Project
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset