コード例 #1
0
ファイル: MonkeyST.cs プロジェクト: CDMMKY/fuzzy_core
        public override SAFuzzySystem TuneUpFuzzySystem(SAFuzzySystem Classifier, ILearnAlgorithmConf conf)
        {
            Init(conf);
            KnowlegeBaseSARules temp_c_Rule = new KnowlegeBaseSARules(Classifier.RulesDatabaseSet[0]);
            SAFuzzySystem       result      = Classifier;

            for (int t = 0; t < population_count; t++)
            {
                monkey[t] = new KnowlegeBaseSARules(result.RulesDatabaseSet[0]);
                for (int k = 0; k < result.RulesDatabaseSet[0].TermsSet.Count; k++)
                {
                    for (int q = 0; q < result.RulesDatabaseSet[0].TermsSet[k].CountParams; q++)
                    {
                        //monkey[t].TermsSet[k].Parametrs[q] = StaticRandom.NextDouble() * (result.RulesDatabaseSet[0].TermsSet[k].Max - result.RulesDatabaseSet[0].TermsSet[k].Min);
                        monkey[t].TermsSet[k].Parametrs[q] = GaussRandom.Random_gaussian(rand, monkey[t].TermsSet[k].Parametrs[q], monkey[t].TermsSet[k].Parametrs[q] * 0.05);
                    }
                }

                result.UnlaidProtectionFix(monkey[t]);

                // delete
                testvals[t] = result.ErrorLearnSamples(monkey[t]);
                Console.WriteLine("Begin: " + t.ToString() + " " + iter.ToString() + " " + testvals[t].ToString());
            }
            bestsolution       = new KnowlegeBaseSARules(monkey.SelectBest(result, 1)[0]);
            bestsolutionnumber = result.ErrorLearnSamples(bestsolution);

            iter_amount = somersault_iter * (1 + jump_iter * (1 + crawl_iter));
            deltaLength = result.RulesDatabaseSet[0].TermsSet.Sum(x => x.Parametrs.Length);
            for (int r = 0; r < somersault_iter; r++)
            {
                for (int t = 0; t < jump_iter; t++)
                {
                    for (int e = 0; e < crawl_iter; e++)
                    {
                        iter++;
                        CheckForBest(result);
                        oneClimb(result, deltaLength, step);
                        //Console.WriteLine(iter_amount.ToString() + "/" + iter.ToString());
                    }
                    iter++;
                    oneWatchJump(result);
                    //Console.WriteLine(iter_amount.ToString() + "/" + iter.ToString());
                }
                iter++;
                oneGlobalJump(result);
                Console.WriteLine(iter_amount.ToString() + "/" + iter.ToString());
            }

            /*  for (int t = 0; t < population_count; t++)
             *    if (result.ErrorLearnSamples(monkey[best]) < result.ErrorLearnSamples(monkey[t]))
             *        best = t; */
            CheckForBest(result);
            if (bestsolutionnumber < result.ErrorLearnSamples(result.RulesDatabaseSet[0]))
            {
                result.RulesDatabaseSet[0] = bestsolution;
            }
            iter = 0;
            return(result);
        }
コード例 #2
0
ファイル: SSOApprox.cs プロジェクト: CDMMKY/fuzzy_core
        private void SetPopulation()
        {
            Population = new KnowlegeBaseSARules[numberOfAllParts];
            KnowlegeBaseSARules TempRule = new KnowlegeBaseSARules(result.RulesDatabaseSet[0]);

            Population[0] = TempRule;
            Universal     = TempRule;
            for (int i = 1; i < numberOfAllParts; i++)
            {
                Population[i] = new KnowlegeBaseSARules(TempRule);
                for (int j = 0; j < Population[i].TermsSet.Count; j++)
                {
                    for (int k = 0; k < Population[i].TermsSet[j].Parametrs.Length; k++)
                    {
                        Population[i].TermsSet[j].Parametrs[k] = GaussRandom.Random_gaussian(rand, Population[i].TermsSet[j].Parametrs[k], 0.1 * Population[i].TermsSet[j].Parametrs[k]);
                    }
                }
                result.UnlaidProtectionFix(Population[i]);
            }
            Universal = new KnowlegeBaseSARules(TempRule);
            for (int i = 0; i < Universal.TermsSet.Count; i++)
            {
                Population[i] = new KnowlegeBaseSARules(TempRule);
                for (int j = 0; j < Universal.TermsSet[i].Parametrs.Length; j++)
                {
                    Universal.TermsSet[i].Parametrs[j] = GaussRandom.Random_gaussian(rand, Universal.TermsSet[i].Parametrs[j], 0.1 * Universal.TermsSet[i].Parametrs[j]);
                }
            }
        }
