Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/NormalDistributionCutPointsThresholdCalculator.cs @ 8913

Last change on this file since 8913 was 8913, checked in by gkronber, 11 years ago

#1925: made corrections as suggested by abeham in the code review. In particular hopefully corrected the calculation of the CDF.

File size: 10.3 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 calculates thresholds as the cutting points between the estimated class distributions (assuming normally distributed class values).
32  /// </summary>
33  [StorableClass]
34  [Item("NormalDistributionCutPointsThresholdCalculator", "Represents a threshold calculator that calculates thresholds as the cutting points between the estimated class distributions (assuming normally distributed class values).")]
35  public class NormalDistributionCutPointsThresholdCalculator : ThresholdCalculator {
36
37    [StorableConstructor]
38    protected NormalDistributionCutPointsThresholdCalculator(bool deserializing) : base(deserializing) { }
39    protected NormalDistributionCutPointsThresholdCalculator(NormalDistributionCutPointsThresholdCalculator original, Cloner cloner)
40      : base(original, cloner) {
41    }
42    public NormalDistributionCutPointsThresholdCalculator()
43      : base() {
44    }
45
46    public override IDeepCloneable Clone(Cloner cloner) {
47      return new NormalDistributionCutPointsThresholdCalculator(this, cloner);
48    }
49
50    public override void Calculate(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) {
51      NormalDistributionCutPointsThresholdCalculator.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      var estimatedTargetValues = Enumerable.Zip(estimatedValues, targetClassValues, (e, t) => new { EstimatedValue = e, TargetValue = t }).ToList();
56      double estimatedValuesRange = estimatedValues.Range();
57
58      Dictionary<double, double> classMean = new Dictionary<double, double>();
59      Dictionary<double, double> classStdDev = new Dictionary<double, double>();
60      // calculate moments per class
61      foreach (var group in estimatedTargetValues.GroupBy(p => p.TargetValue)) {
62        IEnumerable<double> estimatedClassValues = group.Select(x => x.EstimatedValue);
63        double classValue = group.Key;
64        double mean, variance;
65        OnlineCalculatorError meanErrorState, varianceErrorState;
66        OnlineMeanAndVarianceCalculator.Calculate(estimatedClassValues, out mean, out variance, out meanErrorState, out varianceErrorState);
67
68        if (meanErrorState == OnlineCalculatorError.None && varianceErrorState == OnlineCalculatorError.None) {
69          classMean[classValue] = mean;
70          classStdDev[classValue] = Math.Sqrt(variance);
71        }
72      }
73      double[] originalClasses = classMean.Keys.OrderBy(x => x).ToArray();
74      int nClasses = originalClasses.Length;
75      List<double> thresholdList = new List<double>();
76      for (int i = 0; i < nClasses - 1; i++) {
77        for (int j = i + 1; j < nClasses; j++) {
78          double x1, x2;
79          double class0 = originalClasses[i];
80          double class1 = originalClasses[j];
81          // calculate all thresholds
82          CalculateCutPoints(classMean[class0], classStdDev[class0], classMean[class1], classStdDev[class1], out x1, out x2);
83
84          // if the two cut points are too close (for instance because the stdDev=0)
85          // then move them by 0.1% of the range of estimated values
86          if (x1.IsAlmost(x2)) {
87            x1 -= 0.001 * estimatedValuesRange;
88            x2 += 0.001 * estimatedValuesRange;
89          }
90          if (!double.IsInfinity(x1) && !thresholdList.Any(x => x.IsAlmost(x1))) thresholdList.Add(x1);
91          if (!double.IsInfinity(x2) && !thresholdList.Any(x => x.IsAlmost(x2))) thresholdList.Add(x2);
92        }
93      }
94      thresholdList.Sort();
95
96      // add small value and large value for the calculation of most influential class in each thresholded section
97      thresholdList.Insert(0, estimatedValues.Min() - 1);
98      thresholdList.Add(estimatedValues.Max() + 1);
99
100      // determine class values for each partition separated by a threshold by calculating the density of all class distributions
101      // all points in the partition are classified as the class with the maximal density in the parition
102      List<double> classValuesList = new List<double>();
103      if (thresholdList.Count == 2) {
104        // this happens if there are no thresholds (distributions for all classes are exactly the same)
105        // -> all samples should be classified as the class with the most observations
106        // group observations by target class and select the class with largest count
107        classValuesList.Add(targetClassValues.GroupBy(c => c)
108          .OrderBy(g => g.Count())
109          .Last().Key);
110      } else {
111        // at least one reasonable threshold ...
112        // find the most likely class for the points between thresholds m
113        for (int i = 0; i < thresholdList.Count - 1; i++) {
114
115          // determine class with maximal density mass between the thresholds
116          double maxDensity = DensityMass(thresholdList[i], thresholdList[i + 1], classMean[originalClasses[0]], classStdDev[originalClasses[0]]);
117          double maxDensityClassValue = originalClasses[0];
118          foreach (var classValue in originalClasses.Skip(1)) {
119            double density = DensityMass(thresholdList[i], thresholdList[i + 1], classMean[classValue], classStdDev[classValue]);
120            if (density > maxDensity) {
121              maxDensity = density;
122              maxDensityClassValue = classValue;
123            }
124          }
125          classValuesList.Add(maxDensityClassValue);
126        }
127      }
128
129      // only keep thresholds at which the class changes
130      // class B overrides threshold s. So only thresholds r and t are relevant and have to be kept
131      //
132      //      A    B  C
133      //       /\  /\/\       
134      //      / r\/ /\t\       
135      //     /   /\/  \ \     
136      //    /   / /\s  \ \     
137      //  -/---/-/ -\---\-\----
138
139      List<double> filteredThresholds = new List<double>();
140      List<double> filteredClassValues = new List<double>();
141      filteredThresholds.Add(double.NegativeInfinity); // the smallest possible threshold for the first class
142      filteredClassValues.Add(classValuesList[0]);
143      // do not include the last threshold which was just needed for the previous step
144      for (int i = 0; i < classValuesList.Count - 1; i++) {
145        if (!classValuesList[i].IsAlmost(classValuesList[i + 1])) {
146          filteredThresholds.Add(thresholdList[i + 1]);
147          filteredClassValues.Add(classValuesList[i + 1]);
148        }
149      }
150      thresholds = filteredThresholds.ToArray();
151      classValues = filteredClassValues.ToArray();
152    }
153
154    private static double NormalCDF(double mu, double sigma, double x) {
155      return 0.5 * (1 + alglib.normaldistr.errorfunction((x - mu) / (sigma * Math.Sqrt(2.0))));
156    }
157
158    // determines the value NormalCDF(mu,sigma, upper)  - NormalCDF(mu, sigma, lower)
159    // = the integral of the PDF of N(mu, sigma) in the range [lower, upper]
160    private static double DensityMass(double lower, double upper, double mu, double sigma) {
161      if (sigma.IsAlmost(0.0)) {
162        if (lower < mu && mu < upper) return 1.0; // all mass is between lower and upper
163        else return 0; // no mass is between lower and upper
164      }
165
166      if (double.IsNegativeInfinity(lower)) return NormalCDF(mu, sigma, upper);
167      else return NormalCDF(mu, sigma, upper) - NormalCDF(mu, sigma, lower);
168    }
169
170    // Calculates the points x1 and x2 where the distributions N(m1, s1) == N(m2,s2).
171    // In the general case there should be two cut points. If either s1 or s2 is 0 then x1==x2.
172    // If both s1 and s2 are zero than there are no cut points but we should return something reasonable (e.g. (m1 + m2) / 2) then.
173    private static void CalculateCutPoints(double m1, double s1, double m2, double s2, out double x1, out double x2) {
174      if (s1.IsAlmost(s2)) {
175        if (m1.IsAlmost(m2)) {
176          x1 = double.NegativeInfinity;
177          x2 = double.NegativeInfinity;
178        } else {
179          // s1==s2 and m1 != m2
180          // return something reasonable. cut point should be half way between m1 and m2
181          x1 = (m1 + m2) / 2;
182          x2 = double.NegativeInfinity;
183        }
184      } else if (s1.IsAlmost(0.0)) {
185        // when s1 is 0.0 the cut points are exactly at m1 ...
186        x1 = m1;
187        x2 = m1;
188      } else if (s2.IsAlmost(0.0)) {
189        // ... same for s2
190        x1 = m2;
191        x2 = m2;
192      } else {
193        if (s2 < s1) {
194          // make sure s2 is the larger std.dev.
195          CalculateCutPoints(m2, s2, m1, s1, out x1, out x2);
196        } else {
197          // general case
198          // calculate the solutions x1, x2 where N(m1,s1) == N(m2,s2)
199          double a = (s1 + s2) * (s1 - s2);
200          double g = Math.Sqrt(s1 * s1 * s2 * s2 * ((m1 - m2) * (m1 - m2) + 2.0 * (s1 * s1 + s2 * s2) * Math.Log(s2 / s1)));
201          double m1s2 = m1 * s2 * s2;
202          double m2s1 = m2 * s1 * s1;
203          x1 = (m2s1 - m1s2 - g) / a;
204          x2 = (m2s1 - m1s2 + g) / a;
205        }
206      }
207    }
208  }
209}
Note: See TracBrowser for help on using the repository browser.