Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/AccuracyMaximizationThresholdCalculator.cs @ 8126

Last change on this file since 8126 was 8126, checked in by gkronber, 12 years ago

#1823 fixed a bug in the Pareto-best solution analyzers for symbolic data analysis. Fixed a minor bug in the calculation of classification thresholds, made a sneaky change in SymbolicExpressionTree

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