Ejemplo n.º 1
0
        public Problem Bat(Problem prob)
        {
            //default parameters
            int    populationSize = 5; //number of bats in the population
            int    maxGeneration  = 100;
            int    subsetSize     = 200;
            double loudness       = 0.5;
            double pulseRate      = 0.5;
            int    totalInstances = prob.X.Count(); //problem size
            double frequencyMin   = 0;              //minimum frequency. Frequency range determine the scalings
            double frequencyMax   = 2;              //maximum frequency.
            int    lowerBound     = -2;             //set lower bound - lower boundary
            int    upperBound     = 2;              //set upper bound - upper boundary

            double[] batFitnessVal                = new double[populationSize];
            double[] newbatFitnessVal             = new double[populationSize];
            double   globalBest                   = double.MinValue;
            ObjectInstanceSelection globalBestBat = null;
            Random r = new Random();

            //initialize population
            List <ObjectInstanceSelection> bats    = InitializeBat(populationSize, subsetSize, totalInstances, prob);
            List <ObjectInstanceSelection> newBats = new List <ObjectInstanceSelection>(bats.Count); //create a clone of bats

            bats.ForEach((item) =>
            {
                newBats.Add(new ObjectInstanceSelection(item.__Attribute_Values, item.__Attribute_Values_Continuous, item.__Frequency, item.__Velocity, item.__Pointers, item.__Fitness)); //create a clone of flowers
            });

            batFitnessVal    = fi.EvaluateObjectiveFunction(bats, prob);                                                           //evaluate fitness value for all the bats
            newbatFitnessVal = fi.EvaluateObjectiveFunction(newBats, prob);                                                        //evaluate fitness value for new bats. Note: this will be the same for this function call, since pollination has not occur
            BatFitness(batFitnessVal, bats);                                                                                       //fitness value for each bats
            BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
            globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
            globalBest    = globalBestBat.__Fitness;

            //start bat algorithm
            double rand = r.NextDouble(); //generate random number

            for (int i = 0; i < maxGeneration; i++)
            {
                //loop over all bats or solutions
                for (int j = 0; j < populationSize; j++)
                {
                    bats[j].__Frequency = frequencyMin + (frequencyMin - frequencyMax) * rand; //adjust frequency
                    for (int k = 0; k < subsetSize; k++)
                    {
                        double randNum = SimpleRNG.GetNormal();                                                                                                                             //generate random number with normal distribution
                        newBats[j].__Velocity[k] = bats[j].__Velocity[k] + (bats[j].__Attribute_Values_Continuous[k] - globalBestBat.Attribute_Values_Continuous[k]) * bats[j].__Frequency; //update velocity
                        newBats[j].__Attribute_Values_Continuous[k] = bats[j].__Attribute_Values_Continuous[k] + bats[j].__Velocity[k];                                                     //update bat position in continuous space
                        newBats[j].__Attribute_Values_Continuous[k] = SimpleBounds(newBats[j].__Attribute_Values_Continuous[k], lowerBound, upperBound);                                    //ensure that value does not go beyond defined boundary

                        if (rand > pulseRate)                                                                                                                                               //The factor 0.001 limits the step sizes of random walks
                        {
                            newBats[j].__Attribute_Values_Continuous[k] = globalBestBat.Attribute_Values_Continuous[k] + 0.001 * randNum;
                        }

                        newBats[j].__Attribute_Values[k] = fi.Binarize(newBats[j].__Attribute_Values_Continuous[k], r.NextDouble()); //convert to binary
                    }
                }

                //evaluate new solution
                newbatFitnessVal = fi.EvaluateObjectiveFunction(newBats, prob);                                                        //evaluate fitness value for all the bats
                BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
                globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
                globalBest    = globalBestBat.__Fitness;
            }

            //ensure that at least, 40 instances is selected for classification
            int countSelected = globalBestBat.__Attribute_Values.Count(q => q == 1); //count the total number of selected instances
            int diff, c = 0, d = 0;
            int Min = 40;                                                            //minimum number of selected instances

            if (countSelected < Min)
            {
                //if there are less than N, add N instances, where N = the number of selected instances
                diff = Min - countSelected;
                while (c < diff)
                {
                    if (globalBestBat.__Attribute_Values[d++] == 1)
                    {
                        continue;
                    }
                    else
                    {
                        globalBestBat.__Attribute_Values[d++] = 1;
                        c++;
                    }
                }
            }

            Problem subBest = fi.buildModel(globalBestBat, prob); //build model for the best Instance Mast

            return(subBest);
        }
