Skip to content

Self adapter mutation #130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: master
Choose a base branch
from

Conversation

G3r4rd00
Copy link

@G3r4rd00 G3r4rd00 commented Feb 6, 2025

Fix net version error

@giacomelli
Copy link
Owner

I've looked at your code contribution and it looks like an interesting PR. Still, before I can properly review it, I need you to describe the purpose of the PR in the PR description, with a good explanation of the "SelfAdaptive" component and an example of usage.

@G3r4rd00
Copy link
Author

PR Description

This Pull Request introduces a self-adaptive approach for genetic algorithms in GeneticSharp. It adds the SelfAdaptive component, which allows mutation and crossover operators to dynamically adjust their parameters during evolution.

The goal of this enhancement is to eliminate the need for fixed hyperparameters and instead enable the algorithm to optimize its behavior at runtime, improving search efficiency and adaptability.

https://www.researchgate.net/publication/221418906_Self-adaptive_parameters_in_genetic_algorithms

Explanation of the "SelfAdaptive" Component

The SelfAdaptive approach allows genetic operators to modify their behavior based on the population's performance in each generation. For example:

SelfAdaptiveMutation adjusts its mutation rate depending on the genetic diversity present.
SelfAdaptiveCrossover dynamically changes its crossover probability based on evolutionary progress.

This allows the algorithm to adapt without manual intervention, reducing the need for empirical testing to find optimal hyperparameters.
Usage Example

The following code compares the SelfAdaptiveMutation operator in a Traveling Salesman Problem (TSP) scenario:


using System;
using System.Linq;
using GeneticSharp;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int numberOfCities = 20;
        var cities = GenerateRandomCities(numberOfCities);

        Console.WriteLine("Comparing SelfAdaptiveMutation in TSP...\n");

        var bestResult = RunGeneticAlgorithm(cities, 
            new SelfAdaptiveMutation(),
            new SelfAdaptiveCrossover(), 
            "Self Adaptive");

        Console.WriteLine("\nFinal results:");
        Console.WriteLine($"Self Adaptive -> Best distance: {bestResult}");
    }

    static double RunGeneticAlgorithm(List<Tuple<double, double>> cities, IMutation mutation, ICrossover crossover, string methodName)
    {
        var chromosome = new TspChromosome(cities.Count);
        var population = new Population(50, 500, chromosome);
        var fitness = new TspFitness(cities);
        var selection = new RouletteWheelSelection();

        var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
        {
            Termination = new GenerationNumberTermination(2000)
        };

        Console.WriteLine($"Running {methodName}...");
        ga.Start();

        var bestChromosome = ga.BestChromosome as TspChromosome;
        double bestFitness = fitness.Evaluate(bestChromosome);
        Console.WriteLine($"{methodName} -> Best distance found: {bestFitness}");
        Console.WriteLine($"{string.Join("-", bestChromosome.GetGenes().Select(g => Convert.ToInt32(g.Value)).ToArray())}");

        return bestFitness;
    }

    static List<Tuple<double, double>> GenerateRandomCities(int count)
    {
        var rnd = new Random();
        return Enumerable.Range(0, count)
                         .Select(_ => Tuple.Create(rnd.NextDouble() * 1000, rnd.NextDouble() * 1000))
                         .ToList();
    }
}

This code runs a genetic algorithm with SelfAdaptive operators to solve the traveling salesman problem. The operators automatically adjust their parameters based on evolutionary performance, optimizing the algorithm's efficiency.

With this description, you meet the PR requirements: explaining the purpose, detailing how SelfAdaptive works, and providing a clear usage example.

@giacomelli
Copy link
Owner

Ok, good description, even though it was generated with the help of AI, it is still valid. :D
I will review the code shortly.

Copy link
Owner

@giacomelli giacomelli left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also update the readme.md and add these new SelfAdaptiveChromosome, SelfAdaptiveCrossover and SelfAdaptiveMutation in the appropriate sections (follow the pattern of the other items listed there)

global.json Outdated
@@ -1,5 +1,5 @@
{
"sdk": {
"version": "6.0.400"
"version": "8"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The GeneticSharp is officially only supporting .NET 6, so it's not a good idea to change it here.

When I have some time available, I will make a PR to support .NET 9.

{
if (random.GetDouble() < adaptiveChromosome.GetMutationProbability(i))
{
// Mutación auto-adaptativa de la tasa de mutación
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, only English comments (even though I'm a native Portuguese speaker and can understand a little bit of Spanish, we need to keep all comments in English)

adaptiveChromosome.SetMutationProbability(i,p);
}

// Aplicar mutación al gen con la tasa adaptada
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here about the English comment only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants