Beispiel #1
0
        public static double getGICSumReverce(this TSAFuzzySystem source, int indexDataBase = 0)
        {
            double result = 0.0;


            if (source != null)
            {
                double temp = 0;
                for (int i = 0; i < source.CountFeatures; i++)
                {
                    temp = 0.0;
                    List <Term> termList = source.RulesDatabaseSet[indexDataBase].TermsSet.Where(x => x.NumVar == i).ToList();
                    if (termList.Count() <= 1)
                    {
                        temp = 0.0;
                    }
                    else
                    {
                        for (int j = 0; j < termList.Count; j++)
                        {
                            for (int k = j + 1; k < termList.Count; k++)
                            {
                                temp += 1.0 - TermOnterpreting.getIndexByCentersClose(termList[j], termList[k], termList.Count(), source.LearnSamplesSet.InputAttributes[i].Scatter);
                            }
                        }
                    }
                    result += temp;
                }
                result = result / (double)source.CountFeatures;
            }
            return(result);
        }
Beispiel #2
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approximate, ILearnAlgorithmConf conf)
        {
            if (Approximate.RulesDatabaseSet.Count == 0)
            {
                throw new InvalidOperationException("Нечеткая система не была корректно инициализированна");
            }
            KnowlegeBaseTSARules newBase = new KnowlegeBaseTSARules(Approximate.RulesDatabaseSet[0]);


            double result_before = Approximate.approxLearnSamples(newBase);

            foreach (TSARule Rule in newBase.RulesDatabase)
            {
                double [] coefficient = null;
                double    Value       = LSMWeghtReqursiveSimple.EvaluteConsiquent(Approximate, Rule.ListTermsInRule, out coefficient);
                Rule.IndependentConstantConsequent = Value;
                Rule.IndependentConstantConsequent = Value;
                Rule.RegressionConstantConsequent  = coefficient;
            }

            double result_after = Approximate.approxLearnSamples(newBase);

            if (result_before > result_after)
            {
                Approximate.RulesDatabaseSet[0] = newBase;
            }
            GC.Collect();
            Approximate.RulesDatabaseSet[0].TermsSet.Trim();
            return(Approximate);
        }
Beispiel #3
0
        public static double getGISSumReverce(this TSAFuzzySystem source, double goodsForArea = 0, int indexDataBase = 0)
        {
            double result = 0.0;

            if (goodsForArea == 0)
            {
                goodsForArea = FuzzyCore.Properties.Settings.Default.Pareto_simpler_UnionTerms_bySqarePercent * 0.01;
            }
            if (source != null)
            {
                double temp = 0.0;
                for (int i = 0; i < source.CountFeatures; i++)
                {
                    temp = 0.0;
                    List <Term> termList = source.RulesDatabaseSet[indexDataBase].TermsSet.Where(x => x.NumVar == i).ToList();
                    if (termList.Count() <= 1)
                    {
                        temp = 0.0;
                    }
                    else
                    {
                        for (int j = 0; j < termList.Count; j++)
                        {
                            for (int k = j + 1; k < termList.Count; k++)
                            {
                                temp += 1 - TermOnterpreting.getIndexByAreaTerms(termList[j], termList[k], goodsForArea);
                            }
                        }
                    }
                    result += temp;
                }
                result = result / (double)source.CountFeatures;
            }
            return(result);
        }
Beispiel #4
0
        private TSAFuzzySystem BreakCrossTerm(TSAFuzzySystem Approx, int Feature, int indexATerm, int indexBterm, int dataBase)
        {
            TSAFuzzySystem       result     = Approx;
            KnowlegeBaseTSARules DataSet    = result.RulesDatabaseSet[dataBase];
            List <Term>          soureTerms = DataSet.TermsSet.Where(x => x.NumVar == Feature).ToList();
            Term ATerm = soureTerms[indexATerm];
            Term BTerm = soureTerms[indexBterm];

            Term Left  = ATerm;
            Term Right = BTerm;

            if (ATerm.Pick > BTerm.Pick)
            {
                Left  = BTerm;
                Right = ATerm;
            }



            double border = (Left.Max + Right.Min) / 2;

            Left.Max  = border;
            Right.Min = border;

            result.RulesDatabaseSet[dataBase] = DataSet;


            return(result);
        }