コード例 #3
0
        public override SAFuzzySystem Generate(FuzzySystem.SingletoneApproximate.SAFuzzySystem Approximate, IGeneratorConf config)
        {
            start_add_rules = Approximate.RulesDatabaseSet.Count;
            SAFuzzySystem result = Approximate;

            if (result.RulesDatabaseSet.Count == 0)
            {
                AbstractNotSafeGenerator tempGen = new GeneratorRulesEveryoneWithEveryone();
                result = tempGen.Generate(result, config);

                GC.Collect();
            }



            Request_count_rules = ((RullesShrinkConf)config).RSCCountRules;
            max_count_rules     = ((RullesShrinkConf)config).RSCMaxRules;
            count_slices        = ((RullesShrinkConf)config).IEWECountSlice;
            min_count_rules     = ((RullesShrinkConf)config).RSCMinRules;
            type_term           = ((RullesShrinkConf)config).IEWEFuncType;

            int         count_of_swith_off    = ((RullesShrinkConf)config).RSCMaxRules - Request_count_rules;
            List <byte> Varians_of_run_system = new List <byte>();

            for (int i = 0; i < Approximate.RulesDatabaseSet[0].RulesDatabase.Count; i++)
            {
                Varians_of_run_system.Add(1);
            }
            for (int i = 0; i < count_of_swith_off; i++)
            {
                Varians_of_run_system[i] = 0;
            }
            Generate_all_variant_in_pool(Varians_of_run_system);
            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                KnowlegeBaseSARules temp_rules = new  KnowlegeBaseSARules(result.RulesDatabaseSet[0], Pull_of_systems[i]);
                temp_rules.TrimTerms();

                result.RulesDatabaseSet.Add(temp_rules);
                result.UnlaidProtectionFix(result.RulesDatabaseSet[start_add_rules + i]);
                errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[start_add_rules + i]));
            }

            int best_index           = errors_of_systems.IndexOf(errors_of_systems.Min());
            KnowlegeBaseSARules best = result.RulesDatabaseSet[start_add_rules + best_index];

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(best);
            Console.WriteLine(Pull_of_systems.Count());



            GC.Collect();
//            result.UnlaidProtectionFix();
            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
コード例 #4
0
        public override SAFuzzySystem Generate(SAFuzzySystem Approximate, IGeneratorConf config)
        {
            type_alg            = ((kMeanRulesGeneratorConfig)config).KMRGTypeAlg;
            count_rules         = ((kMeanRulesGeneratorConfig)config).KMRGCountRules;
            type_func           = ((kMeanRulesGeneratorConfig)config).KMRGTypeFunc;
            nebulisation_factor = ((kMeanRulesGeneratorConfig)config).KMRGExponentialWeight;
            Max_iteration       = ((kMeanRulesGeneratorConfig)config).KMRGIteraton;
            need_precision      = ((kMeanRulesGeneratorConfig)config).KMRGAccuracy;


            Approxk_mean_base K_Agl = null;

            switch (type_alg)
            {
            case Type_k_mean_algorithm.GathGeva: K_Agl = new Approxk_mean_Gath_Geva(Approximate.LearnSamplesSet, Max_iteration, need_precision, count_rules, nebulisation_factor); break;

            case Type_k_mean_algorithm.GustafsonKessel: K_Agl = new Approxk_mean_Gustafson_kessel(Approximate.LearnSamplesSet, Max_iteration, need_precision, count_rules, nebulisation_factor); break;

            case Type_k_mean_algorithm.FCM: K_Agl = new Approxk_mean_base(Approximate.LearnSamplesSet, Max_iteration, need_precision, count_rules, nebulisation_factor); break;
            }
            K_Agl.Calc();

            KnowlegeBaseSARules New_Rules = new KnowlegeBaseSARules();

            for (int i = 0; i < count_rules; i++)
            {
                int []      order_terms = new int [Approximate.LearnSamplesSet.CountVars];
                List <Term> term_set    = new List <Term>();
                for (int j = 0; j < Approximate.LearnSamplesSet.CountVars; j++)
                {
                    Term temp_term = Term.MakeTerm(K_Agl.Centroid_cordinate_S[i][j], Math.Sqrt(Calc_distance_for_member_ship_function_for_Clust(i, j, K_Agl)) * 3, type_func, j);
                    term_set.Add(temp_term);
                }
                New_Rules.constuct__and_add_the_Rule(term_set, Approximate);
            }

            SAFuzzySystem Result = Approximate;

            if (Result.RulesDatabaseSet.Count > 0)
            {
                Result.RulesDatabaseSet[0] = New_Rules;
            }
            else
            {
                Result.RulesDatabaseSet.Add(New_Rules);
            }
            Result.UnlaidProtectionFix(Result.RulesDatabaseSet[0]);
            GC.Collect();
            Result.RulesDatabaseSet[0].TermsSet.Trim();
            return(Result);
        }
コード例 #5
0
        public override SAFuzzySystem TuneUpFuzzySystem(FuzzySystem.SingletoneApproximate.SAFuzzySystem Approximate, ILearnAlgorithmConf config)
        {
            start_add_rules = Approximate.RulesDatabaseSet.Count;
            SAFuzzySystem result = Approximate;

            if (result.RulesDatabaseSet.Count == 0)
            {
                throw new System.FormatException("Что то не то с входными данными");
            }



            OptimizeRullesShrinkConf Config = config as OptimizeRullesShrinkConf;

            count_Shrink_rule = Config.ORSCCountShrinkRules;

            int         count_of_swith_off    = count_Shrink_rule;
            List <byte> Varians_of_run_system = new List <byte>();

            for (int i = 0; i < Approximate.RulesDatabaseSet[0].RulesDatabase.Count; i++)
            {
                Varians_of_run_system.Add(1);
            }
            for (int i = 0; i < count_of_swith_off; i++)
            {
                Varians_of_run_system[i] = 0;
            }
            Generate_all_variant_in_pool(Varians_of_run_system);
            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                KnowlegeBaseSARules temp_rules = new  KnowlegeBaseSARules(result.RulesDatabaseSet[0], Pull_of_systems[i]);
                temp_rules.TrimTerms();

                result.RulesDatabaseSet.Add(temp_rules);
                result.UnlaidProtectionFix(result.RulesDatabaseSet[start_add_rules + i]);
                errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[start_add_rules + i]));
            }

            int best_index           = errors_of_systems.IndexOf(errors_of_systems.Min());
            KnowlegeBaseSARules best = result.RulesDatabaseSet[start_add_rules + best_index];

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(best);
            Console.WriteLine(Pull_of_systems.Count());



            result.RulesDatabaseSet[0].TermsSet.Trim();
