Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis Refactoring/HeuristicLab.Problems.DataAnalysis/3.4/DiscriminantFunctionClassificationSolution.cs @ 5678

Last change on this file since 5678 was 5678, checked in by gkronber, 13 years ago

#1418 Worked on calculation of thresholds for classification solutions based on discriminant functions.

File size: 8.3 KB
Line 
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
22using System.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Optimization;
31using System;
32
33namespace HeuristicLab.Problems.DataAnalysis {
34  /// <summary>
35  /// Represents a classification solution that uses a discriminant function and classification thresholds.
36  /// </summary>
37  [StorableClass]
38  [Item("DiscriminantFunctionClassificationSolution", "Represents a classification solution that uses a discriminant function and classification thresholds.")]
39  public class DiscriminantFunctionClassificationSolution : ClassificationSolution, IDiscriminantFunctionClassificationSolution {
40    [StorableConstructor]
41    protected DiscriminantFunctionClassificationSolution(bool deserializing) : base(deserializing) { }
42    protected DiscriminantFunctionClassificationSolution(DiscriminantFunctionClassificationSolution original, Cloner cloner)
43      : base(original, cloner) {
44    }
45    public DiscriminantFunctionClassificationSolution(IRegressionModel model, IClassificationProblemData problemData)
46      : this(new DiscriminantFunctionClassificationModel(model, problemData.ClassValues, CalculateClassThresholds(model, problemData, problemData.TrainingIndizes)), problemData) {
47    }
48    public DiscriminantFunctionClassificationSolution(IDiscriminantFunctionClassificationModel model, IClassificationProblemData problemData)
49      : base(model, problemData) {
50      Model.ThresholdsChanged += new EventHandler(Model_ThresholdsChanged);
51    }
52
53    #region IDiscriminantFunctionClassificationSolution Members
54
55    public new IDiscriminantFunctionClassificationModel Model {
56      get { return (IDiscriminantFunctionClassificationModel)base.Model; }
57    }
58
59    public IEnumerable<double> EstimatedValues {
60      get { return GetEstimatedValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); }
61    }
62
63    public IEnumerable<double> EstimatedTrainingValues {
64      get { return GetEstimatedValues(ProblemData.TrainingIndizes); }
65    }
66
67    public IEnumerable<double> EstimatedTestValues {
68      get { return GetEstimatedValues(ProblemData.TestIndizes); }
69    }
70
71    public IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows) {
72      return Model.GetEstimatedValues(ProblemData.Dataset, rows);
73    }
74
75    public IEnumerable<double> Thresholds {
76      get {
77        return Model.Thresholds;
78      }
79      set { Model.Thresholds = new List<double>(value); }
80    }
81
82    public event EventHandler ThresholdsChanged;
83
84    private void Model_ThresholdsChanged(object sender, EventArgs e) {
85      OnThresholdsChanged(e);
86    }
87
88    protected virtual void OnThresholdsChanged(EventArgs e) {
89      var listener = ThresholdsChanged;
90      if (listener != null) listener(this, e);
91    }
92    #endregion
93
94    private static double[] CalculateClassThresholds(IRegressionModel model, IClassificationProblemData problemData, IEnumerable<int> rows) {
95      double[] thresholds;
96      double[] classValues;
97      CalculateClassThresholds(problemData, model.GetEstimatedValues(problemData.Dataset, rows), problemData.Dataset.GetEnumeratedVariableValues(problemData.TargetVariable, rows), out classValues, out thresholds);
98      return thresholds;
99    }
100
101    public static void CalculateClassThresholds(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) {
102      int slices = 100;
103      List<double> estimatedValuesList = estimatedValues.ToList();
104      double maxEstimatedValue = estimatedValuesList.Max();
105      double minEstimatedValue = estimatedValuesList.Min();
106      double thresholdIncrement = (maxEstimatedValue - minEstimatedValue) / slices;
107      var estimatedAndTargetValuePairs =
108        estimatedValuesList.Zip(targetClassValues, (x, y) => new { EstimatedValue = x, TargetClassValue = y })
109        .OrderBy(x => x.EstimatedValue)
110        .ToList();
111
112      classValues = problemData.ClassValues.OrderBy(x => x).ToArray();
113      int nClasses = classValues.Length;
114      thresholds = new double[nClasses + 1];
115      thresholds[0] = double.NegativeInfinity;
116      thresholds[thresholds.Length - 1] = double.PositiveInfinity;
117
118      // incrementally calculate accuracy of all possible thresholds
119      int[,] confusionMatrix = new int[nClasses, nClasses];
120
121      // one threshold is always treated as binary separation of the remaining classes
122      for (int i = 1; i < thresholds.Length - 1; i++) {
123        double lowerThreshold = thresholds[i - 1];
124        double actualThreshold = Math.Max(lowerThreshold, minEstimatedValue);
125        double lowestBestThreshold = double.NaN;
126        double highestBestThreshold = double.NaN;
127        double bestClassificationScore = double.PositiveInfinity;
128        bool seriesOfEqualClassificationScores = false;
129
130        while (actualThreshold < maxEstimatedValue) {
131          double classificationScore = 0.0;
132
133          foreach (var pair in estimatedAndTargetValuePairs) {
134            //all positives
135            if (pair.TargetClassValue.IsAlmost(classValues[i - 1])) {
136              if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold)
137                //true positive
138                classificationScore += problemData.GetClassificationPenalty(classValues[i - 1], classValues[i - 1]);
139              else
140                //false negative
141                classificationScore += problemData.GetClassificationPenalty(classValues[i], classValues[i - 1]);
142            }
143              //all negatives
144            else {
145              if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold)
146                //false positive
147                classificationScore += problemData.GetClassificationPenalty(classValues[i - 1], classValues[i]);
148              else
149                //true negative, consider only upper class
150                classificationScore += problemData.GetClassificationPenalty(classValues[i], classValues[i]);
151            }
152          }
153
154          //new best classification score found
155          if (classificationScore < bestClassificationScore) {
156            bestClassificationScore = classificationScore;
157            lowestBestThreshold = actualThreshold;
158            highestBestThreshold = actualThreshold;
159            seriesOfEqualClassificationScores = true;
160          }
161            //equal classification scores => if seriesOfEqualClassifcationScores == true update highest threshold
162          else if (Math.Abs(classificationScore - bestClassificationScore) < double.Epsilon && seriesOfEqualClassificationScores)
163            highestBestThreshold = actualThreshold;
164          //worse classificatoin score found reset seriesOfEqualClassifcationScores
165          else seriesOfEqualClassificationScores = false;
166
167          actualThreshold += thresholdIncrement;
168        }
169        //scale lowest thresholds and highest found optimal threshold according to the misclassification matrix
170        double falseNegativePenalty = problemData.GetClassificationPenalty(classValues[i], classValues[i - 1]);
171        double falsePositivePenalty = problemData.GetClassificationPenalty(classValues[i - 1], classValues[i]);
172        thresholds[i] = (lowestBestThreshold * falsePositivePenalty + highestBestThreshold * falseNegativePenalty) / (falseNegativePenalty + falsePositivePenalty);
173      }
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.