Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis Refactoring/HeuristicLab.Problems.DataAnalysis/3.4/ThresholdCalculators/AccuracyMaximizationThresholdCalculator.cs @ 5717

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

#1418 Implemented interactive simplifier views for symbolic classification and regression.

File size: 6.5 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 threshold calculator that maximizes the weighted accuracy of the classifcation model.
36  /// </summary>
37  [StorableClass]
38  [Item("AccuracyMaximizationThresholdCalculator", "Represents a threshold calculator that maximizes the weighted accuracy of the classifcation model.")]
39  public class AccuracyMaximizationThresholdCalculator : ThresholdCalculator {
40
41    [StorableConstructor]
42    protected AccuracyMaximizationThresholdCalculator(bool deserializing) : base(deserializing) { }
43    protected AccuracyMaximizationThresholdCalculator(AccuracyMaximizationThresholdCalculator original, Cloner cloner)
44      : base(original, cloner) {
45    }
46    public AccuracyMaximizationThresholdCalculator()
47      : base() {
48    }
49
50    public override IDeepCloneable Clone(Cloner cloner) {
51      return new AccuracyMaximizationThresholdCalculator(this, cloner);
52    }
53
54    public override void Calculate(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) {
55      AccuracyMaximizationThresholdCalculator.CalculateThresholds(problemData, estimatedValues, targetClassValues, out classValues, out thresholds);
56    }
57
58    public static void CalculateThresholds(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) {
59      int slices = 100;
60      List<double> estimatedValuesList = estimatedValues.ToList();
61      double maxEstimatedValue = estimatedValuesList.Max();
62      double minEstimatedValue = estimatedValuesList.Min();
63      double thresholdIncrement = (maxEstimatedValue - minEstimatedValue) / slices;
64      var estimatedAndTargetValuePairs =
65        estimatedValuesList.Zip(targetClassValues, (x, y) => new { EstimatedValue = x, TargetClassValue = y })
66        .OrderBy(x => x.EstimatedValue)
67        .ToList();
68
69      classValues = problemData.ClassValues.OrderBy(x => x).ToArray();
70      int nClasses = classValues.Length;
71      thresholds = new double[nClasses + 1];
72      thresholds[0] = double.NegativeInfinity;
73      thresholds[thresholds.Length - 1] = double.PositiveInfinity;
74
75      // incrementally calculate accuracy of all possible thresholds
76      int[,] confusionMatrix = new int[nClasses, nClasses];
77
78      for (int i = 1; i < thresholds.Length - 1; i++) {
79        double lowerThreshold = thresholds[i - 1];
80        double actualThreshold = Math.Max(lowerThreshold, minEstimatedValue);
81        double lowestBestThreshold = double.NaN;
82        double highestBestThreshold = double.NaN;
83        double bestClassificationScore = double.PositiveInfinity;
84        bool seriesOfEqualClassificationScores = false;
85
86        while (actualThreshold < maxEstimatedValue) {
87          double classificationScore = 0.0;
88
89          foreach (var pair in estimatedAndTargetValuePairs) {
90            //all positives
91            if (pair.TargetClassValue.IsAlmost(classValues[i - 1])) {
92              if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold)
93                //true positive
94                classificationScore += problemData.GetClassificationPenalty(classValues[i - 1], classValues[i - 1]);
95              else
96                //false negative
97                classificationScore += problemData.GetClassificationPenalty(classValues[i], classValues[i - 1]);
98            }
99              //all negatives
100            else {
101              if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold)
102                //false positive
103                classificationScore += problemData.GetClassificationPenalty(classValues[i - 1], classValues[i]);
104              else
105                //true negative, consider only upper class
106                classificationScore += problemData.GetClassificationPenalty(classValues[i], classValues[i]);
107            }
108          }
109
110          //new best classification score found
111          if (classificationScore < bestClassificationScore) {
112            bestClassificationScore = classificationScore;
113            lowestBestThreshold = actualThreshold;
114            highestBestThreshold = actualThreshold;
115            seriesOfEqualClassificationScores = true;
116          }
117            //equal classification scores => if seriesOfEqualClassifcationScores == true update highest threshold
118          else if (Math.Abs(classificationScore - bestClassificationScore) < double.Epsilon && seriesOfEqualClassificationScores)
119            highestBestThreshold = actualThreshold;
120          //worse classificatoin score found reset seriesOfEqualClassifcationScores
121          else seriesOfEqualClassificationScores = false;
122
123          actualThreshold += thresholdIncrement;
124        }
125        //scale lowest thresholds and highest found optimal threshold according to the misclassification matrix
126        double falseNegativePenalty = problemData.GetClassificationPenalty(classValues[i], classValues[i - 1]);
127        double falsePositivePenalty = problemData.GetClassificationPenalty(classValues[i - 1], classValues[i]);
128        thresholds[i] = (lowestBestThreshold * falsePositivePenalty + highestBestThreshold * falseNegativePenalty) / (falseNegativePenalty + falsePositivePenalty);
129      }
130    }
131  }
132}
Note: See TracBrowser for help on using the repository browser.