//            result.UnlaidProtectionFix();
            return(result);
        }
コード例 #6
0
        public void randomSelection()
        {
            for (int i = 0; i < childrenMassive.Count(); i++)
            //Parallel.For(0, childrenMassive.Count(), i =>
            {
                fullFuzzySystem.RulesDatabaseSet.Add(childrenMassive[i]);
                fullFuzzySystem.UnlaidProtectionFix(childrenMassive[i]);
            }

            int        a            = allRandom.Next(childrenMassive.Count());
            List <int> indexMassive = new List <int>();

            //Parallel.For(0, current.Count(), i =>
            for (int i = 0; i < populationMassive.Count(); i++)
            {
                while (indexMassive.Contains(a))
                {
                    a = allRandom.Next(childrenMassive.Count());
                }
                populationMassive[i] = childrenMassive[a];
                indexMassive.Add(a);
                //});
            }
        }
コード例 #7
0
ファイル: GsaApprox.cs プロジェクト: CDMMKY/fuzzy_core
        public override SAFuzzySystem TuneUpFuzzySystem(SAFuzzySystem Approx, ILearnAlgorithmConf conf) // Здесь ведется оптимизация вашим алгоритмом
        {
            theFuzzySystem = Approx;

            iterMax = ((gsa_conf)conf).Количество_итераций;
            MCount  = ((gsa_conf)conf).Количество_частиц;
            G0      = ((gsa_conf)conf).Гравитационная_постоянная;
            alpha   = ((gsa_conf)conf).Коэффициент_уменьшения;
            epsilon = ((gsa_conf)conf).Малая_константа;
            X       = new KnowlegeBaseSARules[MCount];
            Errors  = new double[MCount];
            mass    = new double[MCount];
            double ErrorBest;
            KnowlegeBaseSARules BestSolution;
            double minValue;
            int    iminIndex;
            KnowlegeBaseSARules temp_c_Rule = new KnowlegeBaseSARules(theFuzzySystem.RulesDatabaseSet[0]);

            X[0]      = temp_c_Rule;
            Errors[0] = theFuzzySystem.RMSEtoMSEforLearn(theFuzzySystem.approxLearnSamples(X[0]));
            double ErrorZero = Errors[0];

            ErrorBest    = ErrorZero;
            BestSolution = temp_c_Rule;
            //number = X[0].TermsSet.Count * X[0].TermsSet[0].Parametrs.Count();

            R     = new double[MCount][, , ];
            speed = new double[MCount, X[0].TermsSet.Count, X[0].TermsSet[0].Parametrs.Count()];

            for (int i = 0; i < MCount; i++)
            {
                R[i] = new double[MCount, X[0].TermsSet.Count, X[0].TermsSet[0].Parametrs.Count()];
            }
            RR = new double[MCount, MCount];
            a  = new double[MCount, X[0].TermsSet.Count, X[0].TermsSet[0].Parametrs.Count()];

            for (int i = 1; i < MCount; i++)
            {
                temp_c_Rule = new KnowlegeBaseSARules(theFuzzySystem.RulesDatabaseSet[0]);
                X[i]        = temp_c_Rule;
                for (int j = 0; j < X[i].TermsSet.Count; j++)
                {
                    for (int k = 0; k < X[i].TermsSet[j].Parametrs.Count(); k++)
                    {
                        X[i].TermsSet[j].Parametrs[k] = GaussRandom.Random_gaussian(rand, X[i].TermsSet[j].Parametrs[k], 0.1 * (X[i].TermsSet[j].Parametrs[k])) + theFuzzySystem.LearnSamplesSet.InputAttributes[X[i].TermsSet[j].NumVar].Scatter * 0.05;
                    }
                }
                theFuzzySystem.RulesDatabaseSet.Add(X[i]);
                theFuzzySystem.UnlaidProtectionFix(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]);
                Errors[i] = theFuzzySystem.RMSEtoMSEforLearn(theFuzzySystem.approxLearnSamples(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]));

                X[i] = theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1];

                theFuzzySystem.RulesDatabaseSet.Remove(X[i]);
            }

            for (int iter = 0; iter < iterMax; iter++)
            {
                //g(t) = G(0)*e^(-a*t/T);
                G = G0 * Math.Pow(Math.E, ((-1) * alpha * iter / iterMax));

                /*  if (iter >= 100) {
                 *    Console.WriteLine("Wait");
                 * }*/
                algorithm();
                for (int r = 0; r < MCount; r++)
                {
                    theFuzzySystem.RulesDatabaseSet.Add(X[r]);
                    theFuzzySystem.UnlaidProtectionFix(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]);
                    Errors[r] = theFuzzySystem.RMSEtoMSEforLearn(theFuzzySystem.approxLearnSamples(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]));
                    X[r]      = theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1];
                    theFuzzySystem.RulesDatabaseSet.Remove(X[r]);
                }
                minValue  = Errors.Min();
                iminIndex = Errors.ToList().IndexOf(minValue);
                if (minValue < ErrorBest)
                {
                    ErrorBest    = minValue;
                    BestSolution = new KnowlegeBaseSARules(X[iminIndex]);
                }
            }

            if (ErrorBest < ErrorZero)
            {
                theFuzzySystem.RulesDatabaseSet[0] = BestSolution;
            }

            return(theFuzzySystem);
        }