Beispiel #5
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approx, ILearnAlgorithmConf conf)
        {
            TSAFuzzySystem result        = Approx;
            double         minValue      = 5;
            int            minFeature    = 0;
            int            minATerm      = 0;
            int            minBTerm      = 1;
            int            indexDatabase = 0;

            for (int i = 0; i < result.CountFeatures; i++)
            {
                List <Term> soureceByFeature = result.RulesDatabaseSet[indexDatabase].TermsSet.Where(x => x.NumVar == i).ToList();
                for (int j = 0; j < soureceByFeature.Count(); j++)
                {
                    for (int k = j + 1; k < soureceByFeature.Count(); k++)
                    {
                        double temp = TermOnterpreting.getIndexByLinds(soureceByFeature[j], soureceByFeature[k], soureceByFeature);
                        if (temp < minValue)
                        {
                            minValue   = temp;
                            minATerm   = j;
                            minBTerm   = k;
                            minFeature = i;
                        }
                    }
                }
            }
            result = BreakCrossTerm(result, minFeature, minATerm, minBTerm, indexDatabase);
            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
Beispiel #6
0
        public virtual void oneIterate(TSAFuzzySystem result)
        {
            foreach (Colony colony in colonyList)      //Шаг 9. Если имеется следующая колония, то сделать текущим первого муравья в этой колонии и перейти на шаг 5, иначе перейти на шаг 10.
            {
                for (int i = 0; i < ACO_antCount; i++) //Шаг 8. Если в текущей колонии имеется следующий муравей, то сделать его текущим и перейти к шагу 5, иначе перейти на шаг 9.
                {
                    // Шаг 5. Для текущего муравья текущей колонии вычислить номер l, используемой функции Гаусса по формуле 2.14. Определить  l i для i = 1, ..., N по формуле 2.15. Сгенерировать N случайных величин {θl*1, θl*2,…, θl*N} на основе полученных функций gl i(x).
                    colony.runAnt(i, rand, ACO_xi);

                    //Шаг 6.  Найти ошибку вывода нечеткой системы при параметрах {θ1,…, θN }, если ошибка меньше текущей, то сохранить новые параметры.
                    baseError = colony.checkAntDecision(i, baseError);

                    // Шаг 7. Добавить в архив новое решение, ранжировать архив, удалить из архива худшее решение.
                    colony.updateDecisionArchive(i);
                }
            }
            // Шаг. * Модифицированный алгоритм. Проверяем находиться ли в экстремуме алгоритм.
            if (isInExtremum())
            {
                foreach (Colony colony in colonyList)    //Шаг **. Обновляем архивы, заполняем их случайными решениями и элитными
                {
                    colony.refillDesicionArchive(MACOCountEliteDecision - 1, rand, this);
                }
            }
        }
Beispiel #7
0
        public static double getLindisSumReverse(this TSAFuzzySystem source, int indexDataBase = 0)
        {
            double result = 0.0;

            if (source != null)
            {
                double temp = 0.0;
                for (int i = 0; i < source.CountFeatures; i++)
                {
                    temp = 0.0;
                    List <Term> termList = source.RulesDatabaseSet[indexDataBase].TermsSet.Where(x => x.NumVar == i).ToList();
                    if (termList.Count() <= 1)
                    {
                        temp = 0.0;
                    }
                    else
                    {
                        for (int j = 0; j < termList.Count; j++)
                        {
                            for (int k = j + 1; k < termList.Count; k++)
                            {
                                temp += 1 - TermOnterpreting.getIndexByLinds(termList[j], termList[k], termList);
                            }
                        }
                    }
                    result += temp;
                }
                result = result / (double)source.CountFeatures;
            }
            return(result);
        }
Beispiel #8
0
        public void GetDots(TSAFuzzySystem approx, KnowlegeBaseTSARules knowlegeBase)
        {
            // Dots (COMPLETE, BUT DOUBLECHECK WHEN DEBUGGING)
            var inputs = approx.LearnSamplesSet.DataRows.AsParallel().AsOrdered()
                         .Select(dataRow => dataRow.InputAttributeValue).ToList();
            var localDots = inputs.AsParallel().AsOrdered()
                            .Where(InBetweenTheLimits).ToList();
            //  var strs = new List<string[]>(localDots.Count);
            //  for (int i = 0; i < strs.Capacity; i++)
            //    strs.Add(new[] { string.Empty });

            var rezs = approx.LearnSamplesSet.DataRows.AsParallel().AsOrdered()
                       .Where(row => localDots.Contains(row.InputAttributeValue))
                       .Select(dataRow => dataRow.DoubleOutput).ToList();

            List <SampleSet.RowSample> rows = localDots.Select((t, i) => new SampleSet.RowSample(t, null, rezs[i], null)).ToList();

            var samples = new SampleSet("1.dat", rows, approx.LearnSamplesSet.InputAttributes, approx.LearnSamplesSet.OutputAttribute);

            system = new TSAFuzzySystem(samples, samples);

            var usedRules = GetRules(knowlegeBase);

            system.RulesDatabaseSet.Add(new KnowlegeBaseTSARules(knowlegeBase, null));
        }
Beispiel #9
0
        public static TSAFuzzySystem loadUFS(this TSAFuzzySystem Approx, string fileName)
        {
            XmlDocument Source = new XmlDocument();

            Source.Load(fileName);
            return(Approx.loadUFS(Source));
        }
Beispiel #10
0
 private static void writeAboutRules(XmlWriter writer, TSAFuzzySystem Approximate)
 {
     writer.WriteStartElement("Rules");
     writer.WriteAttributeString("Count", XmlConvert.ToString(Approximate.RulesDatabaseSet[0].RulesDatabase.Count));
     foreach (TSARule rule in Approximate.RulesDatabaseSet[0].RulesDatabase)
     {
         writer.WriteStartElement("Rule");
         writer.WriteStartElement("Antecedent");
         writer.WriteAttributeString("Count", XmlConvert.ToString(rule.ListTermsInRule.Count));
         foreach (Term term in rule.ListTermsInRule)
         {
             writer.WriteStartElement("Pair");
             writer.WriteAttributeString("Variable", Approximate.LearnSamplesSet.InputAttributes[term.NumVar].Name);
             writer.WriteAttributeString("Term", XmlConvert.ToString(Approximate.RulesDatabaseSet[0].TermsSet.IndexOf(term)));
             writer.WriteEndElement();
         }
         writer.WriteEndElement();
         writer.WriteStartElement("Consequent");
         writer.WriteAttributeString("Count", XmlConvert.ToString(rule.RegressionConstantConsequent.Length + 1));
         writer.WriteStartElement("Pair");
         writer.WriteAttributeString("Variable", "IndependentValue");
         writer.WriteAttributeString("Value", XmlConvert.ToString(rule.IndependentConstantConsequent));
         writer.WriteEndElement();
         for (int i = 0; i < rule.RegressionConstantConsequent.Length; i++)
         {
             writer.WriteStartElement("Pair");
             writer.WriteAttributeString("Variable", Approximate.LearnSamplesSet.InputAttributes[i].Name);
             writer.WriteAttributeString("Coefficient", XmlConvert.ToString(rule.RegressionConstantConsequent[i]));
             writer.WriteEndElement();
         }
         writer.WriteEndElement();
         writer.WriteEndElement();
     }
     writer.WriteEndElement();
 }
Beispiel #11
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approximate, ILearnAlgorithmConf conf)
        {
            BacteryAlgorithmConfig Config = conf as BacteryAlgorithmConfig;

            sendBactery    = Config.BFOCountSolution;
            interPSOtoSend = Config.BFOCountIteration;
            result         = Approximate;


            if (result.RulesDatabaseSet.Count < 1)
            {
                throw new InvalidDataException("Нечеткая система не проинициализированна");
            }
            KnowlegeBaseTSARules backSave = new KnowlegeBaseTSARules(result.RulesDatabaseSet[0]);
            double backResult             = result.approxLearnSamples(result.RulesDatabaseSet[0]);

            savetoUFS(result.RulesDatabaseSet, 0, 0, 0);
            BacteryRunner();
            KnowlegeBaseTSARules[] solutions = loadDatabase();
            solutions = sortSolution(solutions);
            if (solutions.Count() < 1)
            {
                result.RulesDatabaseSet[0] = backSave; return(result);
            }
            result.RulesDatabaseSet[0] = solutions[0];
            double newResult = result.approxLearnSamples(result.RulesDatabaseSet[0]);

            if (newResult > backResult)
            {
                result.RulesDatabaseSet[0] = backSave;
            }

            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
Beispiel #12
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approx, ILearnAlgorithmConf conf)
        {
            TSAFuzzySystem result = Approx;
            BeeParamsConf  Config = conf as BeeParamsConf;

            Init(Config);
            theFuzzySystem = result;

            if (result.RulesDatabaseSet.Count < 1)
            {
                throw (new Exception("Что то не так с базой правил"));
            }
            theHive = new HiveParams(this, result.RulesDatabaseSet[0]);
            //  HiveParams theHive = new ParallelHiveParams(this, result.RulesDatabaseSet[0]);
            // HiveParams theHive = new HiveParallelParams2(this, result.RulesDatabaseSet[0]);

            theBest = new BeeParams(result.RulesDatabaseSet[0], this);
            double temperature = initTemp;

            for (int r = 0; r < iterration; r++)
            {
                temperature = oneIterate(temperature);
                GC.Collect();
            }
            theBest = lastStep(theBest);
            Approx.RulesDatabaseSet[0] = theBest.PositionOfBee;
            Approx.RulesDatabaseSet[0].TermsSet.Trim();
            return(Approx);
        }
