Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Classification/3.4/SymbolicDiscriminantFunctionClassificationModel.cs @ 8026

Last change on this file since 8026 was 8026, checked in by mkommend, 12 years ago

#1874: Corrected scaling in SymbolicDataAnalysis models.

File size: 8.7 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;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Classification {
31  /// <summary>
32  /// Represents a symbolic classification model
33  /// </summary>
34  [StorableClass]
35  [Item(Name = "SymbolicDiscriminantFunctionClassificationModel", Description = "Represents a symbolic classification model unsing a discriminant function.")]
36  public class SymbolicDiscriminantFunctionClassificationModel : SymbolicDataAnalysisModel, ISymbolicDiscriminantFunctionClassificationModel {
37
38    [Storable]
39    private double[] thresholds;
40    public IEnumerable<double> Thresholds {
41      get { return (IEnumerable<double>)thresholds.Clone(); }
42      private set { thresholds = value.ToArray(); }
43    }
44    [Storable]
45    private double[] classValues;
46    public IEnumerable<double> ClassValues {
47      get { return (IEnumerable<double>)classValues.Clone(); }
48      private set { classValues = value.ToArray(); }
49    }
50    [Storable]
51    private double lowerEstimationLimit;
52    public double LowerEstimationLimit { get { return lowerEstimationLimit; } }
53    [Storable]
54    private double upperEstimationLimit;
55    public double UpperEstimationLimit { get { return upperEstimationLimit; } }
56
57    [StorableConstructor]
58    protected SymbolicDiscriminantFunctionClassificationModel(bool deserializing) : base(deserializing) { }
59    protected SymbolicDiscriminantFunctionClassificationModel(SymbolicDiscriminantFunctionClassificationModel original, Cloner cloner)
60      : base(original, cloner) {
61      classValues = (double[])original.classValues.Clone();
62      thresholds = (double[])original.thresholds.Clone();
63      lowerEstimationLimit = original.lowerEstimationLimit;
64      upperEstimationLimit = original.upperEstimationLimit;
65    }
66    public SymbolicDiscriminantFunctionClassificationModel(ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
67      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue)
68      : base(tree, interpreter) {
69      thresholds = new double[] { double.NegativeInfinity };
70      classValues = new double[] { 0.0 };
71      this.lowerEstimationLimit = lowerEstimationLimit;
72      this.upperEstimationLimit = upperEstimationLimit;
73    }
74
75    public override IDeepCloneable Clone(Cloner cloner) {
76      return new SymbolicDiscriminantFunctionClassificationModel(this, cloner);
77    }
78
79    public void SetThresholdsAndClassValues(IEnumerable<double> thresholds, IEnumerable<double> classValues) {
80      var classValuesArr = classValues.ToArray();
81      var thresholdsArr = thresholds.ToArray();
82      if (thresholdsArr.Length != classValuesArr.Length) throw new ArgumentException();
83
84      this.classValues = classValuesArr;
85      this.thresholds = thresholdsArr;
86      OnThresholdsChanged(EventArgs.Empty);
87    }
88
89    public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
90      return Interpreter.GetSymbolicExpressionTreeValues(SymbolicExpressionTree, dataset, rows)
91        .LimitToRange(lowerEstimationLimit, upperEstimationLimit);
92    }
93
94    public IEnumerable<double> GetEstimatedClassValues(Dataset dataset, IEnumerable<int> rows) {
95      foreach (var x in GetEstimatedValues(dataset, rows)) {
96        int classIndex = 0;
97        // find first threshold value which is larger than x => class index = threshold index + 1
98        for (int i = 0; i < thresholds.Length; i++) {
99          if (x > thresholds[i]) classIndex++;
100          else break;
101        }
102        yield return classValues.ElementAt(classIndex - 1);
103      }
104    }
105
106    public SymbolicDiscriminantFunctionClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
107      return new SymbolicDiscriminantFunctionClassificationSolution(this, problemData);
108    }
109    IClassificationSolution IClassificationModel.CreateClassificationSolution(IClassificationProblemData problemData) {
110      return CreateClassificationSolution(problemData);
111    }
112    IDiscriminantFunctionClassificationSolution IDiscriminantFunctionClassificationModel.CreateDiscriminantFunctionClassificationSolution(IClassificationProblemData problemData) {
113      return CreateClassificationSolution(problemData);
114    }
115
116    #region events
117    public event EventHandler ThresholdsChanged;
118    protected virtual void OnThresholdsChanged(EventArgs e) {
119      var listener = ThresholdsChanged;
120      if (listener != null) listener(this, e);
121    }
122    #endregion
123
124    public static void Scale(SymbolicDiscriminantFunctionClassificationModel model, IClassificationProblemData problemData) {
125      var dataset = problemData.Dataset;
126      var targetVariable = problemData.TargetVariable;
127      var rows = problemData.TrainingIndizes;
128      var estimatedValues = model.Interpreter.GetSymbolicExpressionTreeValues(model.SymbolicExpressionTree, dataset, rows);
129      var boundedEstimatedValues = estimatedValues.LimitToRange(model.LowerEstimationLimit, model.UpperEstimationLimit);
130      var targetValues = dataset.GetDoubleValues(targetVariable, rows);
131      double alpha;
132      double beta;
133      OnlineCalculatorError errorState;
134      OnlineLinearScalingParameterCalculator.Calculate(boundedEstimatedValues, targetValues, out alpha, out beta, out errorState);
135      if (errorState != OnlineCalculatorError.None) return;
136
137      ConstantTreeNode alphaTreeNode = null;
138      ConstantTreeNode betaTreeNode = null;
139      // check if model has been scaled previously by analyzing the structure of the tree
140      var startNode = model.SymbolicExpressionTree.Root.GetSubtree(0);
141      if (startNode.GetSubtree(0).Symbol is Addition) {
142        var addNode = startNode.GetSubtree(0);
143        if (addNode.SubtreeCount == 2 && addNode.GetSubtree(0).Symbol is Multiplication && addNode.GetSubtree(1).Symbol is Constant) {
144          alphaTreeNode = addNode.GetSubtree(1) as ConstantTreeNode;
145          var mulNode = addNode.GetSubtree(0);
146          if (mulNode.SubtreeCount == 2 && mulNode.GetSubtree(1).Symbol is Constant) {
147            betaTreeNode = mulNode.GetSubtree(1) as ConstantTreeNode;
148          }
149        }
150      }
151      // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
152      if (alphaTreeNode != null && betaTreeNode != null) {
153        betaTreeNode.Value *= beta;
154        alphaTreeNode.Value *= beta;
155        alphaTreeNode.Value += alpha;
156      } else {
157        var mainBranch = startNode.GetSubtree(0);
158        startNode.RemoveSubtree(0);
159        var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
160        startNode.AddSubtree(scaledMainBranch);
161      }
162    }
163
164    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
165      if (alpha.IsAlmost(0.0)) {
166        return treeNode;
167      } else {
168        var addition = new Addition();
169        var node = addition.CreateTreeNode();
170        var alphaConst = MakeConstant(alpha);
171        node.AddSubtree(treeNode);
172        node.AddSubtree(alphaConst);
173        return node;
174      }
175    }
176
177    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
178      if (beta.IsAlmost(1.0)) {
179        return treeNode;
180      } else {
181        var multipliciation = new Multiplication();
182        var node = multipliciation.CreateTreeNode();
183        var betaConst = MakeConstant(beta);
184        node.AddSubtree(treeNode);
185        node.AddSubtree(betaConst);
186        return node;
187      }
188    }
189
190    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
191      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
192      node.Value = c;
193      return node;
194    }
195  }
196}
Note: See TracBrowser for help on using the repository browser.