Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3057_DynamicALPS/TestProblems/oesr-alps-master/HeuristicLab.Algorithms.OESRALPS/Analyzers/Regression/SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer.cs @ 18242

Last change on this file since 18242 was 17479, checked in by kyang, 5 years ago

#3057

  1. upload the latest version of ALPS with SMS-EMOA
  2. upload the related dynamic test problems (dynamic, single-objective symbolic regression), written by David Daninel.
File size: 12.8 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
7#region License Information
8/* HeuristicLab
9    * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
10    *
11    * This file is part of HeuristicLab.
12    *
13    * HeuristicLab is free software: you can redistribute it and/or modify
14    * it under the terms of the GNU General Public License as published by
15    * the Free Software Foundation, either version 3 of the License, or
16    * (at your option) any later version.
17    *
18    * HeuristicLab is distributed in the hope that it will be useful,
19    * but WITHOUT ANY WARRANTY; without even the implied warranty of
20    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    * GNU General Public License for more details.
22    *
23    * You should have received a copy of the GNU General Public License
24    * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
25    */
26#endregion
27
28using HEAL.Attic;
29using HeuristicLab.Problems.DataAnalysis.Symbolic;
30using HeuristicLab.Core;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Parameters;
33using HeuristicLab.Common;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
35using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
36using HeuristicLab.Random;
37using HeuristicLab.Data;
38using HeuristicLab.Optimization;
39
40namespace HeuristicLab.Algorithms.OESRALPS.Analyzers.Regression
41{
42    /// <summary>
43    /// An operator that analyzes the validation best symbolic regression solution for single objective symbolic regression problems.
44    /// </summary>
45    [Item("SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer", "An operator that analyzes the validation best symbolic regression solution for single objective symbolic regression problems.")]
46    [StorableType("75E2AFFF-95B2-4FA4-8544-CF202A665890")]
47    public class SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer
48        : SymbolicDataAnalysisSingleObjectiveLayerValidationAnalyzer<ISymbolicRegressionSingleObjectiveEvaluator, IRegressionProblemData>,
49        ISymbolicDataAnalysisBoundedOperator
50    {
51        private const string EstimationLimitsParameterName = "EstimationLimits";
52        private const string ValidationBestSolutionParameterName = "Best validation solution";
53        private const string ValidationBestSolutionQualityParameterName = "Best validation solution quality";
54        private const string ValidationBestSolutionGenerationParameterName = "Best validation solution generation";
55        private const string UpdateAlwaysParameterName = "Always update best solution";
56        private const string IterationsParameterName = "Generations";
57        private const string MaximumIterationsParameterName = "Maximum Iterations";
58
59        #region parameter properties
60        public IValueLookupParameter<DoubleLimit> EstimationLimitsParameter {
61            get { return (IValueLookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
62        }
63        public ILookupParameter<ISymbolicRegressionSolution> ValidationBestSolutionParameter {
64            get { return (ILookupParameter<ISymbolicRegressionSolution>)Parameters[ValidationBestSolutionParameterName]; }
65        }
66        public ILookupParameter<DoubleValue> ValidationBestSolutionQualityParameter {
67            get { return (ILookupParameter<DoubleValue>)Parameters[ValidationBestSolutionQualityParameterName]; }
68        }
69        public ILookupParameter<IntValue> ValidationBestSolutionGenerationParameter {
70            get { return (ILookupParameter<IntValue>)Parameters[ValidationBestSolutionGenerationParameterName]; }
71        }
72        public IFixedValueParameter<BoolValue> UpdateAlwaysParameter {
73            get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateAlwaysParameterName]; }
74        }
75        public ILookupParameter<IntValue> IterationsParameter {
76            get { return (ILookupParameter<IntValue>)Parameters[IterationsParameterName]; }
77        }
78        public IValueLookupParameter<IntValue> MaximumIterationsParameter {
79            get { return (IValueLookupParameter<IntValue>)Parameters[MaximumIterationsParameterName]; }
80        }
81        #endregion
82
83        #region properties
84        public ISymbolicRegressionSolution ValidationBestSolution {
85            get { return ValidationBestSolutionParameter.ActualValue; }
86            set { ValidationBestSolutionParameter.ActualValue = value; }
87        }
88        public DoubleValue ValidationBestSolutionQuality {
89            get { return ValidationBestSolutionQualityParameter.ActualValue; }
90            set { ValidationBestSolutionQualityParameter.ActualValue = value; }
91        }
92        public BoolValue UpdateAlways {
93            get { return UpdateAlwaysParameter.Value; }
94        }
95        #endregion
96
97        [StorableConstructor]
98        private SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer(StorableConstructorFlag _) : base(_) { }
99        private SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer(SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer original, Cloner cloner) : base(original, cloner) { }
100        public SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer()
101            : base()
102        {
103            Parameters.Add(new LookupParameter<ISymbolicRegressionSolution>(ValidationBestSolutionParameterName, "The validation best symbolic data analyis solution."));
104            Parameters.Add(new LookupParameter<DoubleValue>(ValidationBestSolutionQualityParameterName, "The quality of the validation best symbolic data analysis solution."));
105            Parameters.Add(new LookupParameter<IntValue>(ValidationBestSolutionGenerationParameterName, "The generation in which the best validation solution was found."));
106            Parameters.Add(new FixedValueParameter<BoolValue>(UpdateAlwaysParameterName, "Determines if the best validation solution should always be updated regardless of its quality.", new BoolValue(true)));
107            Parameters.Add(new LookupParameter<IntValue>(IterationsParameterName, "The number of performed iterations."));
108            Parameters.Add(new ValueLookupParameter<IntValue>(MaximumIterationsParameterName, "The maximum number of performed iterations.") { Hidden = true });
109            UpdateAlwaysParameter.Hidden = true;
110            Parameters.Add(new ValueLookupParameter<DoubleLimit>(EstimationLimitsParameterName, "The lower and upper limit for the estimated values produced by the symbolic regression model."));
111        }
112
113        public override IDeepCloneable Clone(Cloner cloner)
114        {
115            return new SymbolicRegressionSingleObjectiveValidationBestSolutionSlidingWindowAnalyzer(this, cloner);
116        }
117
118        protected ISymbolicRegressionSolution CreateSolution(ISymbolicExpressionTree bestTree, double bestQuality)
119        {
120            var model = new SymbolicRegressionModel(ProblemDataParameter.ActualValue.TargetVariable, (ISymbolicExpressionTree)bestTree.Clone(), SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper);
121            if (ApplyLinearScalingParameter.ActualValue.Value) model.Scale(ProblemDataParameter.ActualValue);
122            return new SymbolicRegressionSolution(model, (IRegressionProblemData)ProblemDataParameter.ActualValue.Clone());
123        }
124
125        protected override IEnumerable<int> GenerateRowsToEvaluate()
126        {
127            if (ValidationPartitionParameter.ActualValue == null
128                || TestPartitionParameter.ActualValue == null)
129                return base.GenerateRowsToEvaluate();
130
131            int seed = RandomParameter.ActualValue.Next();
132            int samplesStart = ValidationPartitionParameter.ActualValue.Start;
133            int samplesEnd = ValidationPartitionParameter.ActualValue.End;
134            int testPartitionStart = TestPartitionParameter.ActualValue.Start;
135            int testPartitionEnd = TestPartitionParameter.ActualValue.End;
136
137            if (samplesEnd < samplesStart) throw new ArgumentException("Start value is larger than end value.");
138            int count = (int)((samplesEnd - samplesStart) * RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value);
139            if (count == 0) count = 1;
140            return RandomEnumerable.SampleRandomNumbers(seed, samplesStart, samplesEnd, count)
141                .Where(i => i < testPartitionStart && i < ProblemDataParameter.ActualValue.Dataset.Rows);
142        }
143
144        public override IOperation Apply()
145        {
146            IEnumerable<int> rows = GenerateRowsToEvaluate();
147            if (!rows.Any()) return base.Apply();
148
149            #region find best tree
150            var evaluator = EvaluatorParameter.ActualValue;
151            var problemData = ProblemDataParameter.ActualValue;
152            double bestValidationQuality = Maximization.Value ? double.NegativeInfinity : double.PositiveInfinity;
153            ISymbolicExpressionTree bestTree = null;
154            ISymbolicExpressionTree[] tree = SymbolicExpressionTree.ToArray();
155
156            // sort is ascending and we take the first n% => order so that best solutions are smallest
157            // sort order is determined by maximization parameter
158            double[] trainingQuality;
159            if (Maximization.Value)
160            {
161                // largest values must be sorted first
162                trainingQuality = Quality.Select(x => -x.Value).ToArray();
163            }
164            else
165            {
166                // smallest values must be sorted first
167                trainingQuality = Quality.Select(x => x.Value).ToArray();
168            }
169
170            // sort trees by training qualities
171            Array.Sort(trainingQuality, tree);
172
173            // number of best training solutions to validate (at least 1)
174            int topN = (int)Math.Max(tree.Length * PercentageOfBestSolutionsParameter.ActualValue.Value, 1);
175
176            IExecutionContext childContext = (IExecutionContext)ExecutionContext.CreateChildOperation(evaluator);
177            // evaluate best n training trees on validiation set
178            var quality = tree
179              .Take(topN)
180              .Select(t => evaluator.Evaluate(childContext, t, problemData, rows))
181              .ToArray();
182
183            for (int i = 0; i < quality.Length; i++)
184            {
185                if (IsBetter(quality[i], bestValidationQuality, Maximization.Value))
186                {
187                    bestValidationQuality = quality[i];
188                    bestTree = tree[i];
189                }
190            }
191            #endregion
192
193            var results = ResultCollection;
194            if (bestTree != null && (UpdateAlways.Value || ValidationBestSolutionQuality == null ||
195              IsBetter(bestValidationQuality, ValidationBestSolutionQuality.Value, Maximization.Value)))
196            {
197                ValidationBestSolution = CreateSolution(bestTree, bestValidationQuality);
198                ValidationBestSolutionQuality = new DoubleValue(bestValidationQuality);
199                if (IterationsParameter.ActualValue != null)
200                    ValidationBestSolutionGenerationParameter.ActualValue = new IntValue(IterationsParameter.ActualValue.Value);
201
202                if (!results.ContainsKey(ValidationBestSolutionParameter.Name))
203                {
204                    results.Add(new Result(ValidationBestSolutionParameter.Name, ValidationBestSolutionParameter.Description, ValidationBestSolution));
205                    results.Add(new Result(ValidationBestSolutionQualityParameter.Name, ValidationBestSolutionQualityParameter.Description, ValidationBestSolutionQuality));
206                    if (ValidationBestSolutionGenerationParameter.ActualValue != null)
207                        results.Add(new Result(ValidationBestSolutionGenerationParameter.Name, ValidationBestSolutionGenerationParameter.Description, ValidationBestSolutionGenerationParameter.ActualValue));
208                }
209                else
210                {
211                    results[ValidationBestSolutionParameter.Name].Value = ValidationBestSolution;
212                    results[ValidationBestSolutionQualityParameter.Name].Value = ValidationBestSolutionQuality;
213                    if (ValidationBestSolutionGenerationParameter.ActualValue != null)
214                        results[ValidationBestSolutionGenerationParameter.Name].Value = ValidationBestSolutionGenerationParameter.ActualValue;
215                }
216            }
217            return base.Apply();
218        }
219        private bool IsBetter(double lhs, double rhs, bool maximization)
220        {
221            if (maximization) return lhs > rhs;
222            else return lhs < rhs;
223        }
224    }
225}
226
Note: See TracBrowser for help on using the repository browser.