Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer.cs @ 8168

Last change on this file since 8168 was 8126, checked in by gkronber, 12 years ago

#1823 fixed a bug in the Pareto-best solution analyzers for symbolic data analysis. Fixed a minor bug in the calculation of classification thresholds, made a sneaky change in SymbolicExpressionTree

File size: 10.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using System;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  /// <summary>
36  /// An operator that collects the Pareto-best symbolic data analysis solutions for single objective symbolic data analysis problems.
37  /// </summary>
38  [Item("SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer", "An operator that analyzes the Pareto-best symbolic data analysis solution for single objective symbolic data analysis problems.")]
39  [StorableClass]
40  public abstract class SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer<S, T, U> : SymbolicDataAnalysisSingleObjectiveValidationAnalyzer<T, U>
41    where S : class, ISymbolicDataAnalysisSolution
42    where T : class, ISymbolicDataAnalysisSingleObjectiveEvaluator<U>
43    where U : class, IDataAnalysisProblemData {
44    private const string ValidationBestSolutionsParameterName = "Best validation solutions";
45    private const string ValidationBestSolutionQualitiesParameterName = "Best validation solution qualities";
46    private const string ComplexityParameterName = "Complexity";
47
48    public override bool EnabledByDefault {
49      get { return false; }
50    }
51
52    #region parameter properties
53    public ILookupParameter<ItemList<S>> ValidationBestSolutionsParameter {
54      get { return (ILookupParameter<ItemList<S>>)Parameters[ValidationBestSolutionsParameterName]; }
55    }
56    public ILookupParameter<ItemList<DoubleArray>> ValidationBestSolutionQualitiesParameter {
57      get { return (ILookupParameter<ItemList<DoubleArray>>)Parameters[ValidationBestSolutionQualitiesParameterName]; }
58    }
59    public IScopeTreeLookupParameter<DoubleValue> ComplexityParameter {
60      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters[ComplexityParameterName]; }
61    }
62    #endregion
63    #region properties
64    public ItemList<S> ValidationBestSolutions {
65      get { return ValidationBestSolutionsParameter.ActualValue; }
66      set { ValidationBestSolutionsParameter.ActualValue = value; }
67    }
68    public ItemList<DoubleArray> ValidationBestSolutionQualities {
69      get { return ValidationBestSolutionQualitiesParameter.ActualValue; }
70      set { ValidationBestSolutionQualitiesParameter.ActualValue = value; }
71    }
72    #endregion
73
74    [StorableConstructor]
75    protected SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer(bool deserializing) : base(deserializing) { }
76    protected SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer(SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer<S, T, U> original, Cloner cloner) : base(original, cloner) { }
77    public SymbolicDataAnalysisSingleObjectiveValidationParetoBestSolutionAnalyzer()
78      : base() {
79      Parameters.Add(new LookupParameter<ItemList<S>>(ValidationBestSolutionsParameterName, "The validation best (Pareto-optimal) symbolic data analysis solutions."));
80      Parameters.Add(new LookupParameter<ItemList<DoubleArray>>(ValidationBestSolutionQualitiesParameterName, "The qualities of the validation best (Pareto-optimal) solutions."));
81      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(ComplexityParameterName, "The complexity of each tree."));
82    }
83
84    public override IOperation Apply() {
85      IEnumerable<int> rows = GenerateRowsToEvaluate();
86      if (!rows.Any()) return base.Apply();
87
88      #region find best tree
89      var evaluator = EvaluatorParameter.ActualValue;
90      var problemData = ProblemDataParameter.ActualValue;
91      ISymbolicExpressionTree[] tree = SymbolicExpressionTree.ToArray();
92
93      // sort is ascending and we take the first n% => order so that best solutions are smallest
94      // sort order is determined by maximization parameter
95      double[] trainingQuality;
96      if (Maximization.Value) {
97        // largest values must be sorted first
98        trainingQuality = Quality.Select(x => -x.Value).ToArray();
99      } else {
100        // smallest values must be sorted first
101        trainingQuality = Quality.Select(x => x.Value).ToArray();
102      }
103
104      int[] treeIndexes = Enumerable.Range(0, tree.Length).ToArray();
105
106      // sort trees by training qualities
107      Array.Sort(trainingQuality, treeIndexes);
108
109      // number of best training solutions to validate (at least 1)
110      int topN = (int)Math.Max(tree.Length * PercentageOfBestSolutionsParameter.ActualValue.Value, 1);
111
112      IExecutionContext childContext = (IExecutionContext)ExecutionContext.CreateChildOperation(evaluator);
113      // evaluate best n training trees on validiation set
114      var qualities = treeIndexes
115        .Select(i => tree[i])
116        .Take(topN)
117        .AsParallel()
118        .Select(t => evaluator.Evaluate(childContext, t, problemData, rows))
119        .ToArray();
120      #endregion
121
122      var results = ResultCollection;
123      // create empty parameter and result values
124      if (ValidationBestSolutions == null) {
125        ValidationBestSolutions = new ItemList<S>();
126        ValidationBestSolutionQualities = new ItemList<DoubleArray>();
127        results.Add(new Result(ValidationBestSolutionQualitiesParameter.Name, ValidationBestSolutionQualitiesParameter.Description, ValidationBestSolutionQualities));
128        results.Add(new Result(ValidationBestSolutionsParameter.Name, ValidationBestSolutionsParameter.Description, ValidationBestSolutions));
129      }
130
131      IList<Tuple<double, double>> validationBestQualities = ValidationBestSolutionQualities
132        .Select(x => Tuple.Create(x[0], x[1]))
133        .ToList();
134
135      #region find best trees
136      IList<int> nonDominatedIndexes = new List<int>();
137
138      List<double> complexities;
139      if (ComplexityParameter.ActualValue != null && ComplexityParameter.ActualValue.Length == trainingQuality.Length) {
140        complexities = ComplexityParameter.ActualValue.Select(x => x.Value).ToList();
141      } else {
142        complexities = tree.Select(t => (double)t.Length).ToList();
143      }
144      List<Tuple<double, double>> fitness = new List<Tuple<double, double>>();
145      for (int i = 0; i < qualities.Length; i++)
146        fitness.Add(Tuple.Create(qualities[i], complexities[treeIndexes[i]]));
147
148      var maximization = Tuple.Create(Maximization.Value, false); // complexity must be minimized
149      List<Tuple<double, double>> newNonDominatedQualities = new List<Tuple<double, double>>();
150      for (int i = 0; i < fitness.Count; i++) {
151        if (IsNonDominated(fitness[i], validationBestQualities, maximization) &&
152          IsNonDominated(fitness[i], newNonDominatedQualities, maximization) &&
153          IsNonDominated(fitness[i], fitness.Skip(i + 1), maximization)) {
154          if (!newNonDominatedQualities.Contains(fitness[i])) {
155            newNonDominatedQualities.Add(fitness[i]);
156            nonDominatedIndexes.Add(i);
157          }
158        }
159      }
160      #endregion
161
162      #region update Pareto-optimal solution archive
163      if (nonDominatedIndexes.Count > 0) {
164        ItemList<DoubleArray> nonDominatedQualities = new ItemList<DoubleArray>();
165        ItemList<S> nonDominatedSolutions = new ItemList<S>();
166        // add all new non-dominated solutions to the archive
167        foreach (var index in nonDominatedIndexes) {
168          S solution = CreateSolution(tree[treeIndexes[index]]);
169          nonDominatedSolutions.Add(solution);
170          nonDominatedQualities.Add(new DoubleArray(new double[] { fitness[index].Item1, fitness[index].Item2 }));
171        }
172        // add old non-dominated solutions only if they are not dominated by one of the new solutions
173        for (int i = 0; i < validationBestQualities.Count; i++) {
174          if (IsNonDominated(validationBestQualities[i], newNonDominatedQualities, maximization)) {
175            if (!newNonDominatedQualities.Contains(validationBestQualities[i])) {
176              nonDominatedSolutions.Add(ValidationBestSolutions[i]);
177              nonDominatedQualities.Add(ValidationBestSolutionQualities[i]);
178            }
179          }
180        }
181
182        // make sure solutions and qualities are ordered in the results
183        var orderedIndexes =
184          nonDominatedSolutions.Select((s, i) => i).OrderBy(i => nonDominatedQualities[i][0]).ToArray();
185
186        var orderedNonDominatedSolutions = new ItemList<S>();
187        var orderedNonDominatedQualities = new ItemList<DoubleArray>();
188        foreach (var i in orderedIndexes) {
189          orderedNonDominatedQualities.Add(nonDominatedQualities[i]);
190          orderedNonDominatedSolutions.Add(nonDominatedSolutions[i]);
191        }
192
193        ValidationBestSolutions = orderedNonDominatedSolutions;
194        ValidationBestSolutionQualities = orderedNonDominatedQualities;
195
196        results[ValidationBestSolutionsParameter.Name].Value = orderedNonDominatedSolutions;
197        results[ValidationBestSolutionQualitiesParameter.Name].Value = orderedNonDominatedQualities;
198      }
199      #endregion
200      return base.Apply();
201    }
202
203    protected abstract S CreateSolution(ISymbolicExpressionTree bestTree);
204
205    private bool IsNonDominated(Tuple<double, double> point, IEnumerable<Tuple<double, double>> points, Tuple<bool, bool> maximization) {
206      return !points.Any(p => IsBetterOrEqual(p.Item1, point.Item1, maximization.Item1) &&
207                             IsBetterOrEqual(p.Item2, point.Item2, maximization.Item2));
208    }
209    private bool IsBetterOrEqual(double lhs, double rhs, bool maximization) {
210      if (maximization) return lhs >= rhs;
211      else return lhs <= rhs;
212    }
213  }
214}
Note: See TracBrowser for help on using the repository browser.