Ejemplo n.º 2
0
        //flower pollination algorithm by Yang
        public Problem FlowerPollination(Problem prob)
        {
            int    nargin = 0, totalInstances = prob.X.Count(), maxGeneration = 500;
            int    numOfFlower       = 10;  //population size
            double probabilitySwitch = 0.8; //assign probability switch
            int    subsetSize        = 200; //dimension for each flower

            double[] flowerFitnessVal    = new double[numOfFlower];
            double[] newFlowerFitnessVal = new double[numOfFlower];
            FireflyInstanceSelection fw  = new FireflyInstanceSelection();
            double globalBest            = double.MinValue;
            double newBest = new double();
            ObjectInstanceSelection globalBestFlower = null;
            int lowerBound = -2; //set lower bound - lower boundary
            int upperBound = 2;  //set upper bound - upper boundary
            int maxIndex;

            //inittalize flowers, and get global best
            List <ObjectInstanceSelection> flowers    = InitializeFlower(numOfFlower, subsetSize, totalInstances, prob); //initialize solution
            List <ObjectInstanceSelection> newFlowers = new List <ObjectInstanceSelection>(flowers.Count);               //create a clone of flowers

            flowers.ForEach((item) =>
            {
                newFlowers.Add(new ObjectInstanceSelection(item.__Attribute_Values, item.__Attribute_Values_Continuous, item.__Pointers, item.__Fitness)); //create a clone of flowers
            });

            flowerFitnessVal    = fw.EvaluateObjectiveFunction(flowers, prob);                                                             //evaluate fitness value for all the flowers
            newFlowerFitnessVal = fw.EvaluateObjectiveFunction(newFlowers, prob);                                                          //evaluate fitness value for new flowers. Note: this will be the same for this function call, since pollination has not occur
            FlowerFitness(flowerFitnessVal, flowers);                                                                                      //fitness value for each flower
            FlowerFitness(newFlowerFitnessVal, newFlowers);                                                                                //fitness value for new flower
            globalBestFlower = EvaluateSolution(flowerFitnessVal, newFlowerFitnessVal, globalBest, flowers, newFlowers, globalBestFlower); //get the global best flower
            globalBest       = flowerFitnessVal.Max();

            //start flower algorithm
            Random r = new Random();

            double[] levy = new double[subsetSize];
            for (int i = 0; i < maxGeneration; i++)
            {
                double rand = r.NextDouble();
                if (rand > probabilitySwitch) //global pollination
                {
                    //global pollination
                    for (int j = 0; j < numOfFlower; j++)
                    {
                        levy = LevyFlight(subsetSize);
                        for (int k = 0; k < subsetSize; k++)
                        {
                            double A = levy[k] * (flowers[j].__Attribute_Values_Continuous[k] - globalBestFlower.__Attribute_Values_Continuous[k]);
                            double B = flowers[j].__Attribute_Values_Continuous[k] + A;
                            A = SimpleBounds(B, lowerBound, upperBound);                                     //ensure that value does not go beyond defined boundary
                            newFlowers[j].__Attribute_Values_Continuous[k] = A;
                            newFlowers[j].__Attribute_Values[k]            = fw.Binarize(B, r.NextDouble()); //convert to binary
                        }
                    }
                }
                else //local pollination
                {
                    for (int j = 0; j < numOfFlower; j++)
                    {
                        List <int> randNum = Training.GetRandomNumbers(2, numOfFlower); //generate 2 distinct random numbers
                        double     epsilon = rand;

                        //local pollination
                        for (int k = 0; k < subsetSize; k++)
                        {
                            double A = flowers[j].__Attribute_Values_Continuous[k] + epsilon * (flowers[randNum[0]].__Attribute_Values_Continuous[k] - flowers[randNum[1]].__Attribute_Values_Continuous[k]); //randomly select two flowers from neighbourhood for pollination
                            A = SimpleBounds(A, lowerBound, upperBound);                                                                                                                                      //ensure that value does not exceed defined boundary
                            newFlowers[j].__Attribute_Values_Continuous[k] = A;                                                                                                                               //save computation
                            newFlowers[j].__Attribute_Values[k]            = fw.Binarize(A, r.NextDouble());                                                                                                  //convert to binary
                        }
                    }
                }

                //evaluate new solution
                newFlowerFitnessVal = fw.EvaluateObjectiveFunction(newFlowers, prob);                                                          //evaluate fitness value for all the flowers
                FlowerFitness(newFlowerFitnessVal, newFlowers);                                                                                //fitness value for new flower
                globalBestFlower = EvaluateSolution(flowerFitnessVal, newFlowerFitnessVal, globalBest, flowers, newFlowers, globalBestFlower); //Evaluate solution, update better solution and get global best flower
                globalBest       = flowerFitnessVal.Max();
            }

            //ensure that at least, 40 instances is selected for classification
            int countSelected = globalBestFlower.__Attribute_Values.Count(q => q == 1); //count the total number of selected instances
            int diff, c = 0, d = 0;
            int Min = 40;                                                               //minimum number of selected instances

            if (countSelected < Min)
            {
                //if there are less than N, add N instances, where N = the number of selected instances
                diff = Min - countSelected;
                while (c < diff)
                {
                    if (globalBestFlower.__Attribute_Values[d++] == 1)
                    {
                        continue;
                    }
                    else
                    {
                        globalBestFlower.__Attribute_Values[d++] = 1;
                        c++;
                    }
                }
            }

            Problem subBest = fw.buildModel(globalBestFlower, prob); //build model for the best Instance Mast

            return(subBest);
        }
        /// <summary>
        /// Evaluate Objective Function
        /// </summary>
        public double[] EvaluateObjectiveFunction(List <ObjectInstanceSelection> Spiders, Problem prob)
        {
            int NB  = Spiders.Count;                                 //NF -> number of spiders
            int tNI = Spiders.ElementAt(0).Attribute_Values.Count(); //size of each Instance Mask

            double[] fitness = new double[NB];
            int      sum;


            List <double> y = new List <double>();
            List <Node[]> x = new List <Node[]>();

            double C, Gamma;

            for (int i = 0; i < NB; i++)
            {
                //building model for each instance in instance mask in each spider object
                Problem subProb = fi.buildModel(Spiders.ElementAt(i), prob);

                Parameter param = new Parameter();
                if (subProb != null)
                {
                    int countP = subProb.Y.Count(k => k == 1);  //counting the total number of positive instance in the subpeoblem
                    int countN = subProb.Y.Count(k => k == -1); //counting the total number of negative instance in the subproblem

                    if (countN <= 1 || countP <= 1)             //ensuring that there are at least two positive or negative instance in a subproblem
                    {
                        int m = 0;
                        if (countN <= 1)
                        {
                            for (int k = 0; k < prob.Count; k++) //if no negative instance, search the whole subproblem and insert two postive instance in the first and second position of subproblem
                            {
                                if (prob.Y[k] == -1)
                                {
                                    subProb.X[m] = prob.X[k]; //insert negative instance in the first and second position
                                    subProb.Y[m] = prob.Y[k]; //insert label
                                    m++;
                                }
                                if (m == 2)
                                {
                                    break;
                                }
                            }
                        }
                        else if (countP <= 1)
                        {
                            for (int k = 0; k < prob.Count; k++) //if no positive instance, search the whole subproblem and insert two postive instance in the first and second position of subproblem
                            {
                                if (prob.Y[k] == 1)
                                {
                                    subProb.X[m] = prob.X[k]; //insert negative instance in the first and second position
                                    subProb.Y[m] = prob.Y[k]; //insert label
                                    m++;
                                }
                                if (m == 2)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    Problem subP                  = Training.ClusteringBoundaryInstance(subProb);
                    int     count                 = Spiders.ElementAt(i).__Attribute_Values.Count(q => q == 1); //total number of selected instances, to be used for subsetSize
                    double  perRedBInstances      = (double)(subProb.Count / subP.Count);                       //percentage reduction for boundary instances
                    double  perRedSpiderInstances = (double)(tNI - count) / tNI;                                //percentage reduction for flower instances
                    fitness[i] = (100 * perRedSpiderInstances) + perRedBInstances;
                }
            }

            return(fitness);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Evaluate Objective Function
        /// </summary>
        //public double[] EvaluateObjectiveFunction(List<ObjectInstanceSelection> fireflies, List<double> accuracy, Problem prob)
        public double[] EvaluateObjectiveFunction(List <ObjectInstanceSelection> Cuckoos, Problem prob)
        {
            int NF  = Cuckoos.Count;                                 //NF -> number of fireflies
            int tNI = Cuckoos.ElementAt(0).Attribute_Values.Count(); //size of each Instance Mask

            double[] fitness = new double[NF];
            int      sum;

            List <double> classes = fi.getClassLabels(prob.Y); //get the class labels
            int           nClass  = classes.Count;

            List <double> y = new List <double>();
            List <Node[]> x = new List <Node[]>();

            double C, Gamma;

            for (int i = 0; i < NF; i++)
            {
                //building model for each instance in instance mask in each firefly object
                Problem subProb = fi.buildModel(Cuckoos.ElementAt(i), prob);

                Parameter param = new Parameter();
                if (subProb != null)
                {
                    if (nClass == 2)
                    {
                        int countP = subProb.Y.Count(k => k == 1);  //counting the total number of positive instance in the subpeoblem
                        int countN = subProb.Y.Count(k => k == -1); //counting the total number of negative instance in the subproblem

                        if (countN <= 1 || countP <= 1)             //ensuring that there are at least two positive or negative instance in a subproblem
                        {
                            int m = 0;
                            if (countN <= 1)
                            {
                                for (int k = 0; k < prob.Count; k++) //if no negative instance, search the whole subproblem and insert two postive instance in the first and second position of subproblem
                                {
                                    if (prob.Y[k] == -1)
                                    {
                                        subProb.X[m] = prob.X[k]; //insert negative instance in the first and second position
                                        subProb.Y[m] = prob.Y[k]; //insert label
                                        m++;
                                    }
                                    if (m == 2)
                                    {
                                        break;
                                    }
                                }
                            }
                            else if (countP <= 1)
                            {
                                for (int k = 0; k < prob.Count; k++) //if no positive instance, search the whole subproblem and insert two postive instance in the first and second position of subproblem
                                {
                                    if (prob.Y[k] == 1)
                                    {
                                        subProb.X[m] = prob.X[k]; //insert negative instance in the first and second position
                                        subProb.Y[m] = prob.Y[k]; //insert label
                                        m++;
                                    }
                                    if (m == 2)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    Problem subP = Training.ClusteringBoundaryInstance(subProb);
                    //int subProbCount = subP.Count; //number of selected boundary instances
                    int count = Cuckoos.ElementAt(i).__Attribute_Values.Count(q => q == 1); //total number of selected instances, to be used for subsetSize
                    //double percentageReduction = 100 * (tNI - count) / tNI; //calculating percentage reduction for each instance Mask
                    //double perRedBnstances = (double)(subProb.Count - subProbCount) / subProb.Count; //percentage reduction for boundary instances
                    //double perRedBInstances = (double)(subProb.Count - subP.Count) * subP.Count; //percentage reduction for boundary instances
                    double perRedBInstances      = (double)(subProb.Count / subP.Count); //percentage reduction for boundary instances
                    double perRedCuckooInstances = (double)(tNI - count) / tNI;          //percentage reduction for cuckoo instances

                    //fitness[i] = perRedCuckooInstances * 100;
                    fitness[i] = (100 * perRedCuckooInstances) + perRedBInstances;
                    //fitness[i] = 100 * ((double)count / (double)tNI);
                    //fitness[i] = 100 * perRedBnstances;
                    //fitness[i] = 100 * (perRedBnstances + perRedCuckooInstances);
                    //fitness[i] = (W_SeelctedBoundaryInstances * subProbCount) + (W_Instances * ((tNI - count) / tNI));
                    //fitness[i] = percentageReduction;
                }
            }

            return(fitness);
        }