Beispiel #13
0
        protected static void writeAboutVariblesAndTerms(XmlWriter writer, TSAFuzzySystem Approximate)
        {
            writer.WriteStartElement("Variables");
            writer.WriteAttributeString("Count", XmlConvert.ToString(Approximate.CountFeatures));
            for (int i = 0; i < Approximate.CountFeatures; i++)
            {
                if (Approximate.AcceptedFeatures[i] == false)
                {
                    continue;
                }
                writer.WriteStartElement("Variable");
                writer.WriteAttributeString("Name", Approximate.LearnSamplesSet.InputAttributes[i].Name);
                writer.WriteAttributeString("Min",
                                            XmlConvert.ToString(Approximate.LearnSamplesSet.InputAttributes[i].Min));
                writer.WriteAttributeString("Max",
                                            XmlConvert.ToString(Approximate.LearnSamplesSet.InputAttributes[i].Max));
                List <Term> terms_for_varrible =
                    Approximate.RulesDatabaseSet[0].TermsSet.Where(x => x.NumVar == i).ToList();
                writer.WriteStartElement("Terms");
                writer.WriteAttributeString("Count", XmlConvert.ToString(terms_for_varrible.Count));

                foreach (var term in terms_for_varrible)
                {
                    BaseUFSWriter.writeAboutTerm(writer, Approximate.RulesDatabaseSet[0].TermsSet.IndexOf(term), term);
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Beispiel #14
0
        public double Calc_Error(TSAFuzzySystem error_checker)
        {
            Individ temp_Best = null;
            double  min_error = double.PositiveInfinity;

            foreach (Individ indiv in the_popualate)
            {
                indiv.calc_Error(error_checker);
                if (min_error > indiv.error)
                {
                    min_error = indiv.error;
                    temp_Best = indiv;
                }
            }


            if (temp_Best != null)
            {
                if (best_individ != null)
                {
                    if (temp_Best.error > best_individ.error)
                    {
                        best_individ = temp_Best;
                    }
                }
                else
                {
                    best_individ = temp_Best;
                }
            }


            return(min_error);
        }
        public override TSAFuzzySystem Generate(TSAFuzzySystem Approximate, IGeneratorConf config)
        {
            TSAFuzzySystem result = Approximate;

            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 < 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(Approximate, 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());



            GC.Collect();
//            result.UnlaidProtectionFix();
            result.RulesDatabaseSet[0].TermsSet.Trim();
            return(result);
        }
Beispiel #16
0
        public virtual void Init(ILearnAlgorithmConf conf)
        {
            currentConf     = conf as GeneticConf;
            fullFuzzySystem = result;
            step            = 0;
            errorAfter      = 0;
            errorBefore     = result.approxLearnSamples(result.RulesDatabaseSet[0]);
            backUp          = result.RulesDatabaseSet[0];

            initFunc = new initFuncType(localInit);
            if (currentConf.GENCTypeInit == GeneticConf.Alg_Init_Type.Глобальный)
            {
                initFunc = new initFuncType(globalInit);
            }

            crossoverFunc = new crossoverFuncType(unifiedCrossover);
            if (currentConf.GENCTypeCrossover == GeneticConf.Alg_Crossover_Type.Многоточечный)
            {
                crossoverFunc = new crossoverFuncType(pointsCrossover);
            }

            selectionFunc = new selectionFuncType(rouletteSelection);
            if (currentConf.GENCTypeSelection == GeneticConf.Alg_Selection_Type.Случайный)
            {
                selectionFunc = new selectionFuncType(randomSelection);
            }
            if (currentConf.GENCTypeSelection == GeneticConf.Alg_Selection_Type.Элитарный)
            {
                selectionFunc = new selectionFuncType(eliteSelection);
            }
            fullInit(); // Здесь проходит инициализация
        }
Beispiel #17
0
 public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approx, ILearnAlgorithmConf conf)
 {
     result = Approx;
     groups = new List <int[]>();
     Init(conf);
     SetPopulation();
     Population = ListTakagiSugenoApproximateTool.SortRules(Population, result);
     NS         = new int[m];
     for (int i = 0; i < m; i++)
     {
         NS[i] = (N - 1) / m;
     }
     cur_iter = 0;
     while (cur_iter < iter)
     {
         groups = GroupStream();
         if (p_one > rand.NextDouble())
         {
             ChooseOneCluster();
         }
         else
         {
             ChooseTwoClusters();
         }
         //
         Population = ListTakagiSugenoApproximateTool.SortRules(Population, result);
         Console.WriteLine(cur_iter + " - Итерация");
         Console.WriteLine("Обуч. выборка = " + result.ErrorLearnSamples(Population[0]));
         Console.WriteLine("Тест. выборка = " + result.ErrorTestSamples(Population[0]));
         cur_iter++;
     }
     Population = ListTakagiSugenoApproximateTool.SortRules(Population, result);
     result.RulesDatabaseSet[0] = Population[0];
     return(result);
 }
Beispiel #18
0
        public override TSAFuzzySystem TuneUpFuzzySystem(TSAFuzzySystem Approx, ILearnAlgorithmConf conf)
        {
            try
            {
                ACOSearchConf config = conf as ACOSearchConf;

                if (preCheck(Approx) == false)
                {
                    throw new ArgumentNullException("Не правильно инициализированная нечеткая система");
                }

                // Шаг 1. Задать начальные параметры.
                init(Approx, config);

                // Шаг 2. Сгенерировать популяцию муравьев в колониях
                colonyGenerate();


                Parallel.ForEach(colonyList, colony =>
                {
                    // Шаг 3. Сгенерировать k случайных решений, для всех архивов решений с последующим  оцениванием и ранжированием.
                    randomDecisionsGenerate(colony);

                    //Шаг 4. Найти значения вектора весов.
                    calc_decisions_Weight(colony);
                }
                                 );



                for (int iterNum = 0; iterNum < ACO_iterationCount; iterNum++)
                {
                    foreach (Colony colony in colonyList)      //Шаг 9. Если имеется следующая колония, то сделать текущим первого муравья в этой колонии и перейти на шаг 5, иначе перейти на шаг 10.
                    {
                        for (int i = 0; i < ACO_antCount; i++) //Шаг 8. Если в текущей колонии имеется следующий муравей, то сделать его текущим и перейти к шагу 5, иначе перейти на шаг 9.
                        {
                            // Шаг 5. Для текущего муравья текущей колонии вычислить номер l, используемой функции Гаусса по формуле 2.14. Определить  l i для i = 1, ..., N по формуле 2.15. Сгенерировать N случайных величин {θl*1, θl*2,…, θl*N} на основе полученных функций gl i(x).
                            colony.runAnt(i, rand, ACO_xi);

                            //Шаг 6.  Найти ошибку вывода нечеткой системы при параметрах {θ1,…, θN }, если ошибка меньше текущей, то сохранить новые параметры.
                            baseError = colony.checkAntDecision(i, baseError);

                            // Шаг 7. Добавить в архив новое решение, ранжировать архив, удалить из архива худшее решение.
                            colony.updateDecisionArchive(i);
                        }
                    }
                }



                prepareFinalFuzzySystem();
                result.RulesDatabaseSet[0].TermsSet.Trim();
                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #19
0
 public TSAFuzzySystemWithErrorKnowledgeBase(TSAFuzzySystem Source) : base(Source)
 {
     RulesDatabaseSet = new List <KnowlegeBaseTSARules>();
     for (int i = 0; i < Source.RulesDatabaseSet.Count; i++)
     {
         RulesDatabaseSet.Add(new KnowlegeBaseTSARulesWithError(Source.RulesDatabaseSet[i]));
     }
 }
Beispiel #20
0
 public region2(List <region_side> sides, TSAFuzzySystem approx, List <input_space> variable_spaces)
 {
     this.sides = new List <region_side>(sides.Count);
     this.sides.AddRange(sides);
     this.approx = approx;
     get_dots(approx.LearnSamplesSet.DataRows);
     this.variable_spaces = variable_spaces;
 }
        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);
        }
Beispiel #22
0
 public virtual void oneIterate(TSAFuzzySystem result)
 {
     fullCrossover();              // здесь проходит скрещивание
     mutationAlg();                // здесь проходит мутация
     fullSelection();              //здесь проходит селекция
     step = findMinErrorElement(); // поиск лучшей базы знаний
     result.RulesDatabaseSet[0] = new KnowlegeBaseTSARules(result.RulesDatabaseSet[step]);
     result.RulesDatabaseSet.RemoveRange(1, (result.RulesDatabaseSet.Count - 1));
 }
Beispiel #23
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);
        }
