Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Problems.DataAnalysis.Classification.Views/3.3/RocCurvesView.cs @ 11896

Last change on this file since 11896 was 4651, checked in by mkommend, 14 years ago

Integrated EnhancedChart in all GP specific views (ticket #1228).

File size: 10.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
29using HeuristicLab.Common;
30using HeuristicLab.MainForm;
31using HeuristicLab.MainForm.WindowsForms;
32namespace HeuristicLab.Problems.DataAnalysis.Classification.Views {
33  [View("ROC Curves View")]
34  [Content(typeof(SymbolicClassificationSolution))]
35  public partial class RocCurvesView : AsynchronousContentView {
36    private const string xAxisTitle = "False Positive Rate";
37    private const string yAxisTitle = "True Positive Rate";
38    private const string TrainingSamples = "Training";
39    private const string TestSamples = "Test";
40    private Dictionary<string, List<ROCPoint>> cachedRocPoints;
41
42    public RocCurvesView() {
43      InitializeComponent();
44
45      cachedRocPoints = new Dictionary<string, List<ROCPoint>>();
46
47      cmbSamples.Items.Add(TrainingSamples);
48      cmbSamples.Items.Add(TestSamples);
49      cmbSamples.SelectedIndex = 0;
50
51      chart.CustomizeAllChartAreas();
52      chart.ChartAreas[0].AxisX.Minimum = 0.0;
53      chart.ChartAreas[0].AxisX.Maximum = 1.0;
54      chart.ChartAreas[0].AxisX.MajorGrid.Interval = 0.2;
55      chart.ChartAreas[0].AxisY.Minimum = 0.0;
56      chart.ChartAreas[0].AxisY.Maximum = 1.0;
57      chart.ChartAreas[0].AxisY.MajorGrid.Interval = 0.2;
58
59      chart.ChartAreas[0].AxisX.Title = xAxisTitle;
60      chart.ChartAreas[0].AxisY.Title = yAxisTitle;
61    }
62
63    public new SymbolicClassificationSolution Content {
64      get { return (SymbolicClassificationSolution)base.Content; }
65      set { base.Content = value; }
66    }
67
68    protected override void RegisterContentEvents() {
69      base.RegisterContentEvents();
70      Content.EstimatedValuesChanged += new EventHandler(Content_EstimatedValuesChanged);
71      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
72    }
73    protected override void DeregisterContentEvents() {
74      base.DeregisterContentEvents();
75      Content.EstimatedValuesChanged -= new EventHandler(Content_EstimatedValuesChanged);
76      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
77    }
78
79    private void Content_EstimatedValuesChanged(object sender, EventArgs e) {
80      UpdateChart();
81    }
82    private void Content_ProblemDataChanged(object sender, EventArgs e) {
83      UpdateChart();
84    }
85
86    protected override void OnContentChanged() {
87      base.OnContentChanged();
88      chart.Series.Clear();
89      if (Content != null) UpdateChart();
90    }
91
92    private void UpdateChart() {
93      if (InvokeRequired) Invoke((Action)UpdateChart);
94      else {
95        chart.Series.Clear();
96        chart.Annotations.Clear();
97        cachedRocPoints.Clear();
98
99        int slices = 100;
100        IEnumerable<int> rows;
101
102        if (cmbSamples.SelectedItem.ToString() == TrainingSamples) {
103          rows = Content.ProblemData.TrainingIndizes;
104        } else if (cmbSamples.SelectedItem.ToString() == TestSamples) {
105          rows = Content.ProblemData.TestIndizes;
106        } else throw new InvalidOperationException();
107
108        double[] estimatedValues = Content.GetEstimatedValues(rows).ToArray();
109        double[] targetClassValues = Content.ProblemData.Dataset.GetEnumeratedVariableValues(Content.ProblemData.TargetVariable.Value, rows).ToArray();
110        double minThreshold = estimatedValues.Min();
111        double maxThreshold = estimatedValues.Max();
112        double thresholdIncrement = (maxThreshold - minThreshold) / slices;
113        minThreshold -= thresholdIncrement;
114        maxThreshold += thresholdIncrement;
115
116        List<double> classValues = Content.ProblemData.SortedClassValues.ToList();
117
118        foreach (double classValue in classValues) {
119          List<ROCPoint> rocPoints = new List<ROCPoint>();
120          int positives = targetClassValues.Where(c => c.IsAlmost(classValue)).Count();
121          int negatives = targetClassValues.Length - positives;
122
123          for (double lowerThreshold = minThreshold; lowerThreshold < maxThreshold; lowerThreshold += thresholdIncrement) {
124            for (double upperThreshold = lowerThreshold + thresholdIncrement; upperThreshold < maxThreshold; upperThreshold += thresholdIncrement) {
125              int truePositives = 0;
126              int falsePositives = 0;
127
128              for (int row = 0; row < estimatedValues.Length; row++) {
129                if (lowerThreshold < estimatedValues[row] && estimatedValues[row] < upperThreshold) {
130                  if (targetClassValues[row].IsAlmost(classValue)) truePositives++;
131                  else falsePositives++;
132                }
133              }
134
135              double truePositiveRate = ((double)truePositives) / positives;
136              double falsePositiveRate = ((double)falsePositives) / negatives;
137
138              ROCPoint rocPoint = new ROCPoint(truePositiveRate, falsePositiveRate, lowerThreshold, upperThreshold);
139              if (!rocPoints.Any(x => x.truePositiveRate >= rocPoint.truePositiveRate && x.falsePositiveRate <= rocPoint.falsePositiveRate)) {
140                rocPoints.RemoveAll(x => x.falsePositiveRate >= rocPoint.falsePositiveRate && x.truePositiveRate <= rocPoint.truePositiveRate);
141                rocPoints.Add(rocPoint);
142              }
143            }
144          }
145
146          string className = Content.ProblemData.ClassNames.ElementAt(classValues.IndexOf(classValue));
147          cachedRocPoints[className] = rocPoints.OrderBy(x => x.falsePositiveRate).ToList(); ;
148
149          Series series = new Series(className);
150          series.ChartType = SeriesChartType.Line;
151          series.MarkerStyle = MarkerStyle.Diamond;
152          series.MarkerSize = 5;
153          chart.Series.Add(series);
154          FillSeriesWithDataPoints(series, cachedRocPoints[className]);
155
156          double auc = CalculateAreaUnderCurve(series);
157          series.LegendToolTip = "AUC: " + auc;
158        }
159      }
160    }
161
162    private void FillSeriesWithDataPoints(Series series, IEnumerable<ROCPoint> rocPoints) {
163      series.Points.Add(new DataPoint(0, 0));
164      foreach (ROCPoint rocPoint in rocPoints) {
165        DataPoint point = new DataPoint();
166        point.XValue = rocPoint.falsePositiveRate;
167        point.YValues[0] = rocPoint.truePositiveRate;
168        point.Tag = rocPoint;
169
170        StringBuilder sb = new StringBuilder();
171        sb.AppendLine("True Positive Rate: " + rocPoint.truePositiveRate);
172        sb.AppendLine("False Positive Rate: " + rocPoint.falsePositiveRate);
173        sb.AppendLine("Upper Threshold: " + rocPoint.upperThreshold);
174        sb.AppendLine("Lower Threshold: " + rocPoint.lowerThreshold);
175        point.ToolTip = sb.ToString();
176
177        series.Points.Add(point);
178      }
179      series.Points.Add(new DataPoint(1, 1));
180    }
181
182    private double CalculateAreaUnderCurve(Series series) {
183      if (series.Points.Count < 1) throw new ArgumentException("Could not calculate area under curve if less than 1 data points were given.");
184
185      double auc = 0.0;
186      for (int i = 1; i < series.Points.Count; i++) {
187        double width = series.Points[i].XValue - series.Points[i - 1].XValue;
188        double y1 = series.Points[i - 1].YValues[0];
189        double y2 = series.Points[i].YValues[0];
190
191        auc += (y1 + y2) * width / 2;
192      }
193
194      return auc;
195    }
196
197    private void cmbSamples_SelectedIndexChanged(object sender, System.EventArgs e) {
198      if (Content != null)
199        UpdateChart();
200    }
201
202
203    #region show / hide series
204    private void ToggleSeries(Series series) {
205      if (series.Points.Count == 0)
206        FillSeriesWithDataPoints(series, cachedRocPoints[series.Name]);
207      else
208        series.Points.Clear();
209    }
210    private void chart_MouseDown(object sender, MouseEventArgs e) {
211      HitTestResult result = chart.HitTest(e.X, e.Y);
212      if (result.ChartElementType == ChartElementType.LegendItem) {
213        if (result.Series != null) ToggleSeries(result.Series);
214      }
215    }
216    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
217      foreach (LegendItem legendItem in e.LegendItems) {
218        var series = chart.Series[legendItem.SeriesName];
219        if (series != null) {
220          bool seriesIsInvisible = series.Points.Count == 0;
221          foreach (LegendCell cell in legendItem.Cells)
222            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
223        }
224      }
225    }
226    private void chart_MouseMove(object sender, MouseEventArgs e) {
227      HitTestResult result = chart.HitTest(e.X, e.Y);
228      if (result.ChartElementType == ChartElementType.LegendItem)
229        this.Cursor = Cursors.Hand;
230      else
231        this.Cursor = Cursors.Default;
232
233      string newTooltipText = string.Empty;
234      if (result.ChartElementType == ChartElementType.DataPoint)
235        newTooltipText = ((DataPoint)result.Object).ToolTip;
236
237      string oldTooltipText = this.toolTip.GetToolTip(chart);
238      if (newTooltipText != oldTooltipText)
239        this.toolTip.SetToolTip(chart, newTooltipText);
240    }
241    #endregion
242
243
244    private class ROCPoint {
245      public ROCPoint(double truePositiveRate, double falsePositiveRate, double lowerThreshold, double upperThreshold) {
246        this.truePositiveRate = truePositiveRate;
247        this.falsePositiveRate = falsePositiveRate;
248        this.lowerThreshold = lowerThreshold;
249        this.upperThreshold = upperThreshold;
250
251      }
252      public double truePositiveRate { get; private set; }
253      public double falsePositiveRate { get; private set; }
254      public double lowerThreshold { get; private set; }
255      public double upperThreshold { get; private set; }
256    }
257
258  }
259}
Note: See TracBrowser for help on using the repository browser.