コード例 #8
0
ファイル: GsaApprox.cs プロジェクト: CDMMKY/fuzzy_core
        private void weight()
        {
            double sum   = 0;
            double worst = mass[0];
            double best  = mass[0];

            int[] index = new Int32[MCount];
            int   count = 0;

            for (int i = 1; i < MCount; i++)
            {
                mass[i] = Errors[i];
                if (mass[i] > worst)
                {
                    worst = mass[i];
                }
                if (mass[i] < best)
                {
                    best = mass[i];
                }
            }
            for (int i = 0; i < MCount; i++)
            {
                if (mass[i] == worst)
                {
                    count++;
                    index[count - 1] = i;
                }
            }
            if (count > 1)
            {
                for (int i = 1; i < count; i++)
                {
                    ///X[index[i]] = ;
                    int f = index[i];
                    KnowlegeBaseSARules temp_c_Rule = new KnowlegeBaseSARules(theFuzzySystem.RulesDatabaseSet[0]);
                    temp_c_Rule = new KnowlegeBaseSARules(theFuzzySystem.RulesDatabaseSet[0]);
                    X[f]        = temp_c_Rule;
                    for (int j = 0; j < X[f].TermsSet.Count; j++)
                    {
                        for (int k = 0; k < X[f].TermsSet[j].Parametrs.Count(); k++)
                        {
                            X[f].TermsSet[j].Parametrs[k] = GaussRandom.Random_gaussian(rand, X[f].TermsSet[j].Parametrs[k], 0.1 * (X[f].TermsSet[j].Parametrs[k])) + theFuzzySystem.LearnSamplesSet.InputAttributes[X[f].TermsSet[j].NumVar].Scatter * 0.05;
                        }
                    }
                    theFuzzySystem.RulesDatabaseSet.Add(X[f]);
                    theFuzzySystem.UnlaidProtectionFix(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]);
                    Errors[f] = theFuzzySystem.RMSEtoMSEforLearn(theFuzzySystem.approxLearnSamples(theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1]));
                    X[f]      = theFuzzySystem.RulesDatabaseSet[theFuzzySystem.RulesDatabaseSet.Count - 1];
                    theFuzzySystem.RulesDatabaseSet.Remove(X[f]);
                    mass[f] = Errors[f];
                    if (mass[f] > worst)
                    {
                        i--;
                    }
                }
            }
            for (int i = 0; i < MCount; i++)
            {
                mass[i] = (mass[i] - worst) / (best - worst);
                sum     = sum + mass[i];
            }
            for (int i = 0; i < MCount; i++)
            {
                mass[i] = mass[i] / sum;
            }
        }
コード例 #9
0
 public double CalcNewProfit(KnowlegeBaseSARules Solution)
 {
     Tempory.Add(Solution);
     theFuzzySystem.UnlaidProtectionFix(Solution);
     return(theFuzzySystem.approxLearnSamples(Solution));
 }
コード例 #10
0
        public override SAFuzzySystem Generate(FuzzySystem.SingletoneApproximate.SAFuzzySystem Approximate, IGeneratorConf config)
        {
            Random        rand   = new Random();
            SAFuzzySystem result = Approximate;

            if (result.RulesDatabaseSet.Count == 0)
            {
                KnowlegeBaseSARules temp_rules = new KnowlegeBaseSARules();
                result.RulesDatabaseSet.Add(temp_rules);
            }

            type_term    = ((GeneratorRullesSimpleRandomConfig)config).RSRTypeFunc;
            stable_terms = (int)((GeneratorRullesSimpleRandomConfig)config).RSRConstant;
            count_rules  = ((GeneratorRullesSimpleRandomConfig)config).RSRCountRules;


            for (int j = 0; j < count_rules; j++)
            {
                int[]            order = new int[result.CountFeatures];
                TypeTermFuncEnum temp_type_term;
                if (stable_terms == 0)
                {
                    temp_type_term = type_term;
                }
                else
                {
                    temp_type_term = Generator_type_term();
                }

                List <Term> temp_term_list = new List <Term>();
                for (int k = 0; k < result.CountFeatures; k++)
                {
                    double[] parametrs = new double[Term.CountParamsinSelectedTermType(temp_type_term)];

                    switch (temp_type_term)
                    {
                    case TypeTermFuncEnum.Треугольник:
                        parametrs[0] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[1] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[2] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        Array.Sort(parametrs);
                        break;

                    case TypeTermFuncEnum.Гауссоида: parametrs[0] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[1] = (rand.NextDouble() + 0.01) * 0.5 *
                                       (result.LearnSamplesSet.InputAttributes[k].Max -
                                        result.LearnSamplesSet.InputAttributes[k].Min);
                        break;

                    case TypeTermFuncEnum.Парабола: parametrs[0] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[1] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        Array.Sort(parametrs);
                        break;

                    case TypeTermFuncEnum.Трапеция: parametrs[0] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[1] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[2] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);
                        parametrs[3] = result.LearnSamplesSet.InputAttributes[k].Min + rand.NextDouble() * (result.LearnSamplesSet.InputAttributes[k].Max - result.LearnSamplesSet.InputAttributes[k].Min);

                        Array.Sort(parametrs);

                        break;
                    }
                    Term temp_term = new Term(parametrs, temp_type_term, k);
                    result.RulesDatabaseSet[0].TermsSet.Add(temp_term);
                    temp_term_list.Add(temp_term);
                    order[k] = result.RulesDatabaseSet[0].TermsSet.Count - 1;
                }
                double DoubleOutput = KNNConsequent.NearestApprox(result, temp_term_list);
                SARule temp_Rule    = new SARule(result.RulesDatabaseSet[0].TermsSet, order, DoubleOutput);
                result.RulesDatabaseSet[0].RulesDatabase.Add(temp_Rule);
            }
            result.RulesDatabaseSet[0].TermsSet.Trim();


            result.UnlaidProtectionFix(result.RulesDatabaseSet[0]);

            GC.Collect();
            return(result);
        }
