Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2989_MovingPeaksBenchmark/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModel.cs @ 17187

Last change on this file since 17187 was 16290, checked in by gkronber, 6 years ago

#2950 adjusted scaling code for SymbolicDataAnalysisModels because with the new hashing code and simplification we cannot assume that scale and offset nodes are at the same locations

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
32  /// <summary>
33  /// Abstract base class for symbolic data analysis models
34  /// </summary>
35  [StorableClass]
36  public abstract class SymbolicDataAnalysisModel : DataAnalysisModel, ISymbolicDataAnalysisModel {
37    public static new Image StaticItemImage {
38      get { return HeuristicLab.Common.Resources.VSImageLibrary.Function; }
39    }
40
41    #region properties
42    [Storable]
43    private double lowerEstimationLimit;
44    public double LowerEstimationLimit { get { return lowerEstimationLimit; } }
45    [Storable]
46    private double upperEstimationLimit;
47    public double UpperEstimationLimit { get { return upperEstimationLimit; } }
48
49    [Storable]
50    private ISymbolicExpressionTree symbolicExpressionTree;
51    public ISymbolicExpressionTree SymbolicExpressionTree {
52      get { return symbolicExpressionTree; }
53    }
54
55    [Storable]
56    private ISymbolicDataAnalysisExpressionTreeInterpreter interpreter;
57    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter {
58      get { return interpreter; }
59    }
60
61    public override IEnumerable<string> VariablesUsedForPrediction {
62      get {
63        var variables =
64          SymbolicExpressionTree.IterateNodesPrefix()
65            .OfType<IVariableTreeNode>()
66            .Select(x => x.VariableName)
67            .Distinct();
68
69        return variables.OrderBy(x => x);
70      }
71    }
72
73    #endregion
74
75    [StorableConstructor]
76    protected SymbolicDataAnalysisModel(bool deserializing) : base(deserializing) { }
77    protected SymbolicDataAnalysisModel(SymbolicDataAnalysisModel original, Cloner cloner)
78      : base(original, cloner) {
79      this.symbolicExpressionTree = cloner.Clone(original.symbolicExpressionTree);
80      this.interpreter = cloner.Clone(original.interpreter);
81      this.lowerEstimationLimit = original.lowerEstimationLimit;
82      this.upperEstimationLimit = original.upperEstimationLimit;
83    }
84    protected SymbolicDataAnalysisModel(ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
85       double lowerEstimationLimit, double upperEstimationLimit)
86      : base() {
87      this.name = ItemName;
88      this.description = ItemDescription;
89      this.symbolicExpressionTree = tree;
90      this.interpreter = interpreter;
91      this.lowerEstimationLimit = lowerEstimationLimit;
92      this.upperEstimationLimit = upperEstimationLimit;
93    }
94
95    #region Scaling
96    protected void Scale(IDataAnalysisProblemData problemData, string targetVariable) {
97      var dataset = problemData.Dataset;
98      var rows = problemData.TrainingIndices;
99      var estimatedValues = Interpreter.GetSymbolicExpressionTreeValues(SymbolicExpressionTree, dataset, rows);
100      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
101
102      var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
103      var targetValuesEnumerator = targetValues.GetEnumerator();
104      var estimatedValuesEnumerator = estimatedValues.GetEnumerator();
105      while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) {
106        double target = targetValuesEnumerator.Current;
107        double estimated = estimatedValuesEnumerator.Current;
108        if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
109          linearScalingCalculator.Add(estimated, target);
110      }
111      if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext()))
112        throw new ArgumentException("Number of elements in target and estimated values enumeration do not match.");
113
114      double alpha = linearScalingCalculator.Alpha;
115      double beta = linearScalingCalculator.Beta;
116      if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) return;
117
118      ConstantTreeNode alphaTreeNode = null;
119      ConstantTreeNode betaTreeNode = null;
120      // check if model has a structure that can be re-used for scaling
121      var startNode = SymbolicExpressionTree.Root.GetSubtree(0);
122      var addNode = startNode.GetSubtree(0);
123      if (addNode.Symbol is Addition && addNode.SubtreeCount == 2) {
124        alphaTreeNode = (ConstantTreeNode)addNode.Subtrees.LastOrDefault(n => n is ConstantTreeNode);
125        var mulNode = addNode.Subtrees.FirstOrDefault(n => n.Symbol is Multiplication);
126        if (mulNode != null) {
127          betaTreeNode = (ConstantTreeNode)mulNode.Subtrees.LastOrDefault(n => n is ConstantTreeNode);
128        }
129      }
130      // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
131      if (alphaTreeNode != null && betaTreeNode != null) {
132        betaTreeNode.Value *= beta;
133        alphaTreeNode.Value *= beta;
134        alphaTreeNode.Value += alpha;
135      } else {
136        var mainBranch = startNode.GetSubtree(0);
137        startNode.RemoveSubtree(0);
138        var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
139        startNode.AddSubtree(scaledMainBranch);
140      }
141    }
142
143    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
144      if (alpha.IsAlmost(0.0)) {
145        return treeNode;
146      } else {
147        var addition = new Addition();
148        var node = addition.CreateTreeNode();
149        var alphaConst = MakeConstant(alpha);
150        node.AddSubtree(treeNode);
151        node.AddSubtree(alphaConst);
152        return node;
153      }
154    }
155
156    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
157      if (beta.IsAlmost(1.0)) {
158        return treeNode;
159      } else {
160        var multipliciation = new Multiplication();
161        var node = multipliciation.CreateTreeNode();
162        var betaConst = MakeConstant(beta);
163        node.AddSubtree(treeNode);
164        node.AddSubtree(betaConst);
165        return node;
166      }
167    }
168
169    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
170      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
171      node.Value = c;
172      return node;
173    }
174    #endregion
175
176  }
177}
Note: See TracBrowser for help on using the repository browser.