Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6412 was 6234, checked in by mkommend, 14 years ago

#1532: Corrected bug in scaling of trees.

File size: 8.0 KB
RevLine 
[5649]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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
[6233]22using System;
[5649]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(); }
[5736]42      private set { thresholds = value.ToArray(); }
[5649]43    }
[5678]44    [Storable]
45    private double[] classValues;
46    public IEnumerable<double> ClassValues {
47      get { return (IEnumerable<double>)classValues.Clone(); }
[5736]48      private set { classValues = value.ToArray(); }
[5678]49    }
[5720]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
[5649]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();
[5720]63      lowerEstimationLimit = original.lowerEstimationLimit;
64      upperEstimationLimit = original.upperEstimationLimit;
[5649]65    }
[5720]66    public SymbolicDiscriminantFunctionClassificationModel(ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
67      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue)
[5649]68      : base(tree, interpreter) {
[5736]69      thresholds = new double[] { double.NegativeInfinity };
70      classValues = new double[] { 0.0 };
[5720]71      this.lowerEstimationLimit = lowerEstimationLimit;
72      this.upperEstimationLimit = upperEstimationLimit;
[5649]73    }
74
75    public override IDeepCloneable Clone(Cloner cloner) {
76      return new SymbolicDiscriminantFunctionClassificationModel(this, cloner);
77    }
78
[5736]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
[5649]89    public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
[5736]90      return Interpreter.GetSymbolicExpressionTreeValues(SymbolicExpressionTree, dataset, rows)
91        .LimitToRange(lowerEstimationLimit, upperEstimationLimit);
[5649]92    }
93
94    public IEnumerable<double> GetEstimatedClassValues(Dataset dataset, IEnumerable<int> rows) {
95      foreach (var x in GetEstimatedValues(dataset, rows)) {
96        int classIndex = 0;
[5678]97        // find first threshold value which is larger than x => class index = threshold index + 1
[5649]98        for (int i = 0; i < thresholds.Length; i++) {
99          if (x > thresholds[i]) classIndex++;
100          else break;
101        }
[5657]102        yield return classValues.ElementAt(classIndex - 1);
[5649]103      }
104    }
105
106    #region events
107    public event EventHandler ThresholdsChanged;
108    protected virtual void OnThresholdsChanged(EventArgs e) {
109      var listener = ThresholdsChanged;
110      if (listener != null) listener(this, e);
111    }
[5720]112    #endregion
[5818]113
114    public static void Scale(SymbolicDiscriminantFunctionClassificationModel model, IClassificationProblemData problemData) {
115      var dataset = problemData.Dataset;
116      var targetVariable = problemData.TargetVariable;
117      var rows = problemData.TrainingIndizes;
118      var estimatedValues = model.Interpreter.GetSymbolicExpressionTreeValues(model.SymbolicExpressionTree, dataset, rows);
119      var targetValues = dataset.GetEnumeratedVariableValues(targetVariable, rows);
120      double alpha;
121      double beta;
[5942]122      OnlineCalculatorError errorState;
[5894]123      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out alpha, out beta, out errorState);
[5942]124      if (errorState != OnlineCalculatorError.None) return;
[5818]125
126      ConstantTreeNode alphaTreeNode = null;
127      ConstantTreeNode betaTreeNode = null;
128      // check if model has been scaled previously by analyzing the structure of the tree
129      var startNode = model.SymbolicExpressionTree.Root.GetSubtree(0);
130      if (startNode.GetSubtree(0).Symbol is Addition) {
131        var addNode = startNode.GetSubtree(0);
132        if (addNode.SubtreesCount == 2 && addNode.GetSubtree(0).Symbol is Multiplication && addNode.GetSubtree(1).Symbol is Constant) {
133          alphaTreeNode = addNode.GetSubtree(1) as ConstantTreeNode;
134          var mulNode = addNode.GetSubtree(0);
135          if (mulNode.SubtreesCount == 2 && mulNode.GetSubtree(1).Symbol is Constant) {
136            betaTreeNode = mulNode.GetSubtree(1) as ConstantTreeNode;
137          }
138        }
139      }
140      // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
141      if (alphaTreeNode != null && betaTreeNode != null) {
142        betaTreeNode.Value *= beta;
143        alphaTreeNode.Value *= beta;
144        alphaTreeNode.Value += alpha;
145      } else {
146        var mainBranch = startNode.GetSubtree(0);
147        startNode.RemoveSubtree(0);
[6234]148        var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
[5818]149        startNode.AddSubtree(scaledMainBranch);
150      }
151    }
152
153    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
154      if (alpha.IsAlmost(0.0)) {
155        return treeNode;
156      } else {
[6234]157        var addition = new Addition();
[6233]158        var node = addition.CreateTreeNode();
[5818]159        var alphaConst = MakeConstant(alpha);
160        node.AddSubtree(treeNode);
161        node.AddSubtree(alphaConst);
162        return node;
163      }
164    }
165
[6233]166    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
[5818]167      if (beta.IsAlmost(1.0)) {
168        return treeNode;
169      } else {
[6234]170        var multipliciation = new Multiplication();
[6233]171        var node = multipliciation.CreateTreeNode();
[5818]172        var betaConst = MakeConstant(beta);
173        node.AddSubtree(treeNode);
174        node.AddSubtree(betaConst);
175        return node;
176      }
177    }
178
179    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
180      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
181      node.Value = c;
182      return node;
183    }
[5649]184  }
185}
Note: See TracBrowser for help on using the repository browser.