コード例 #11
0
ファイル: DynamicTune.cs プロジェクト: CDMMKY/fuzzy_core
        public override SAFuzzySystem TuneUpFuzzySystem(SAFuzzySystem Approximate, ILearnAlgorithmConf conf) // + override
        {
            result = Approximate;


            List <KnowlegeBaseSARules> Archive = new List <KnowlegeBaseSARules>();
            List <double> ErrorsArchive        = new List <double>();

            var config = (DynamicTuneConf)conf;

            maxError  = config.MaxError;
            RuleCount = config.RulesCount;
            TryCount  = config.TryCount;
            double error        = result.RMSEtoMSEdiv2forLearn(result.approxLearnSamples(result.RulesDatabaseSet[0]));
            var    kbToOptimize = new KnowlegeBaseSARules(result.RulesDatabaseSet[0]);
            var    kbBest       = new KnowlegeBaseSARules(kbToOptimize);
            double errorBefore  = Double.MaxValue;

            result.UnlaidProtectionFix(kbToOptimize);

            List <input_space> variable_spaces = new List <input_space>();

            for (int i = 0; i < result.LearnSamplesSet.InputAttributes.Count; i++)
            {
                List <Term> terms_of_variable = new List <Term>();
                terms_of_variable = kbToOptimize.TermsSet.Where(term => term.NumVar == i).ToList();
                variable_spaces.Add(new input_space(terms_of_variable, i));
            }

            int indexRegion = -1,
                indexVar    = -1,
                number_of_input_variables = variable_spaces.Count;

            int tryCount = 0;



            while (error > maxError)
            {
                if (Double.IsInfinity(error))
                {
                    throw new Exception("Something went wrong, error is Infinity, region: " + indexRegion);
                }
                if (Double.IsNaN(error))
                {
                    throw new Exception("Something went wrong, error is NaN, region: " + indexRegion);
                }

                region_side[][] sides = new region_side[number_of_input_variables][];
                for (int i = 0; i < number_of_input_variables; i++)
                {
                    sides[i] = variable_spaces[i].get_region_sides();
                }
                var cartresult = CartesianProduct.Get(sides);

                List <region2> regions = new List <region2>();

                foreach (var x in cartresult)
                {
                    regions.Add(new region2(x.ToList(), result, variable_spaces));
                }

                List <double> region_errors = regions.Select(x => x.region_error()).ToList();
                indexRegion = region_errors.IndexOf(region_errors.Max());

                for (int i = 0; i < region_errors.Count; i++)
                {
                    if (Double.IsNaN(region_errors[i]) || Double.IsInfinity(region_errors[i]) ||
                        Double.IsNegativeInfinity(region_errors[i]) || Double.IsPositiveInfinity(region_errors[i]))
                    {
                        region_errors[i] = 0;
                    }
                }

                List <double> variable_errors = regions[indexRegion].variable_errors();
                bool          check1          = false;
                for (int i = 1; i < variable_errors.Count; i++)
                {
                    if (variable_errors[i - 1] != variable_errors[i])
                    {
                        check1 = true;
                        break;
                    }
                }
                if (!check1)
                {
                    indexVar = StaticRandom.Next(variable_errors.Count - 1);
                }
                else
                {
                    indexVar = variable_errors.IndexOf(variable_errors.Max());
                }

                Term new_term = regions[indexRegion].new_term(indexVar);
                result.RulesDatabaseSet[0] = kbToOptimize;
                kbToOptimize.TermsSet.Add(new_term);

                // Rules (CHECK REFERENCE TYPES)
                int @var = indexVar;

                var rulesLeft = kbToOptimize.RulesDatabase.Where(
                    rule => rule.ListTermsInRule.Contains(regions[indexRegion].sides[indexVar].left)).ToList();
                var rulesRight = kbToOptimize.RulesDatabase.Where(
                    rule => rule.ListTermsInRule.Contains(regions[indexRegion].sides[indexVar].right)).ToList();
                for (int j = 0; j < rulesLeft.Count; j++)
                {
                    int[] order = new int[rulesLeft[j].ListTermsInRule.Count];
                    for (int k = 0; k < rulesLeft[j].ListTermsInRule.Count; k++)
                    {
                        Term temp_term = rulesLeft[j].ListTermsInRule[k];
                        if (temp_term == regions[indexRegion].sides[indexVar].left)
                        {
                            temp_term = new_term;
                        }
                        order[k] = kbToOptimize.TermsSet.FindIndex(x => x == temp_term);
                    }
///!!!!
                    double temp_approx_Values = kbToOptimize.RulesDatabase[j].IndependentConstantConsequent;

                    /*        double[] temp_approx_RegressionConstantConsequent =
                     *          kbToOptimize.RulesDatabase[j].RegressionConstantConsequent.Clone() as double[];
                     */


                    SARule temp_rule = new SARule(
                        kbToOptimize.TermsSet, order, temp_approx_Values);

                    // double[] dC = null;
//!!!
                    temp_rule.IndependentConstantConsequent = KNNConsequent.NearestApprox(result, temp_rule.ListTermsInRule.ToList());



                    kbToOptimize.RulesDatabase.Add(temp_rule);


//!!!
                    rulesLeft[j].IndependentConstantConsequent = KNNConsequent.NearestApprox(result, rulesLeft[j].ListTermsInRule.ToList());
                    //           rulesLeft[j].RegressionConstantConsequent = (double[])dC.Clone();
                }

                foreach (var rule in rulesRight)
                {
//!!!

                    rule.IndependentConstantConsequent = KNNConsequent.NearestApprox(
                        result, rule.ListTermsInRule.ToList());
                    //               rule.RegressionConstantConsequent = dC;
                }

                variable_spaces[indexVar].terms.Add(new_term);
                variable_spaces[indexVar].terms.Sort(new CompararerByPick());

                // Re-evaluate the system's error
                error = result.RMSEtoMSEdiv2forLearn(result.ErrorLearnSamples(kbToOptimize));

                if ((kbToOptimize.RulesDatabase.Count > config.RulesCount))
                {
                    break;
                }

#if Console
                Console.WriteLine(error + " " + kbToOptimize.TermsSet.Count + " terms\n");
                for (int i = 0; i < variable_spaces.Count; i++)
                {
                    Console.WriteLine(variable_spaces[i].terms.Count + " термов по " + i + "му параметру\n");
                }
#endif
                result.RulesDatabaseSet[0] = kbToOptimize;
                // Get the best knowledge base on the 1st place
                if (error < errorBefore)
                {
                    kbBest      = new KnowlegeBaseSARules(kbToOptimize);
                    errorBefore = error;
                    tryCount    = 0;
                }
                else
                {
                    tryCount++;
                }
                if (tryCount > TryCount)
                {
                    break;
                }
            }


            result.RulesDatabaseSet[0] = kbBest;
            RuleCount = kbBest.RulesDatabase.Count;
            TryCount  = tryCount;

            return(result);
        }
