Пример #1
0
        public override FuzzySystem.SingletoneApproximate.SAFuzzySystem TuneUpFuzzySystem(FuzzySystem.SingletoneApproximate.SAFuzzySystem Approximate, ILearnAlgorithmConf conf)
        {
            Mnk_lib.Mnk_class Mnk_me = new Mnk_lib.Mnk_class();

            double [,,] Extracted_rules  = extract_Rules(Approximate.RulesDatabaseSet[0]);
            double [,] Extracted_Samples = extract_Sample_table(Approximate.LearnSamplesSet);
            double [] Extracted_Samples_out = extract_Sample_table_Out(Approximate.LearnSamplesSet);
            int       count_rules           = Approximate.RulesDatabaseSet[0].RulesDatabase.Count;
            int       count_samples         = Approximate.LearnSamplesSet.CountSamples;
            int       count_Vars            = Approximate.LearnSamplesSet.CountVars;

            double []        New_consq = new double[count_rules];
            TypeTermFuncEnum type_Func = Approximate.RulesDatabaseSet[0].TermsSet[0].TermFuncType;
            int type_func = (int)type_Func;

            Mnk_me.mnk_R(Extracted_rules, count_rules, type_func, Extracted_Samples, Extracted_Samples_out, count_samples, count_Vars, out New_consq);

            SAFuzzySystem Result = Approximate;

            double result_before = Result.approxLearnSamples(Result.RulesDatabaseSet[0]);

            double [] Back_consq = Result.RulesDatabaseSet[0].all_conq_of_rules;
            Result.RulesDatabaseSet[0].all_conq_of_rules = New_consq;
            double result_after = Result.approxLearnSamples(Result.RulesDatabaseSet[0]);

            if (result_before < result_after)
            {
                Result.RulesDatabaseSet[0].all_conq_of_rules = Back_consq;
            }
            GC.Collect();
            Result.RulesDatabaseSet[0].TermsSet.Trim();
            return(Result);
        }
        public override PCFuzzySystem Generate(PCFuzzySystem Classifier, IGeneratorConf config)
        {
            PCFuzzySystem result = Classifier;

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

            count_shrink = ((TermShrinkAndRotateConf)config).TSARCShrinkVars;
            size_shrink  = ((TermShrinkAndRotateConf)config).TSARCShrinkTerm;
            type_func    = ((TermShrinkAndRotateConf)config).IEWEFuncType;
            count_slices = ((TermShrinkAndRotateConf)config).IEWECountSlice;



            List <int> Varians_of_run_system = new List <int>();

            for (int i = 0; i < Classifier.CountFeatures; i++)
            {
                int count_terms_for_var = Classifier.RulesDatabaseSet[0].TermsSet.FindAll(x => x.NumVar == i).Count;
                if (i < count_shrink)
                {
                    Varians_of_run_system.Add(count_terms_for_var - size_shrink);
                }
                else
                {
                    Varians_of_run_system.Add(count_terms_for_var);
                }
            }

            Varians_of_run_system.Sort();
            TypeTermFuncEnum type_of_term = Classifier.RulesDatabaseSet[0].TermsSet[0].TermFuncType;

            Generate_all_variant_in_pool(Varians_of_run_system);

            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                Classifier.RulesDatabaseSet.Clear();

                GeneratorRulesEveryoneWithEveryone.InitRulesEveryoneWithEveryone(Classifier, type_of_term, Pull_of_systems[i].ToArray());
                Systems_ready_to_test.Add(Classifier.RulesDatabaseSet[0]);
                errors_of_systems.Add(result.ErrorLearnSamples(result.RulesDatabaseSet[0]));
            }

            int best_index = errors_of_systems.IndexOf(errors_of_systems.Min());

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(Systems_ready_to_test[best_index]);
            Console.WriteLine(Pull_of_systems.Count());



            GC.Collect();
//            result.UnlaidProtectionFix();
            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
Пример #3
0
        /// <summary>
        /// Метод расчитывающий вектор параметров по заданому значению пика функции принадлежности, разбросу отностельно центра и типу функции принадлежности.
        /// </summary>
        /// <param name="Center">Значении пика (центра) функции принадлежности</param>
        /// <param name="distance">Разбросу отностельно пика (центра) функции принадлежности</param>
        /// <param name="TypeTerm">Тип функции принадлежности</param>
        /// <returns>Вектор параметров функции принадлежности</returns>
        public static double[] GenTermParams(double Center, double distance, TypeTermFuncEnum TypeTerm)
        {
            double[] result = new double[CountParamsinSelectedTermType(TypeTerm)];
            switch (TypeTerm)
            {
            case TypeTermFuncEnum.Гауссоида:
            {
                result[0] = Center;
                result[1] = distance / 3.0;
            } break;

            case TypeTermFuncEnum.Треугольник:
            {
                result[0] = Center - distance;
                result[1] = Center;
                result[2] = Center + distance;
            } break;

            case TypeTermFuncEnum.Парабола:
            {
                result[0] = Center - distance;
                result[1] = Center + distance;
            } break;

            case TypeTermFuncEnum.Трапеция:
            {
                result[0] = Center - distance;
                result[3] = Center + distance;
                result[1] = result[0] + 0.8 * distance;
                result[2] = result[0] + 1.2 * distance;
            } break;
            }
            return(result);
        }
