Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/AccuracyMaximizationThresholdCalculator.cs @ 16640

Last change on this file since 16640 was 16640, checked in by gkronber, 5 years ago

#2971: merged r16565:16631 from trunk/HeuristicLab.Problems.DataAnalysis to branch/HeuristicLab.Problems.DataAnalysis (resolving all conflicts)

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