コード例 #12
0
 public void calc_Error(SAFuzzySystem error_checker)
 {
     error_checker.UnlaidProtectionFix(hrom_vector.Core_Check);
     Error = error_checker.approxLearnSamples(hrom_vector.Core_Check);
 }
コード例 #13
0
ファイル: KrillST.cs プロジェクト: CDMMKY/fuzzy_core
        //основные вычисления
        public override SAFuzzySystem TuneUpFuzzySystem(SAFuzzySystem Approx, ILearnAlgorithmConf conf)
        {
            result = Approx;
            Init(conf);
            SetPopulation();
            KnowlegeBaseSARules BEST = new KnowlegeBaseSARules(result.RulesDatabaseSet[0]);
            double bestError         = result.ErrorLearnSamples(BEST);

            //отчистка консоли

#if debug
            Console.Clear();
#endif
            //запуск итераций
            for (int it = 0; it < iter; it++)
            {
#if debug
                //вывод номера итерации
                Console.Write("Итерация __№__ = ");
                Console.WriteLine(it);
#endif
                //расчитыавем значение фитнес-функции
                Population = ListSingletonApproximateTool.SortRules(Population, result);
                double[] K = new double[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    K[i] = result.ErrorLearnSamples(Population[i]);
#if debug
                    Console.Write("Значние  K[i1] = ");
                    Console.WriteLine(K[i]);
#endif
                    if (double.IsNaN(K[i]) || double.IsInfinity(K[i]))
                    {
                        result.UnlaidProtectionFix(Population[i]);
                        K[i] = result.ErrorLearnSamples(Population[i]);

#if debug
                        Console.Write("Значние  K[i2] = ");
                        Console.WriteLine(K[i]);
#endif
                    }
                }
                Kworst = K.Max();
                if (double.IsNaN(Kworst) || double.IsInfinity(Kworst))
                {
                    int iworst = K.ToList().IndexOf(Kworst);
 #if debug
                    Console.Write("Значние iworst = ");
                    Console.WriteLine(iworst);
#endif
                }

#if debug
                //вывод Kworst
                Console.Write("Значние KWorst = ");
                Console.WriteLine(Kworst);
#endif
                Kbest = K.Min();
#if debug
                //вывод Kbest
                Console.Write("Значние Kbest = ");
                Console.WriteLine(Kbest);
#endif
                int ibest = K.ToList().IndexOf(Kbest);
#if debug
                //вывод ibest
                Console.Write("Значние ibest = ");
                Console.WriteLine(ibest);
#endif
                //перебрать значения фитнес функции
                //расчитыавем значение D
                double dit;
                dit = it;
                double diter;
                diter = iter;

                double D = (dmax * (rand.NextDouble() * 2 - 1) * (dit / diter));

                //расчитываем значение rand1 для D
                double rand1;
                rand1 = D / (dmax * (it) / iter);
#if debug
                //выводим значение rand1 для D
                Console.Write("Значение Drand = ");
                Console.WriteLine(rand1);

                //выводим значение D
                Console.Write("Значение __D__ = ");
                Console.WriteLine(D);
#endif
                //расчитыавем значение Xfood
                double divide = K.Select(x => 1 / x).ToList().Sum();
                var    Xfood  = new KnowlegeBaseSARules(Population[0]);
                for (int t = 0; t < Xfood.TermsSet.Count; t++)
                {
                    for (int p = 0; p < Xfood.TermsSet[t].CountParams; p++)
                    {
                        Xfood.TermsSet[t].Parametrs[p] = 0;

                        for (int i = 0; i < Population.Length; i++)
                        {
                            Xfood.TermsSet[t].Parametrs[p] += Population[i].TermsSet[t].Parametrs[p] / K[i];
#if debug
                            //выводим значение Xfood
                            Console.Write("Значение Xfood = ");
                            Console.WriteLine(Xfood.TermsSet[t].Parametrs[p]);
#endif
                        }
                        Xfood.TermsSet[t].Parametrs[p] /= divide;
                    }
                }
#if debug
                //вывод divide
                Console.Write("Значние divide = ");
                Console.WriteLine(divide);
#endif
                //расчитываем значение Kfood
                double Kfood = result.ErrorLearnSamples(Xfood);
                if (double.IsNaN(Kfood) || double.IsInfinity(Kfood))
                {
                    result.UnlaidProtectionFix(Xfood);
                    Kfood = result.ErrorLearnSamples(Xfood);
                }
#if debug
                //выводим значение Kfood
                Console.Write("Значение Kfood = ");
                Console.WriteLine(Kfood);
#endif
                //расчитываем значение Cfood
                double Cfood = 2 * (1 - (dit / diter));
#if debug
                //выводим значение Cfood
                Console.Write("Значение Cfood = ");
                Console.WriteLine(Cfood);
#endif
                //расчитываем значение Bfood
                KnowlegeBaseSARules[] Bfood = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    Bfood[i] = new KnowlegeBaseSARules(Population[i]);
                    double KRoofifood = CalcKroof(K[i], Kfood);
                    KnowlegeBaseSARules Xroofifood = new KnowlegeBaseSARules(CalcXroof(Population[i], Xfood));
                    for (int t = 0; t < Bfood[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < Bfood[i].TermsSet[t].CountParams; p++)
                        {
                            Bfood[i].TermsSet[t].Parametrs[p] = Cfood * KRoofifood * Xroofifood.TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение Bfood
                            Console.Write("Значение Bfood = ");
                            Console.WriteLine(Bfood[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }

                //расчитываем значение Bbest
                KnowlegeBaseSARules[] Bbest = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    Bbest[i] = new KnowlegeBaseSARules(Population[i]);
                    double KRoofifood = CalcKroof(K[i], K[ibest]);
                    KnowlegeBaseSARules Xroofifood = new KnowlegeBaseSARules(CalcXroof(Population[i], Population[ibest]));
                    for (int t = 0; t < Bbest[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < Bbest[i].TermsSet[t].CountParams; p++)
                        {
                            Bbest[i].TermsSet[t].Parametrs[p] = KRoofifood * Xroofifood.TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение Bbest
                            Console.Write("Значение Bbest = ");
                            Console.WriteLine(Bbest[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }

                //расчитываем значение B
                KnowlegeBaseSARules[] B = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    B[i] = new KnowlegeBaseSARules(Population[i]);
                    for (int t = 0; t < B[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < B[i].TermsSet[t].CountParams; p++)
                        {
                            B[i].TermsSet[t].Parametrs[p] = Bfood[i].TermsSet[t].Parametrs[p] + Bbest[i].TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение B
                            Console.Write("Значение __B__ = ");
                            Console.WriteLine(B[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }

                //расчитываем значение F
                KnowlegeBaseSARules[] F = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    if (i == 0)
                    {
                        F[i] = new KnowlegeBaseSARules(Population[i]);
                        for (int t = 0; t < F[i].TermsSet.Count; t++)
                        {
                            for (int p = 0; p < F[i].TermsSet[t].CountParams; p++)
                            {
                                F[i].TermsSet[t].Parametrs[p] = Vf * B[i].TermsSet[t].Parametrs[p];
#if debug
                                //выводим значение F
                                Console.Write("Значение __F__ = ");
                                Console.WriteLine(F[i].TermsSet[t].Parametrs[p]);
#endif
                            }
                        }
                    }
                    else
                    {
                        F[i] = new KnowlegeBaseSARules(Population[i]);
                        for (int t = 0; t < F[i].TermsSet.Count; t++)
                        {
                            for (int p = 0; p < F[i].TermsSet[t].CountParams; p++)
                            {
                                F[i].TermsSet[t].Parametrs[p] = Vf * B[i].TermsSet[t].Parametrs[p] + wf * F[i - 1].TermsSet[t].Parametrs[p];
#if debug
                                //выводим значение F
                                Console.Write("Значение __F__ = ");
                                Console.WriteLine(F[i].TermsSet[t].Parametrs[p]);
#endif
                            }
                        }
                    }
                }
                List <int> [] neihbors = new List <int> [Population.Length];
                //расчитываем значение alocal
                KnowlegeBaseSARules[] alocal = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    alocal[i]   = new KnowlegeBaseSARules(Population[i]);
                    neihbors[i] = countneihbors(Population[i]);

/*
 #if debug
 *                  //вывод значений количества соседей
 *                  for (int g = 0; g < Population.Length; g++)
 *                  {
 *                      Console.Write("Знаение countneihbors = ");
 *                      Console.WriteLine(countneihbors(Population[g]));
 *                  }
 #endif
 */

                    for (int t = 0; t < alocal[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < alocal[i].TermsSet[t].CountParams; p++)
                        {
                            alocal[i].TermsSet[t].Parametrs[p] = 0;
                            for (int j = 0; j < neihbors[i].Count; j++)
                            {
                                double KRoofij = CalcKroof(K[i], K[neihbors[i][j]]);
                                KnowlegeBaseSARules XRoofij = new KnowlegeBaseSARules(CalcXroof(Population[i], Population[neihbors[i][j]]));

                                alocal[i].TermsSet[t].Parametrs[p] += KRoofij * XRoofij.TermsSet[t].Parametrs[p];

#if debug
                                //выводим значение alocal
                                Console.Write("Знаение alocal = ");
                                Console.WriteLine(alocal[i].TermsSet[t].Parametrs[p]);
#endif
                            }
                        }
                    }
                }

                //расчитываем значение Cbest
                double Cbest = 2 * (rand.NextDouble() - (dit / diter));
#if debug
                //выводим значение Cbest
                Console.Write("Значение Сbest = ");
                Console.WriteLine(Cbest);
#endif
                //расчитываем значение rand для Cbest
                double rand2;
                rand2 = it / iter - Cbest / 2;
#if debug
                //выводим значение rand2 для Cbest
                Console.Write("Значение Crand = ");
                Console.WriteLine(rand2);
#endif
                //расчитываем значение atarget
                KnowlegeBaseSARules[] atarget = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    atarget[i] = new KnowlegeBaseSARules(Population[i]);
                    double KRoofibest = CalcKroof(K[i], K[ibest]);
                    KnowlegeBaseSARules XRoofibest = new KnowlegeBaseSARules(CalcXroof(Population[i], Population[ibest]));
                    for (int t = 0; t < alocal[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < atarget[i].TermsSet[t].CountParams; p++)
                        {
                            atarget[i].TermsSet[t].Parametrs[p] = Cbest * KRoofibest * XRoofibest.TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение atarget
                            Console.Write("Знание atarget = ");
                            Console.WriteLine(atarget[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }

                //расчитываем значение a
                KnowlegeBaseSARules[] a = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    a[i] = new KnowlegeBaseSARules(Population[i]);
                    for (int t = 0; t < a[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < a[i].TermsSet[t].CountParams; p++)
                        {
                            a[i].TermsSet[t].Parametrs[p] = atarget[i].TermsSet[t].Parametrs[p] + alocal[i].TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение a
                            Console.Write("Значение __a__ = ");
                            Console.WriteLine(a[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }

                //расчитываем значение N
                KnowlegeBaseSARules[] N = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    if (i == 0)
                    {
                        N[i] = new KnowlegeBaseSARules(Population[i]);
                        for (int t = 0; t < N[i].TermsSet.Count; t++)
                        {
                            for (int p = 0; p < F[i].TermsSet[t].CountParams; p++)
                            {
                                N[i].TermsSet[t].Parametrs[p] = Vf * a[i].TermsSet[t].Parametrs[p];
#if debug
                                //выводим значение N
                                Console.Write("Значение __N__ = ");
                                Console.WriteLine(N[i].TermsSet[t].Parametrs[p]);
#endif
                            }
                        }
                    }
                    else
                    {
                        N[i] = new KnowlegeBaseSARules(Population[i]);
                        for (int t = 0; t < F[i].TermsSet.Count; t++)
                        {
                            for (int p = 0; p < N[i].TermsSet[t].CountParams; p++)
                            {
                                N[i].TermsSet[t].Parametrs[p] = nmax * a[i].TermsSet[t].Parametrs[p] + wn * N[i - 1].TermsSet[t].Parametrs[p];
#if debug
                                //выводим значение N
                                Console.Write("Значение __N__ = ");
                                Console.WriteLine(N[i].TermsSet[t].Parametrs[p]);
#endif
                            }
                        }
                    }
                }

                //расчитываем значение dX
                KnowlegeBaseSARules[] dX = new KnowlegeBaseSARules[Population.Length];
                for (int i = 0; i < Population.Length; i++)
                {
                    dX[i] = new KnowlegeBaseSARules(Population[i]);
                    for (int t = 0; t < a[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < a[i].TermsSet[t].CountParams; p++)
                        {
                            dX[i].TermsSet[t].Parametrs[p] = F[i].TermsSet[t].Parametrs[p] + N[i].TermsSet[t].Parametrs[p] + D;
#if debug
                            //выводим значение dX
                            Console.Write("Значение _dX__ = ");
                            Console.WriteLine(dX[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }



                //выводим значение BEST
                //   Console.Write("Значение BEST_ = ");
                //  Console.WriteLine(BEST);


                //расчитываем значение X(t+dt)
                for (int i = 0; i < Population.Length; i++)
                {
                    Population[i] = new KnowlegeBaseSARules(Population[i]);
                    for (int t = 0; t < Population[i].TermsSet.Count; t++)
                    {
                        for (int p = 0; p < F[i].TermsSet[t].CountParams; p++)
                        {
                            Population[i].TermsSet[t].Parametrs[p] = Population[i].TermsSet[t].Parametrs[p] + calcdeltat(ct) * dX[i].TermsSet[t].Parametrs[p];
#if debug
                            //выводим значение Xnew
                            Console.Write("Знание X(t+dt) = ");
                            Console.WriteLine(Population[i].TermsSet[t].Parametrs[p]);
#endif
                        }
                    }
                }



                for (int i = 0; i < Population.Length; i++)
                {
                    double temp = result.ErrorLearnSamples(Population[i]);
                    if (double.IsNaN(temp) || double.IsInfinity(temp))
                    {
                        result.UnlaidProtectionFix(Xfood);
                        temp = result.ErrorLearnSamples(Population[i]);
                    }

                    if (temp < bestError)
                    {
                        BEST      = new KnowlegeBaseSARules(Population[i]);
                        bestError = temp;
                    }
                }


                double y = it;
                if (y % 50 == 0 & y != 0)
                {
                    Console.WriteLine(it);
                    Console.WriteLine(bestError);
                }
#if debug
                // выводим значение лучшей ошибки Kbest
                Console.Write("Значние BestError = ");
                Console.WriteLine(bestError);

                Console.WriteLine(".");
#endif
            }
            result.RulesDatabaseSet[0] = BEST;
            return(result);
        }