Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModel.cs @ 15820

Last change on this file since 15820 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

File size: 7.3 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 : NamedItem, 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 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 been scaled previously by analyzing the structure of the tree
121      var startNode = SymbolicExpressionTree.Root.GetSubtree(0);
122      if (startNode.GetSubtree(0).Symbol is Addition) {
123        var addNode = startNode.GetSubtree(0);
124        if (addNode.SubtreeCount == 2 && addNode.GetSubtree(0).Symbol is Multiplication && addNode.GetSubtree(1).Symbol is Constant) {
125          alphaTreeNode = addNode.GetSubtree(1) as ConstantTreeNode;
126          var mulNode = addNode.GetSubtree(0);
127          if (mulNode.SubtreeCount == 2 && mulNode.GetSubtree(1).Symbol is Constant) {
128            betaTreeNode = mulNode.GetSubtree(1) as ConstantTreeNode;
129          }
130        }
131      }
132      // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
133      if (alphaTreeNode != null && betaTreeNode != null) {
134        betaTreeNode.Value *= beta;
135        alphaTreeNode.Value *= beta;
136        alphaTreeNode.Value += alpha;
137      } else {
138        var mainBranch = startNode.GetSubtree(0);
139        startNode.RemoveSubtree(0);
140        var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
141        startNode.AddSubtree(scaledMainBranch);
142      }
143    }
144
145    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
146      if (alpha.IsAlmost(0.0)) {
147        return treeNode;
148      } else {
149        var addition = new Addition();
150        var node = addition.CreateTreeNode();
151        var alphaConst = MakeConstant(alpha);
152        node.AddSubtree(treeNode);
153        node.AddSubtree(alphaConst);
154        return node;
155      }
156    }
157
158    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
159      if (beta.IsAlmost(1.0)) {
160        return treeNode;
161      } else {
162        var multipliciation = new Multiplication();
163        var node = multipliciation.CreateTreeNode();
164        var betaConst = MakeConstant(beta);
165        node.AddSubtree(treeNode);
166        node.AddSubtree(betaConst);
167        return node;
168      }
169    }
170
171    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
172      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
173      node.Value = c;
174      return node;
175    }
176    #endregion
177
178  }
179}
Note: See TracBrowser for help on using the repository browser.