Пример #4
0
        protected void InitRulesBySamples(PCFuzzySystem Classifier, TypeTermFuncEnum typeFunc)
        {
            if ((Classifier.RulesDatabaseSet == null) || (Classifier.RulesDatabaseSet.Count == 0))
            {
                KnowlegeBasePCRules temp_rules = new KnowlegeBasePCRules();
                Classifier.RulesDatabaseSet.Add(temp_rules);
            }

            for (int i = 0; i < Classifier.CountClass; i++)
            {
                if (!ExistClassFeatureMax(i) || !ExistClassFeatureMin(i))
                {
                    continue;
                }
                int[] order_terms = new int[Classifier.CountFeatures];

                for (int j = 0; j < Classifier.CountFeatures; j++)
                {
                    if (Classifier.AcceptedFeatures[j] == false)
                    {
                        continue;
                    }


                    double[] paramerts = new double[Term.CountParamsinSelectedTermType(typeFunc)];
                    switch (typeFunc)
                    {
                    case TypeTermFuncEnum.Треугольник:
                        paramerts[0] = min_for_class[i][j] - 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        paramerts[2] = max_for_class[i][j] + 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        paramerts[1] = (paramerts[0] + paramerts[2]) / 2;
                        break;

                    case TypeTermFuncEnum.Гауссоида:
                        paramerts[0] = (max_for_class[i][j] +
                                        min_for_class[i][j]) / 2;
                        paramerts[1] = (paramerts[0] - min_for_class[i][j]) / 3;      // rule of 3g
                        break;

                    case TypeTermFuncEnum.Парабола:
                        paramerts[0] = min_for_class[i][j] - 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        paramerts[1] = max_for_class[i][j] + 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        break;

                    case TypeTermFuncEnum.Трапеция:
                        paramerts[0] = min_for_class[i][j] - 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        paramerts[3] = max_for_class[i][j] + 0.001 * (max_for_class[i][j] - min_for_class[i][j]);
                        paramerts[1] = paramerts[0] + 0.4 * (paramerts[3] - paramerts[0]);
                        paramerts[2] = paramerts[0] + 0.6 * (paramerts[3] - paramerts[0]);
                        break;
                    }
                    Term temp_term = new Term(paramerts, typeFunc, j);
                    Classifier.RulesDatabaseSet[0].TermsSet.Add(temp_term);
                    order_terms[j] = Classifier.RulesDatabaseSet[0].TermsSet.Count - 1;
                }
                PCRule temp_Rule = new PCRule(Classifier.RulesDatabaseSet[0].TermsSet, order_terms,
                                              Classifier.LearnSamplesSet.OutputAttribute.LabelsValues[i], 1);
                Classifier.RulesDatabaseSet[0].RulesDatabase.Add(temp_Rule);
            }
        }
Пример #5
0
        protected override void fill_params(string[] args)
        {
            file_learn = (args.Where(x => x.Contains("tra"))).ToArray()[0];
            Console.WriteLine("Before cut {0}", file_learn);
            file_learn = file_learn.Remove(0, 4);
            Console.WriteLine("After cut {0}", file_learn);
            file_test = (args.Where(x => x.Contains("tst"))).ToArray()[0];
            file_test = file_test.Remove(0, 4);
            file_out  = (args.Where(x => x.Contains("out"))).ToArray()[0];
            file_out  = file_out.Remove(0, 4);

            string temp = (args.Where(x => x.Contains("typeFunc"))).ToArray()[0];

            switch (temp)
            {
            case "Triangle": func = TypeTermFuncEnum.Треугольник; break;

            case "Gauss": func = TypeTermFuncEnum.Гауссоида; break;

            case "Parabola": func = TypeTermFuncEnum.Парабола; break;

            case "Trapezium": func = TypeTermFuncEnum.Трапеция; break;

            default: func = TypeTermFuncEnum.Треугольник; break;
            }
        }