Beispiel #24
0
        protected override void init(TSAFuzzySystem Approx, ACOSearchConf config)
        {
            base.init(Approx, config);
            MACOSearchConf configNew = config as MACOSearchConf;

            MACOCountBorderRepeat  = configNew.MACOCountExtremum;
            MACOCountRepeatError   = 0;
            MACOCurrentError       = getError();
            MACOCountEliteDecision = configNew.MACOCountElite;
        }
Beispiel #25
0
        public static double getRulesCount(this TSAFuzzySystem source, int indexDataBase = 0)
        {
            double result = 0;

            if (source != null)
            {
                result += source.RulesDatabaseSet[indexDataBase].RulesDatabase.Count();
            }
            return(result);
        }
Beispiel #26
0
 public override string ToString(bool with_param = false)
 {
     if (with_param)
     {
         string result = "Brain Storm Algorithm" + "{" + Environment.NewLine;
         result = "Итераций = " + iter + ";" + Environment.NewLine;
         result = "Идей = " + N + ";" + Environment.NewLine;
         return(result);
     }
     return("Brain Storm Algorithm");
 }
Beispiel #27
0
        public virtual void oneIterate(TSAFuzzySystem result)
        {
            for (int j = 0; j < count_particle; j++)
            {
                w = 1 / (1 + Math.Exp(-(Errors[j] - OldErrors[j]) / 0.01));
                for (int k = 0; k < X[j].TermsSet.Count; k++)
                {
                    for (int q = 0; q < X[j].TermsSet[k].CountParams; q++)
                    {
                        double bp = Pi[j].TermsSet[k].Parametrs[q];
                        V[j].TermsSet[k].Parametrs[q] = V[j].TermsSet[k].Parametrs[q] * w + c1 * rnd.NextDouble() * (bp - X[j].TermsSet[k].Parametrs[q]) +
                                                        c2 * rnd.NextDouble() * (Pg.TermsSet[k].Parametrs[q] - X[j].TermsSet[k].Parametrs[q]);
                        X[j].TermsSet[k].Parametrs[q] += V[j].TermsSet[k].Parametrs[q];
                    }
                }
                double[] bf  = new double[V[j].all_conq_of_rules.Length];
                double[] bfw = new double[V[j].all_conq_of_rules.Length];
                for (int k = 0; k < V[j].all_conq_of_rules.Length; k++)
                {
                    bfw[k] = V[j].all_conq_of_rules[k] * w + c1 * rnd.NextDouble() * (Pi[j].all_conq_of_rules[k] - X[j].all_conq_of_rules[k]) +
                             c2 * rnd.NextDouble() * (Pg.all_conq_of_rules[k] - X[j].all_conq_of_rules[k]);
                    double sw = X[j].all_conq_of_rules[k] + bfw[k];
                    bf[k] = sw;
                }
                X[j].all_conq_of_rules = bf;
                V[j].all_conq_of_rules = bfw;
                double newError = 0;
                result.RulesDatabaseSet.Add(X[j]);
                int  temp_index = result.RulesDatabaseSet.Count - 1;
                bool success    = true;
                try
                {
                    newError = result.approxLearnSamples(result.RulesDatabaseSet[temp_index]);
                }
                catch (Exception)
                {
                    success = false;
                }
                result.RulesDatabaseSet.RemoveAt(temp_index);
                if (success && (newError < Errors[j]))
                {
                    OldErrors[j] = Errors[j];
                    Errors[j]    = newError;

                    Pi[j] = new KnowlegeBaseTSARules(X[j]);
                }
                if (minError > newError)
                {
                    minError = newError;
                    Pg       = new KnowlegeBaseTSARules(X[j]);
                }
            }
        }
