Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisModel.cs @ 13921

Last change on this file since 13921 was 13921, checked in by bburlacu, 8 years ago

#2604: Revert changes to DataAnalysisSolution and IDataAnalysisSolution and implement the desired properties in model classes that implement IDataAnalysisModel, IRegressionModel and IClassificationModel.

File size: 7.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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        return
64          SymbolicExpressionTree.IterateNodesPrefix()
65            .OfType<VariableTreeNode>()
66            .Select(x => x.VariableName)
67            .Distinct()
68            .OrderBy(x => x);
69      }
70    }
71
72    #endregion
73
74    [StorableConstructor]
75    protected SymbolicDataAnalysisModel(bool deserializing) : base(deserializing) { }
76    protected SymbolicDataAnalysisModel(SymbolicDataAnalysisModel original, Cloner cloner)
77      : base(original, cloner) {
78      this.symbolicExpressionTree = cloner.Clone(original.symbolicExpressionTree);
79      this.interpreter = cloner.Clone(original.interpreter);
80      this.lowerEstimationLimit = original.lowerEstimationLimit;
81      this.upperEstimationLimit = original.upperEstimationLimit;
82    }
83    protected SymbolicDataAnalysisModel(ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
84       double lowerEstimationLimit, double upperEstimationLimit)
85      : base() {
86      this.name = ItemName;
87      this.description = ItemDescription;
88      this.symbolicExpressionTree = tree;
89      this.interpreter = interpreter;
90      this.lowerEstimationLimit = lowerEstimationLimit;
91      this.upperEstimationLimit = upperEstimationLimit;
92    }
93
94    #region Scaling
95    protected void Scale(IDataAnalysisProblemData problemData, string targetVariable) {
96      var dataset = problemData.Dataset;
97      var rows = problemData.TrainingIndices;
98      var estimatedValues = Interpreter.GetSymbolicExpressionTreeValues(SymbolicExpressionTree, dataset, rows);
99      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
100
101      var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
102      var targetValuesEnumerator = targetValues.GetEnumerator();
103      var estimatedValuesEnumerator = estimatedValues.GetEnumerator();
104      while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) {
105        double target = targetValuesEnumerator.Current;
106        double estimated = estimatedValuesEnumerator.Current;
107        if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
108          linearScalingCalculator.Add(estimated, target);
109      }
110      if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext()))
111        throw new ArgumentException("Number of elements in target and estimated values enumeration do not match.");
112
113      double alpha = linearScalingCalculator.Alpha;
114      double beta = linearScalingCalculator.Beta;
115      if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) return;
116
117      ConstantTreeNode alphaTreeNode = null;
118      ConstantTreeNode betaTreeNode = null;
119      // check if model has been scaled previously by analyzing the structure of the tree
120      var startNode = SymbolicExpressionTree.Root.GetSubtree(0);
121      if (startNode.GetSubtree(0).Symbol is Addition) {
122        var addNode = startNode.GetSubtree(0);
123        if (addNode.SubtreeCount == 2 && addNode.GetSubtree(0).Symbol is Multiplication && addNode.GetSubtree(1).Symbol is Constant) {
124          alphaTreeNode = addNode.GetSubtree(1) as ConstantTreeNode;
125          var mulNode = addNode.GetSubtree(0);
126          if (mulNode.SubtreeCount == 2 && mulNode.GetSubtree(1).Symbol is Constant) {
127            betaTreeNode = mulNode.GetSubtree(1) as ConstantTreeNode;
128          }
129        }
130      }
131      // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
132      if (alphaTreeNode != null && betaTreeNode != null) {
133        betaTreeNode.Value *= beta;
134        alphaTreeNode.Value *= beta;
135        alphaTreeNode.Value += alpha;
136      } else {
137        var mainBranch = startNode.GetSubtree(0);
138        startNode.RemoveSubtree(0);
139        var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
140        startNode.AddSubtree(scaledMainBranch);
141      }
142    }
143
144    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
145      if (alpha.IsAlmost(0.0)) {
146        return treeNode;
147      } else {
148        var addition = new Addition();
149        var node = addition.CreateTreeNode();
150        var alphaConst = MakeConstant(alpha);
151        node.AddSubtree(treeNode);
152        node.AddSubtree(alphaConst);
153        return node;
154      }
155    }
156
157    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
158      if (beta.IsAlmost(1.0)) {
159        return treeNode;
160      } else {
161        var multipliciation = new Multiplication();
162        var node = multipliciation.CreateTreeNode();
163        var betaConst = MakeConstant(beta);
164        node.AddSubtree(treeNode);
165        node.AddSubtree(betaConst);
166        return node;
167      }
168    }
169
170    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
171      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
172      node.Value = c;
173      return node;
174    }
175    #endregion
176
177  }
178}
Note: See TracBrowser for help on using the repository browser.