giacomelli / GeneticSharp

GeneticSharp is a fast, extensible, multi-platform and multithreading C# Genetic Algorithm library that simplifies the development of applications using Genetic Algorithms (GAs).
MIT License
1.27k stars 332 forks source link

How to set Fitness function #52

Closed AlexeyGITb closed 5 years ago

AlexeyGITb commented 5 years ago

have a problem figuring out how to set my function. It should be pretty easy but i am new to GA and espectially to GeneticSharp. So i need to set and optimize this function: -(16 x x - 24 x + 5) Math.Exp(-x) with scope from 1.9 to 3.9, thats all. But right now it runs only once and i think i did something wrong. Thank you in advance! `namespace ConsoleApp1 { class MainClass { public static void Main(string[] args) {

        var chromosome = new FloatingPointChromosome(1.9, 3.9, 3);

        var population = new Population(50, 100, chromosome);

        var fitness = new FuncFitness((c) =>
        {
            var fc = c as FloatingPointChromosome;
            var values = fc.ToFloatingPoints();
            var x = values[0];
            return -(16 * x * x - 24 * x + 5) * Math.Exp(-x);
        });

        var selection = new TournamentSelection();
        var crossover = new UniformCrossover();
        var mutation = new TworsMutation();
        var termination = new GenerationNumberTermination(100);

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

        Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");

        var latestFitness = 0.0;

        ga.GenerationRan += (sender, e) =>
        {
            var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
            var bestFitness = bestChromosome.Fitness.Value;

            if (bestFitness != latestFitness)
            {
                latestFitness = bestFitness;
                var phenotype = bestChromosome.ToFloatingPoints();

                Console.WriteLine(phenotype[0]); Console.WriteLine(bestFitness);

            }
        };

        ga.Start();

        Console.ReadKey();
    }
}

}`

longbiscuit commented 3 years ago