Beispiel #28
0
        private TSAFuzzySystem UniTerm(TSAFuzzySystem Approx, int Feature, int indexATerm, int indexBterm, int dataBase)
        {
            TSAFuzzySystem       result     = Approx;
            KnowlegeBaseTSARules DataSet    = result.RulesDatabaseSet[dataBase];
            List <Term>          soureTerms = DataSet.TermsSet.Where(x => x.NumVar == Feature).ToList();
            Term   ATerm   = soureTerms[indexATerm];
            Term   BTerm   = soureTerms[indexBterm];
            double newPick = (ATerm.Pick + BTerm.Pick) / 2;
            double newMin  = ATerm.Min;

            if (BTerm.Min < newMin)
            {
                newMin = BTerm.Min;
            }
            double newMax = ATerm.Max;

            if (BTerm.Max > newMax)
            {
                newMax = BTerm.Max;
            }

            Term uniTerm = new Term(ATerm);

            uniTerm.Pick = newPick;
            uniTerm.Min  = newMin;
            uniTerm.Max  = newMax;

            DataSet.TermsSet.Add(uniTerm);

            List <TSARule> toChangeArules = DataSet.RulesDatabase.Where(x => x.ListTermsInRule.Contains(ATerm)).ToList();

            for (int i = 0; i < toChangeArules.Count(); i++)
            {
                int indexofA = toChangeArules[i].ListTermsInRule.IndexOf(ATerm);
                toChangeArules[i].ListTermsInRule[indexofA] = uniTerm;
            }
            DataSet.TermsSet.Remove(ATerm);


            List <TSARule> toChangeBrules = DataSet.RulesDatabase.Where(x => x.ListTermsInRule.Contains(BTerm)).ToList();

            for (int i = 0; i < toChangeBrules.Count(); i++)
            {
                int indexofB = toChangeBrules[i].ListTermsInRule.IndexOf(BTerm);
                toChangeBrules[i].ListTermsInRule[indexofB] = uniTerm;
            }
            DataSet.TermsSet.Remove(BTerm);

            result.RulesDatabaseSet[dataBase] = DataSet;


            return(result);
        }
Beispiel #29
0
        public override string ToString(bool with_param = false)
        {
            if (with_param)
            {
                string result = "Алгоритм перемещения бактерии {";
                result += "Итераций= " + interPSOtoSend.ToString() + " ;" + Environment.NewLine;
                result += "Количество различных решений= " + sendBactery.ToString() + " ;" + Environment.NewLine;
                result += "}";
            }

            return("Алгоритм перемещения бактерии");
        }
Beispiel #30
0
        internal static List <KnowlegeBaseTSARules> WeedsRegenerateIteration(TSAFuzzySystem fuzzy, KnowlegeBaseTSARules b, double delta, Random rand, int count)
        {
            var rez = new List <KnowlegeBaseTSARules>();

            for (int k = 0; k < count; k++)
            {
                var bforedit = new KnowlegeBaseTSARules(b);
                bforedit.error = fuzzy.ErrorLearnSamples(bforedit);
                rez.Add(bforedit);
            }
            return(rez);
        }