Пример #6
0
        protected override void fill_params(string[] args)
        {
            file_learn = (args.Where(x => x.Contains("tra"))).ToArray()[0];
            Console.WriteLine("Before cut {0}", file_learn);
            file_learn = file_learn.Remove(0, 4);
            Console.WriteLine("After cut {0}", file_learn);
            file_test = (args.Where(x => x.Contains("tst"))).ToArray()[0];
            file_test = file_test.Remove(0, 4);
            file_out  = (args.Where(x => x.Contains("out"))).ToArray()[0];
            file_out  = file_out.Remove(0, 4);
            int    temp_i = 0;
            string temp   = (args.Where(x => x.Contains("CountN1"))).ToArray()[0];

            int.TryParse(temp, out temp_i);
            CountN[0] = temp_i;

            temp = (args.Where(x => x.Contains("CountN2"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[1] = temp_i;

            temp = (args.Where(x => x.Contains("CountN3"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[2] = temp_i;

            temp = (args.Where(x => x.Contains("CountN4"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[3] = temp_i;

            temp = (args.Where(x => x.Contains("CountN5"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[4] = temp_i;

            temp = (args.Where(x => x.Contains("CountN6"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[5] = temp_i;

            temp = (args.Where(x => x.Contains("CountN7"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[6] = temp_i;

            temp = (args.Where(x => x.Contains("CountN8"))).ToArray()[0];
            int.TryParse(temp, out temp_i);
            CountN[7] = temp_i;


            temp = (args.Where(x => x.Contains("typeFunc"))).ToArray()[0];
            switch (temp)
            {
            case "Triangle": func = TypeTermFuncEnum.Треугольник; break;

            case "Gauss": func = TypeTermFuncEnum.Гауссоида; break;

            case "Parabola": func = TypeTermFuncEnum.Парабола; break;

            case "Trapezium": func = TypeTermFuncEnum.Трапеция; break;

            default: func = TypeTermFuncEnum.Треугольник; break;
            }
        }
 public virtual void Init(int countVars)
 {
     type_term_func = (TypeTermFuncEnum)Settings.Default.Type_func_int;
     count_terms    = new int[countVars];
     for (int i = 0; i < countVars; i++)
     {
         count_terms[i] = Settings.Default.AvrCountTerms;
     }
 }
Пример #8
0
        public override TSAFuzzySystem Generate(TSAFuzzySystem Approximate, IGeneratorConf config)
        {
            start_add_rules = Approximate.RulesDatabaseSet.Count;
            TSAFuzzySystem 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++)
            {
                KnowlegeBaseTSARules temp_rules = new  KnowlegeBaseTSARules(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());
            KnowlegeBaseTSARules 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);
        }
Пример #9
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approximate, ILearnAlgorithmConf config)
        {
            TSAFuzzySystem result = Approximate;

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

            count_shrink = Config.OTSARCountShrinkVars;
            size_shrink  = Config.OTSARCountShrinkTerm;



            List <int> Varians_of_run_system = new List <int>();

            for (int i = 0; i < Approximate.CountFeatures; i++)
            {
                int count_terms_for_var = Approximate.RulesDatabaseSet[0].TermsSet.FindAll(x => x.NumVar == i).Count;
                if (i < count_shrink)
                {
                    Varians_of_run_system.Add(count_terms_for_var - size_shrink);
                }
                else
                {
                    Varians_of_run_system.Add(count_terms_for_var);
                }
            }

            Varians_of_run_system.Sort();
            TypeTermFuncEnum type_of_term = Approximate.RulesDatabaseSet[0].TermsSet[0].TermFuncType;

            Generate_all_variant_in_pool(Varians_of_run_system);

            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                Approximate.RulesDatabaseSet.Clear();

                GeneratorRulesEveryoneWithEveryone.InitRulesEveryoneWithEveryone(result, type_of_term, Pull_of_systems[i].ToArray());
                Systems_ready_to_test.Add(Approximate.RulesDatabaseSet[0]);
                errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[0]));
            }

            int best_index = errors_of_systems.IndexOf(errors_of_systems.Min());

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(Systems_ready_to_test[best_index]);
            Console.WriteLine(Pull_of_systems.Count());



            result.RulesDatabaseSet[0].TermsSet.Trim();
//            result.UnlaidProtectionFix();
            return(result);
        }
        public override SAFuzzySystem Generate(SAFuzzySystem Approximate, IGeneratorConf config)
        {
            SAFuzzySystem            result  = Approximate;
            InitEveryoneWithEveryone config1 = config as InitEveryoneWithEveryone;

            type_func        = config1.IEWEFuncType;
            count_slice_vars = config1.IEWECountSlice;
            InitRulesEveryoneWithEveryone(Approximate, type_func, count_slice_vars);



            return(result);
        }
Пример #11
0
        public override TSAFuzzySystem Generate(TSAFuzzySystem 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();

            KnowlegeBaseTSARules New_Rules = new KnowlegeBaseTSARules();

            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.ConstructNewRule(term_set, Approximate);
            }

            TSAFuzzySystem 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);
        }
Пример #12
0
        /// <summary>
        /// Функция преобразование типа функции принадлежности в текстовое описание
        /// </summary>
        /// <param name="tf">Тип функции принадлежности</param>
        /// <returns>Строка с названием типа функции принадлежности</returns>
        public static string ToStringTypeTerm(TypeTermFuncEnum tf)
        {
            switch (tf)
            {
            case TypeTermFuncEnum.Гауссоида: return("Гауссоида");

            case TypeTermFuncEnum.Парабола: return("Парабола");

            case TypeTermFuncEnum.Трапеция: return("Трапеция");

            case TypeTermFuncEnum.Треугольник: return("Треугольник");
            }

            return("Треугольная");
        }
Пример #13
0
        public override PCFuzzySystem Generate(PCFuzzySystem Classifier, IGeneratorConf config)
        {
            PCFuzzySystem result = Classifier;

            Systems_ready_to_test = new List <KnowlegeBasePCRules>();
            errors_of_systems     = new List <double>();


            InitEveryoneWithEveryone config1 = config as InitEveryoneWithEveryone;

            type_func        = config1.IEWEFuncType;
            count_slice_vars = config1.IEWECountSlice;


            List <int> Varians_of_run_system = new List <int>();

            for (int i = 0; i < Classifier.CountFeatures; i++)
            {
                int count_terms_for_var = count_slice_vars[i];
                Varians_of_run_system.Add(count_terms_for_var);
            }

            Varians_of_run_system.Sort();
            Generate_all_variant_in_pool(Varians_of_run_system);

            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                Classifier.RulesDatabaseSet.Clear();

                GeneratorRulesEveryoneWithEveryone.InitRulesEveryoneWithEveryone(result, type_func, Pull_of_systems[i].ToArray());
                Systems_ready_to_test.Add(Classifier.RulesDatabaseSet[0]);
                errors_of_systems.Add(result.ErrorLearnSamples(result.RulesDatabaseSet[0]));
            }

            int best_index = errors_of_systems.IndexOf(errors_of_systems.Min());

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(Systems_ready_to_test[best_index]);
            for (int i = 0; i < count_slice_vars.Count(); i++)
            {
                count_slice_vars[i] = result.RulesDatabaseSet[0].TermsSet.Count(x => x.NumVar == i);
            }
            Console.WriteLine(Pull_of_systems.Count());

            GC.Collect();
            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
Пример #14
0
        public virtual void Init(ILearnAlgorithmConf Config)
        {
            this.Config  = Config as BeeStructureConf;
            countScouts  = this.Config.ABCSCountScout;
            countWorkers = this.Config.ABCSCountWorkers;
            countRules   = this.Config.ABCSCountRules;
            typeTerm     = this.Config.ABCSTypeFunc;
            theScouts    = new Scout[countScouts];
            theWorkers   = new Worker[countWorkers * 3];


            if (theFuzzySystem.RulesDatabaseSet.Count < 1)
            {
                throw (new Exception("Что то не так с базой правил"));
            }
        }
        public override SAFuzzySystem Generate(SAFuzzySystem Approximate, IGeneratorConf config)
        {
            SAFuzzySystem result = Approximate;

            Systems_ready_to_test = new List <KnowlegeBaseSARules>();
            errors_of_systems     = new List <double>();

            InitEveryoneWithOptimal config1 = config as InitEveryoneWithOptimal;

            type_func        = config1.IEWOTypeFunc;
            count_slice_vars = config1.count_terms;


            List <int> Varians_of_run_system = new List <int>();

            for (int i = 0; i < Approximate.CountFeatures; i++)
            {
                int count_terms_for_var = count_slice_vars[i];
                Varians_of_run_system.Add(count_terms_for_var);
            }

            Varians_of_run_system.Sort();
            Generate_all_variant_in_pool(Varians_of_run_system);

            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                Approximate.RulesDatabaseSet.Clear();

                GeneratorRulesEveryoneWithEveryone.InitRulesEveryoneWithEveryone(Approximate, type_func, Pull_of_systems[i].ToArray());
                Systems_ready_to_test.Add(Approximate.RulesDatabaseSet[0]);
                errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[0]));
            }

            int best_index = errors_of_systems.IndexOf(errors_of_systems.Min());

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(Systems_ready_to_test[best_index]);
            for (int i = 0; i < count_slice_vars.Count(); i++)
            {
                count_slice_vars[i] = result.RulesDatabaseSet[0].TermsSet.Count(x => x.NumVar == i);
            }
            Console.WriteLine(Pull_of_systems.Count());
            result.RulesDatabaseSet[0].TermsSet.Trim();
            GC.Collect();

            return(result);
        }
Пример #16
0
        public void generateNewRule(TypeTermFuncEnum termType, Random rand)
        {
            int CountVaribles = Parrent.CountFeatures;

            forClass.Clear();
            numOfTerms = new int[CountVaribles];
            for (int i = 0; i < CountVaribles; i++)
            {
                double   min     = Parrent.LearnSamplesSet.InputAttributes[i].Min;
                double   max     = Parrent.LearnSamplesSet.InputAttributes[i].Max;
                double   Scatter = Parrent.LearnSamplesSet.InputAttributes[i].Scatter;
                double[] Params  = null;
                Term     newTerm = null;


                switch (termType)
                {
                case TypeTermFuncEnum.Гауссоида: { Params = generateGauss(min, max, Scatter, rand); } break;

                case TypeTermFuncEnum.Парабола: { Params = generateParabolic(min, max, Scatter, rand); } break;

                case TypeTermFuncEnum.Трапеция:
                {
                    Params = generateTrapec(min, max, Scatter, rand);
                    Params = inValidateTrapec(Params, min, max, Scatter, rand);
                }
                break;

                case TypeTermFuncEnum.Треугольник:
                {
                    Params = generateTrianlge(min, max, Scatter, rand);
                    Params = inValidateTriangle(Params, min, max, Scatter, rand);
                }
                break;
                }

                newTerm = new Term(Params, termType, i);
                forClass.Add(newTerm);
                thePositionOfBee.TermsSet.Add(newTerm);
                numOfTerms[i] = thePositionOfBee.TermsSet.Count() - 1;
            }

            makeKons(Parrent, forClass);
            thePositionOfBee.RulesDatabase.Add(theRule);
            numoFRules = thePositionOfBee.RulesDatabase.Count - 1;
        }
Пример #17
0
        /// <summary>
        /// Размер вектора параметров для заданного типа функции принадлежности.
        /// </summary>
        /// <param name="tf">Тип функции принадлежности</param>
        /// <returns>Размер вектора параметров</returns>
        public static int CountParamsinSelectedTermType(TypeTermFuncEnum tf)
        {
            switch (tf)
            {
            case TypeTermFuncEnum.Треугольник:
                return(3);

            case TypeTermFuncEnum.Гауссоида:
                return(2);

            case TypeTermFuncEnum.Парабола:
                return(2);

            case TypeTermFuncEnum.Трапеция:
                return(4);
            }
            return(0);
        }
        public override PCFuzzySystem Generate(PCFuzzySystem Classifier, IGeneratorConf config)
        {
            PCFuzzySystem result = Classifier;

            InitEveryoneWithEveryone config1 = config as InitEveryoneWithEveryone;

            type_func        = config1.IEWEFuncType;
            count_slice_vars = config1.IEWECountSlice;

            InitRulesEveryoneWithEveryone(result, type_func, count_slice_vars);

            InitRulesEveryoneWithEveryone(result, type_func, count_slice_vars);

            result.RulesDatabaseSet[0].TermsSet.Trim();


            return(result);
        }
Пример #19
0
        public void loadParams(string param)
        {
            string stemp = "";

            string[] temp = param.Split('}');


            stemp = Extention.getParamValueString(temp, "IBSTypeFunc");
            switch (stemp)
            {
            case "Triangle": IBSTypeFunc = TypeTermFuncEnum.Треугольник; break;

            case "Gauss": IBSTypeFunc = TypeTermFuncEnum.Гауссоида; break;

            case "Parabola": IBSTypeFunc = TypeTermFuncEnum.Парабола; break;

            case "Trapezium": IBSTypeFunc = TypeTermFuncEnum.Трапеция; break;

            default: IBSTypeFunc = TypeTermFuncEnum.Треугольник; break;
            }
        }
Пример #20
0
        public override TSAFuzzySystem Generate(TSAFuzzySystem Approximate, IGeneratorConf config)
        {
            ResultSystem = Approximate;
            type_func    = TypeTermFuncEnum.Гауссоида;



            var kliConf = config as KLI_conf;

            if (kliConf != null)
            {
                {
                    ResultSystem = Approximate;
                    double meanValue = ResultSystem.LearnSamplesSet.DataRows.Select(x => x.DoubleOutput).Average();

                    var mayError = kliConf.MaxValue * meanValue;
                    kliGenerate(ResultSystem, type_func, mayError);
                    //             File.AppendAllLines("./out.txt", new List<string>() { mayError + " " + Result.RulesDatabaseSet[0].ValueComplexity + " " + Result.RMSEtoMSEforLearn(Result.ErrorLearnSamples()) / 2 + " " + Result.RMSEtoMSEforTest(Result.ErrorTestSamples()) / 2 });
                }
            }
            return(ResultSystem);
        }
Пример #21
0
      public virtual void Init(int countVars)
      {
          type_term_func = (TypeTermFuncEnum)Settings.Default.Type_func_int;
          count_terms    = new int[countVars];
          for (int i = 0; i < countVars; i++)
          {
              count_terms[i] = Settings.Default.AvrCountTerms;
          }

          string temp = "";

          Array.Sort(count_terms);
          for (int i = 0; i < count_terms.Count() - 1; i++)
          {
              temp += count_terms[i].ToString() + ",";
          }
          temp += count_terms[count_terms.Count() - 1].ToString();



          IEWOCountTerms = temp;
      }
Пример #22
0
        public virtual void loadParams(string param)
        {
            string stemp = "";

            string[] temp = param.Split('}');
            ABCSCountScout   = Extention.getParamValueInt(temp, "ABCSCountScout");
            ABCSCountWorkers = Extention.getParamValueInt(temp, "ABCSCountWorkers");
            ABCSCountRules   = Extention.getParamValueInt(temp, "ABCSCountRules");
            stemp            = Extention.getParamValueString(temp, "ABCSTypeFunc");
            switch (stemp)
            {
            case "Triangle": ABCSTypeFunc = TypeTermFuncEnum.Треугольник; break;

            case "Gauss": ABCSTypeFunc = TypeTermFuncEnum.Гауссоида; break;

            case "Parabola": ABCSTypeFunc = TypeTermFuncEnum.Парабола; break;

            case "Trapezium": ABCSTypeFunc = TypeTermFuncEnum.Трапеция; break;

            default: ABCSTypeFunc = TypeTermFuncEnum.Треугольник; break;
            }
        }
Пример #23
0
        public override PCFuzzySystem Generate(PCFuzzySystem Classifier, IGeneratorConf config)
        {
            PCFuzzySystem result = Classifier;

            //Filtre(result);

            InitBySamplesConfig config1 = config as InitBySamplesConfig;

            type_func = config1.IBSTypeFunc;
            calc_min_max_for_class(result.LearnSamplesSet);

            InitRulesBySamples(Classifier, type_func);

            result.RulesDatabaseSet[0].TermsSet.Trim();

            //Chiu(result);

            //Console.WriteLine("Обуч: " + Math.Round(result.ClassifyLearnSamples(result.RulesDatabaseSet[0]), 2));
            //Console.WriteLine("Тест: " + Math.Round(result.ClassifyTestSamples(result.RulesDatabaseSet[0]), 2));
            //Console.WriteLine();

            return(result);
        }
Пример #24
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);
        }
Пример #25
0
        public static SAFuzzySystem loadUFS(this SAFuzzySystem Approx, XmlDocument Source)
        {
            SAFuzzySystem       result       = Approx;
            KnowlegeBaseSARules New_dataBase = new KnowlegeBaseSARules();
            List <string>       added_term   = new List <string>();
            XmlNode             rulles_node  = Source.DocumentElement.SelectSingleNode("descendant::Rules");

            if (rulles_node == null)
            {
                throw new System.FormatException("Нет базы правил в ufs файле");
            }
            int     count_rulles  = XmlConvert.ToInt32(rulles_node.Attributes.GetNamedItem("Count").Value);
            XmlNode varibles_node = Source.DocumentElement.SelectSingleNode("descendant::Variables");

            if (varibles_node == null)
            {
                throw new System.FormatException("Нет термов в базе правил, ошибка UFS");
            }
            for (int i = 0; i < count_rulles; i++)
            {
                XmlNode antecedent_node       = rulles_node.ChildNodes[i].SelectSingleNode("Antecedent");
                int     count_antecedent_term = XmlConvert.ToInt32(antecedent_node.Attributes.GetNamedItem("Count").Value);
                int[]   Order_term            = new int[count_antecedent_term];
                for (int j = 0; j < count_antecedent_term; j++)
                {
                    double[]         Value_temp;
                    TypeTermFuncEnum type_term = TypeTermFuncEnum.Треугольник;
                    int    num_var             = Approx.LearnSamplesSet.InputAttributes.IndexOf(Approx.LearnSamplesSet.InputAttributes.Find(x => x.Name.Equals(antecedent_node.ChildNodes[j].Attributes.GetNamedItem("Variable").Value, StringComparison.OrdinalIgnoreCase)));
                    string name_term           = antecedent_node.ChildNodes[j].Attributes.GetNamedItem("Term").Value;
                    if (added_term.Contains(name_term))
                    {
                        Order_term[j] = added_term.IndexOf(name_term);
                    }
                    else
                    {
                        XmlNode term_node = varibles_node.SelectSingleNode("descendant::Term[@Name='" + name_term + "']");
                        int     count_MB  = 0;
                        switch (term_node.Attributes.GetNamedItem("Type").Value)
                        {
                        case "Triangle": { count_MB = 3; type_term = TypeTermFuncEnum.Треугольник; break; }

                        case "Gauss": { count_MB = 2; type_term = TypeTermFuncEnum.Гауссоида; break; }

                        case "Parabolic": { count_MB = 2; type_term = TypeTermFuncEnum.Парабола; break; }

                        case "Trapezoid": { count_MB = 4; type_term = TypeTermFuncEnum.Трапеция; break; }
                        }
                        Value_temp = new double[count_MB];
                        term_node  = term_node.SelectSingleNode("Params");
                        for (int p = 0; p < count_MB; p++)
                        {
                            string tett         = term_node.ChildNodes[p].Attributes.GetNamedItem("Number").Value;
                            int    number_param = XmlConvert.ToInt32(term_node.ChildNodes[p].Attributes.GetNamedItem("Number").Value);
                            Value_temp[number_param] = XmlConvert.ToDouble(term_node.ChildNodes[p].Attributes.GetNamedItem("Value").Value);
                        }

                        Term temp_term = new Term(Value_temp, type_term, num_var);
                        New_dataBase.TermsSet.Add(temp_term);
                        added_term.Add(name_term);
                        Order_term[j] = New_dataBase.TermsSet.Count - 1;
                    }
                }

                XmlNode consequnt_node = rulles_node.ChildNodes[i].SelectSingleNode("Consequent");
                double  DoubleOutput   = XmlConvert.ToDouble(consequnt_node.Attributes.GetNamedItem("Value").Value);
                SARule  temp_rule      = new SARule(New_dataBase.TermsSet, Order_term, DoubleOutput);
                New_dataBase.RulesDatabase.Add(temp_rule);
            }
            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(New_dataBase);
            GC.Collect();
            return(result);
        }
        public static void InitRulesEveryoneWithEveryone(PCFuzzySystem Classifier, TypeTermFuncEnum typeFunc, int[] countSliceForVar)
        {
            if ((Classifier.RulesDatabaseSet == null) || (Classifier.RulesDatabaseSet.Count == 0))
            {
                KnowlegeBasePCRules temp_rules = new KnowlegeBasePCRules();
                Classifier.RulesDatabaseSet.Add(temp_rules);
            }
            int[][] position_of_terms = new int[Classifier.CountFeatures][];
            for (int i = 0; i < Classifier.CountFeatures; i++)
            {
                position_of_terms[i] = new int[countSliceForVar[i]];
                double current_value = Classifier.LearnSamplesSet.InputAttributes[i].Min;
                double coeef         = (Classifier.LearnSamplesSet.InputAttributes[i].Scatter);

                if (countSliceForVar[i] > 1)
                {
                    coeef = coeef / (countSliceForVar[i] - 1);
                }
                if (countSliceForVar[i] == 1)
                {
                    current_value = current_value + coeef * 0.5;
                    coeef        *= 1.000000001 / 2;
                }
                for (int j = 0; j < countSliceForVar[i]; j++)
                {
                    double[] parametrs = new double[Term.CountParamsinSelectedTermType(typeFunc)];
                    switch (typeFunc)
                    {
                    case TypeTermFuncEnum.Треугольник:
                        parametrs[1] = current_value;
                        parametrs[0] = parametrs[1] - coeef;
                        parametrs[2] = parametrs[1] + coeef;
                        break;

                    case TypeTermFuncEnum.Гауссоида:
                        parametrs[0] = current_value;
                        parametrs[1] = coeef / 3;

                        break;

                    case TypeTermFuncEnum.Парабола:
                        parametrs[0] = current_value - coeef;
                        parametrs[1] = current_value + coeef;

                        break;

                    case TypeTermFuncEnum.Трапеция:
                        parametrs[0] = current_value - coeef;
                        parametrs[3] = current_value + coeef;
                        parametrs[1] = parametrs[0] + 0.4 * (parametrs[3] - parametrs[0]);
                        parametrs[2] = parametrs[0] + 0.6 * (parametrs[3] - parametrs[0]);

                        break;
                    }
                    Term temp_term = new Term(parametrs, typeFunc, i);
                    if (countSliceForVar[i] > 1)
                    {
                        if ((j == 0) && (typeFunc != TypeTermFuncEnum.Гауссоида))
                        {
                            temp_term.Min -= 0.00000001 * (temp_term.Max - temp_term.Min);
                        }
                        if ((j == countSliceForVar[i] - 1) && (typeFunc != TypeTermFuncEnum.Гауссоида))
                        {
                            temp_term.Max += 0.0000001 * (temp_term.Max - temp_term.Min);
                        }
                    }
                    Classifier.RulesDatabaseSet[0].TermsSet.Add(temp_term);
                    position_of_terms[i][j] = Classifier.RulesDatabaseSet[0].TermsSet.Count - 1;

                    current_value += coeef;
                }
            }

            int first_notNull = -1;

            int[] counter = new int[Classifier.CountFeatures];
            for (int i = 0; i < Classifier.CountFeatures; i++)
            {
                if (Classifier.AcceptedFeatures[i] == false)
                {
                    continue;
                }


                counter[i] = countSliceForVar[i] - 1;
                if ((counter[i] != -1) && first_notNull == -1)
                {
                    first_notNull = i;
                }
            }

            while (counter[first_notNull] >= 0 && counter[0] >= -1)
            {
                List <Term> temp_term_set = new List <Term>();
                int[]       order         = new int[Classifier.CountFeatures];
                for (int i = 0; i < Classifier.CountFeatures; i++)
                {
                    if ((counter[i] == -1) || (Classifier.AcceptedFeatures[i] == false))
                    {
                        order[i] = -1;
                        continue;
                    }


                    temp_term_set.Add(Classifier.RulesDatabaseSet[0].TermsSet[position_of_terms[i][counter[i]]]);
                    order[i] = position_of_terms[i][counter[i]];
                }
                string class_label = KNNClassName.NearestClass(Classifier, temp_term_set);

                PCRule temp_rule = new PCRule(Classifier.RulesDatabaseSet[0].TermsSet, order, class_label, 1.0);
                Classifier.RulesDatabaseSet[0].RulesDatabase.Add(temp_rule);
                counter = dec_count(counter, countSliceForVar, Classifier.CountFeatures);
            }
        }
Пример #27
0
 /// <summary>
 /// Конструктор для создания функции принадлежности
 /// </summary>
 /// <param name="paramtrs">Вектор параметров функции принадлежности</param>
 /// <param name="type_term">Тип функции принадлежности</param>
 /// <param name="num_var">Номер входного параметра для которого определена функция принадлежности</param>
 public Term(double[] paramtrs, TypeTermFuncEnum type_term, int num_var)
 {
     Parametrs    = paramtrs;
     TermFuncType = type_term;
     NumVar       = num_var;
 }
        public override TSAFuzzySystem Generate(TSAFuzzySystem Approximate, IGeneratorConf config)
        {
            TSAFuzzySystem result = Approximate;

            Pull_of_systems       = Pull_of_systems = new List <List <int> >();
            Systems_ready_to_test = new List <KnowlegeBaseTSARules>();
            errors_of_systems     = new List <double>();

            DynamicTuneConfGenerator config1 = config as DynamicTuneConfGenerator;

            type_func = config1.IEWOTypeFunc;



            List <int> Varians_of_run_system = new List <int>();


            List <int> allOne = new List <int>();

            for (int i = 0; i < Approximate.CountFeatures; i++)
            {
                allOne.Add(1);
            }
            Pull_of_systems.Add(new List <int>(allOne));

            for (int j = 0; j < Approximate.CountFeatures - 1; j++)
            {
                Varians_of_run_system.Clear();
                allOne[j] = 2;
                Varians_of_run_system.AddRange(new List <int> (allOne));
                Varians_of_run_system.Sort();
                Generate_all_variant_in_pool(Varians_of_run_system);
            }
            allOne[Approximate.CountFeatures - 1] = 2;
            Pull_of_systems.Add(new List <int> (allOne));

            for (int i = 0; i < Pull_of_systems.Count; i++)
            {
                Approximate.RulesDatabaseSet.Clear();

                GeneratorRulesEveryoneWithEveryone.InitRulesEveryoneWithEveryone(Approximate, type_func, Pull_of_systems[i].ToArray());
                Systems_ready_to_test.Add(Approximate.RulesDatabaseSet[0]);
                errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[0]));
            }

            DynamicTuneClass dt = new DynamicTuneClass();

            Approximate = dt.TuneUpFuzzySystem(Approximate, config1);
            Systems_ready_to_test.Add(Approximate.RulesDatabaseSet[0]);
            errors_of_systems.Add(result.approxLearnSamples(result.RulesDatabaseSet[0]));


            int best_index = errors_of_systems.IndexOf(errors_of_systems.Min());

            result.RulesDatabaseSet.Clear();
            result.RulesDatabaseSet.Add(Systems_ready_to_test[best_index]);
            count_slice_vars = new int[Approximate.CountFeatures];
            for (int i = 0; i < count_slice_vars.Count(); i++)
            {
                count_slice_vars[i] = result.RulesDatabaseSet[0].TermsSet.Count(x => x.NumVar == i);
            }
            maxError  = config1.MaxError;
            TryCount  = config1.TryCount;
            RuleCount = result.RulesDatabaseSet[0].RulesDatabase.Count;
            Console.WriteLine(Pull_of_systems.Count());
            result.RulesDatabaseSet[0].TermsSet.Trim();
            GC.Collect();

            return(result);
        }
Пример #29
0
        public void kliGenerate(TSAFuzzySystem Approximate, TypeTermFuncEnum typeFunc, double mayError)
        {
            if ((Approximate.RulesDatabaseSet == null) || (Approximate.RulesDatabaseSet.Count == 0))
            {
                Approximate.RulesDatabaseSet.Add(new KnowlegeBaseTSARules());
            }
            originalSimpleSet = new List <SampleSet.RowSample>(Approximate.LearnSamplesSet.DataRows);
            originalSimpleSetDistanteToPoint = new List <double>();
            CalcFarPoint();


            int ruleIndex = 0;


            while (originalSimpleSet.Count > 0)
            {
                int IndexOfMax = originalSimpleSetDistanteToPoint.IndexOf(originalSimpleSetDistanteToPoint.Max());

                var maxPoint = originalSimpleSet[IndexOfMax];
                originalSimpleSet.Remove(maxPoint);
                originalSimpleSetDistanteToPoint.RemoveAt(IndexOfMax);

                var iterClasterPoints = new List <SampleSet.RowSample>()
                {
                    maxPoint
                };
                var mnk = new MNK()
                {
                    n = maxPoint.InputAttributeValue.Count()
                };
                var P = new Matrix(new[] { new double[] { 0 } });
                var B = new HyperVector(0, 0);

                mnk.mnkIter(iterClasterPoints.Last().InputAttributeValue.ToList(), iterClasterPoints.Last().DoubleOutput,
                            ref P, ref B, true);

                //     var errorIter = errorsMnk(B, iterClasterPoints);

                for (int z = 0; z < Approximate.CountFeatures; z++)
                {
                    int NextIndex2 = maxPoint.NearestNormalizedInputIndex(originalSimpleSet, ResultSystem.LearnSamplesSet);

                    var nextPoint2 = originalSimpleSet[NextIndex2];
                    mnk.mnkIter(nextPoint2.InputAttributeValue.ToList(), nextPoint2.DoubleOutput, ref P, ref B, false);
                    iterClasterPoints.Add(nextPoint2);
                    originalSimpleSet.Remove(nextPoint2);
                }
                var errorIter = errorsMnk(B, iterClasterPoints);


                while (errorIter < mayError)
                {
                    if (originalSimpleSet.Count < Approximate.CountFeatures)
                    {
                        while (originalSimpleSet.Count > 0)
                        {
                            int NextIndex2 = maxPoint.NearestNormalizedInputIndex(originalSimpleSet, ResultSystem.LearnSamplesSet);

                            var nextPoint2 = originalSimpleSet[NextIndex2];
                            mnk.mnkIter(nextPoint2.InputAttributeValue.ToList(), nextPoint2.DoubleOutput, ref P, ref B, false);
                            iterClasterPoints.Add(nextPoint2);
                            originalSimpleSet.Remove(nextPoint2);
                            originalSimpleSetDistanteToPoint.RemoveAt(NextIndex2);
                        }
                        break;
                    }


                    int NextIndex = maxPoint.NearestNormalizedInputIndex(originalSimpleSet, ResultSystem.LearnSamplesSet);

                    var nextPoint = originalSimpleSet[NextIndex];
                    mnk.mnkIter(nextPoint.InputAttributeValue.ToList(), nextPoint.DoubleOutput, ref P, ref B, false);
                    errorIter = errorsMnk(B, new List <SampleSet.RowSample>(iterClasterPoints)
                    {
                        nextPoint
                    });
                    if (errorIter < mayError)
                    {
                        iterClasterPoints.Add(nextPoint);
                        maxPoint = nextPoint;
                        originalSimpleSet.Remove(nextPoint);
                        originalSimpleSetDistanteToPoint.RemoveAt(NextIndex);
                    }
                }
                var         numbersRule = new List <int>();
                List <Term> forRWLSM    = new List <Term>();
                for (int i = 0; i < Approximate.CountFeatures; i++)
                {
                    var parametrs = new double[Term.CountParamsinSelectedTermType(typeFunc)];
                    parametrs[0] = iterClasterPoints.Sum(x => x.InputAttributeValue[i]) / iterClasterPoints.Count;
                    parametrs[1] =
                        Math.Sqrt(
                            iterClasterPoints.Sum(x => Math.Pow(x.InputAttributeValue[i] - parametrs[0], 2.0)) /
                            iterClasterPoints.Count);
                    if (parametrs[1] < Math.Pow(10, -300))
                    {
                        parametrs[1] = Approximate.LearnSamplesSet.InputAttributes[i].Scatter / 100.0;
                    }


                    var temp_term = new Term(parametrs, typeFunc, i);
                    forRWLSM.Add(temp_term);
                    Approximate.RulesDatabaseSet[0].TermsSet.Add(temp_term);
                    numbersRule.Add(Approximate.RulesDatabaseSet[0].TermsSet.Count - 1);
                }
                ruleIndex++;
                double[] coeffs    = null;
                double   coef      = LSMWeghtReqursiveSimple.EvaluteConsiquent(ResultSystem, forRWLSM, out coeffs);
                var      temp_rule = new TSARule(Approximate.RulesDatabaseSet[0].TermsSet, numbersRule.ToArray(), coef, coeffs);

                Approximate.RulesDatabaseSet[0].RulesDatabase.Add(temp_rule);
            }
        }
Пример #30
0
        /// <summary>
        /// Метод упращающий создание функции принадлежности. Использует значение пика (центра ) функции принадлежности, дистанцию (разброс отностительно центра), тип функции принадлежности и указание номер входной переменной
        /// </summary>
        /// <param name="center">значение пика (центра ) функции принадлежности</param>
        /// <param name="distance"> дистанция (разброс отностительно центра)</param>
        /// <param name="TypeTerm">тип функции принадлежности</param>
        /// <param name="NumVar">Номер входной переменной</param>
        /// <returns>Новая функция принадлежности</returns>
        public static Term MakeTerm(double center, double distance, TypeTermFuncEnum TypeTerm, int NumVar)
        {
            Term Result = new Term(GenTermParams(center, distance, TypeTerm), TypeTerm, NumVar);

            return(Result);
        }