i also can't get better fittness,why: `using GeneticSharp.Domain; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Crossovers; using GeneticSharp.Domain.Fitnesses; using GeneticSharp.Domain.Mutations; using GeneticSharp.Domain.Populations; using GeneticSharp.Domain.Selections; using GeneticSharp.Domain.Terminations; using GeneticSharp.Infrastructure.Framework.Threading; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //https://diegogiacomelli.com.br/function-optimization-with-geneticsharp/ //多线程 https://github.com/giacomelli/GeneticSharp/wiki/multithreading namespace ConsoleApp1GeneticSharp { class Program {

    static void Main(string[] args)
    {
        #region example 1
        // https://www.nuget.org/packages/GeneticSharp/
        //https://stackoverflow.com/questions/59191025/optimization-of-an-equation-parameters-using-genetic-sharp-genetic-algorithm
        //x = 1, 2, 3, 4, 5
        //y = 5, 4, 3, 2, 1
        //z = 1, 2, 1, 1, 3
        //t = 9, 12, 9, 9, 15.
        // t=ax+by+c*z. here i know a=1,b=1 and c=3
        double[] x = new double[] { 1, 2, 3, 4, 5 };
        double[] y = new double[] { 5, 4, 3, 2, 1 };
        double[] z = new double[] { 1, 2, 1, 1, 3 };
        double[] t = new double[] { 9, 12, 9, 9, 15 };

        var chromosome = new FloatingPointChromosome(
        new double[] { 0.0, 0.0, 0.0 },//各参数最小值
        new double[] { 10.0, 10.0, 10.0 },//各参数最大值
        //new double[] { 1, 1, 3 },//各参数最小值
        //new double[] { 1, 1, 3 },//各参数最大值
        new int[] { 64, 64, 64 },//用于表示上述参数值的2进制位数
        new int[] { 3, 3, 3 });//参数的十进制形式小数位数

        //https://github.com/giacomelli/GeneticSharp/issues/4
        var population = new Population(100, 100, chromosome);//select the % of individuals who will survive in each generation

        var fitness = new FuncFitness((c) =>
        {
            var fc = c as FloatingPointChromosome;
            double err = 0;
            var values = fc.ToFloatingPoints();
            var pa = values[0];
            var pb = values[1];
            var pc = values[2];
            for (int i = 0; i < x.Count(); i++)
            {
                err -= Math.Pow((t[i] - (pa * x[i] + pb * y[i] + pc * z[i])), 2);
            }
            return err;
        });

        //给定三大算子
        var selection = new TournamentSelection();// Elite, Roulete Wheel, Stochastic Universal Sampling and Tournament. //https://diegogiacomelli.com.br/function-optimization-with-geneticsharp/
        var crossover = new TwoPointCrossover();//https://github.com/giacomelli/GeneticSharp/wiki/crossovers
        var mutation = new FlipBitMutation();//https://github.com/giacomelli/GeneticSharp/wiki/mutations

        //多线程
        var taskExecutor = new ParallelTaskExecutor();//多线程
        taskExecutor.MinThreads = 2;//多线程
        taskExecutor.MaxThreads = 2;//多线程
        var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
        ga.TaskExecutor = taskExecutor;//多线程

        //var termination = new FitnessStagnationTermination(1000);
        //ga.Termination = termination;

        //ga.Termination = new GenerationNumberTermination(3000);

        ga.Termination = new OrTermination(
           new GenerationNumberTermination(5000), //执行到多少代必须停止
           new FitnessStagnationTermination(2000));//目标函数多少代不再变化就停止

        ga.MutationProbability = 0.05f;
        ga.CrossoverProbability = 0.85f;

        Console.WriteLine("GA running...");

        var latestFitness = 0.0;

        ga.GenerationRan += (sender, e) =>
        {
            var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
            var bestFitness = bestChromosome.Fitness.Value;

            if (bestFitness != latestFitness)
            {
                latestFitness = bestFitness;
                var phenotype = bestChromosome.ToFloatingPoints();

                Console.WriteLine(
                    "Generation {0}:  {1},{2},{3} = {4}",
                    ga.GenerationsNumber,
                    phenotype[0],
                    phenotype[1],
                    phenotype[2],
                    bestFitness
                );
            }
        };

        ga.Start();

        Console.WriteLine("GA ending...");

        Console.ReadKey();

        #endregion example 1

        //#region example 2

        //float maxWidth = 998f;
        //float maxHeight = 680f;

        //var chromosome = new FloatingPointChromosome(
        //    new double[] { 0, 0, 0, 0 },
        //    new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
        //    new int[] { 10, 10, 10, 10 },
        //    new int[] { 0, 0, 0, 0 });

        //var population = new Population(100, 100, chromosome);

        //var fitness = new FuncFitness((c) =>
        //{
        //    var fc = c as FloatingPointChromosome;

        //    var values = fc.ToFloatingPoints();
        //    var x1 = values[0];
        //    var y1 = values[1];
        //    var x2 = values[2];
        //    var y2 = values[3];

        //    return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
        //});

        //var selection = new EliteSelection();
        //var crossover = new UniformCrossover(0.5f);
        //var mutation = new FlipBitMutation();
        //var termination = new FitnessStagnationTermination(100);

        //var ga = new GeneticAlgorithm(
        //    population,
        //    fitness,
        //    selection,
        //    crossover,
        //    mutation);

        //ga.Termination = termination;

        //Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");

        //var latestFitness = 0.0;

        //ga.GenerationRan += (sender, e) =>
        //{
        //    var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
        //    var bestFitness = bestChromosome.Fitness.Value;

        //    if (bestFitness != latestFitness)
        //    {
        //        latestFitness = bestFitness;
        //        var phenotype = bestChromosome.ToFloatingPoints();

        //        Console.WriteLine(
        //            "Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
        //            ga.GenerationsNumber,
        //            phenotype[0],
        //            phenotype[1],
        //            phenotype[2],
        //            phenotype[3],
        //            bestFitness
        //        );
        //    }
        //};

        //ga.Start();

        //Console.ReadKey();

        //#endregion example 2

    }
}

} `