source: branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationEnsembleSolutionEstimatedClassValuesView.cs @ 7562

Last change on this file since 7562 was 7562, checked in by sforsten, 8 years ago

#1776:

  • bug fix in NeighbourhoodWeightCalculator
  • added GetConfidence method to IClassificationEnsembleSolutionWeightCalculator
  • adjusted the confidence column in ClassificationEnsembleSolutionEstimatedClassValuesView
File size: 8.4 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
21using System;
22using System.Collections.Generic;
23using System.Drawing;
24using System.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Common;
27using HeuristicLab.Data;
28using HeuristicLab.MainForm;
29using HeuristicLab.MainForm.WindowsForms;
30using HeuristicLab.Problems.DataAnalysis.Interfaces.Classification;
31
32namespace HeuristicLab.Problems.DataAnalysis.Views {
33  [View("Estimated Class Values")]
34  [Content(typeof(ClassificationEnsembleSolution))]
35  public partial class ClassificationEnsembleSolutionEstimatedClassValuesView :
36    ClassificationSolutionEstimatedClassValuesView {
37    private const string RowColumnName = "Row";
38    private const string TargetClassValuesColumnName = "Target Variable";
39    private const string EstimatedClassValuesColumnName = "Estimated Class Values";
40    private const string CorrectClassificationColumnName = "Correct Classification";
41    private const string ConfidenceColumnName = "Confidence";
42
43    private const string SamplesComboBoxAllSamples = "All Samples";
44    private const string SamplesComboBoxTrainingSamples = "Training Samples";
45    private const string SamplesComboBoxTestSamples = "Test Samples";
46
47    public new ClassificationEnsembleSolution Content {
48      get { return (ClassificationEnsembleSolution)base.Content; }
49      set { base.Content = value; }
50    }
51
52    public ClassificationEnsembleSolutionEstimatedClassValuesView()
53      : base() {
54      InitializeComponent();
55      SamplesComboBox.Items.AddRange(new string[] { SamplesComboBoxAllSamples, SamplesComboBoxTrainingSamples, SamplesComboBoxTestSamples });
56      SamplesComboBox.SelectedIndex = 0;
57      matrixView.DataGridView.RowPrePaint += new DataGridViewRowPrePaintEventHandler(DataGridView_RowPrePaint);
58    }
59
60
61
62    private void SamplesComboBox_SelectedIndexChanged(object sender, EventArgs e) {
63      UpdateEstimatedValues();
64    }
65
66    protected override void UpdateEstimatedValues() {
67      if (InvokeRequired) {
68        Invoke((Action)UpdateEstimatedValues);
69        return;
70      }
71      if (Content == null) {
72        matrixView.Content = null;
73        return;
74      }
75
76      int[] indizes;
77      double[] estimatedClassValues;
78
79      switch (SamplesComboBox.SelectedItem.ToString()) {
80        case SamplesComboBoxAllSamples: {
81            indizes = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray();
82            estimatedClassValues = Content.EstimatedClassValues.ToArray();
83            break;
84          }
85        case SamplesComboBoxTrainingSamples: {
86            indizes = Content.ProblemData.TrainingIndizes.ToArray();
87            estimatedClassValues = Content.EstimatedTrainingClassValues.ToArray();
88            break;
89          }
90        case SamplesComboBoxTestSamples: {
91            indizes = Content.ProblemData.TestIndizes.ToArray();
92            estimatedClassValues = Content.EstimatedTestClassValues.ToArray();
93            break;
94          }
95        default:
96          throw new ArgumentException();
97      }
98
99      IEnumerable<IClassificationSolution> solutions = Content.ClassificationSolutions.CheckedItems;
100      int classValuesCount = Content.ProblemData.ClassValues.Count;
101      int solutionsCount = solutions.Count();
102      string[,] values = new string[indizes.Length, 5 + classValuesCount + solutionsCount];
103      double[] target = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
104      List<List<double?>> estimatedValuesVector = GetEstimatedValues(SamplesComboBox.SelectedItem.ToString(), indizes,
105                                                            solutions);
106
107      IClassificationEnsembleSolutionWeightCalculator weightCalc = Content.WeightCalculator;
108
109      for (int i = 0; i < indizes.Length; i++) {
110        int row = indizes[i];
111        values[i, 0] = row.ToString();
112        values[i, 1] = target[i].ToString();
113        //display only indices and target values if no models are present
114        if (solutionsCount > 0) {
115          values[i, 2] = estimatedClassValues[i].ToString();
116          values[i, 3] = (target[i].IsAlmost(estimatedClassValues[i])).ToString();
117          values[i, 4] = weightCalc.GetConfidence(solutions, indizes[i], estimatedClassValues[i]).ToString();
118
119          var groups =
120            estimatedValuesVector[i].GroupBy(x => x).Select(g => new { Key = g.Key, Count = g.Count() }).ToList();
121          for (int classIndex = 0; classIndex < Content.ProblemData.ClassValues.Count; classIndex++) {
122            var group = groups.Where(g => g.Key == Content.ProblemData.ClassValues[classIndex]).SingleOrDefault();
123            if (group == null) values[i, 5 + classIndex] = 0.ToString();
124            else values[i, 5 + classIndex] = group.Count.ToString();
125          }
126          for (int modelIndex = 0; modelIndex < estimatedValuesVector[i].Count; modelIndex++) {
127            values[i, 5 + classValuesCount + modelIndex] = estimatedValuesVector[i][modelIndex] == null
128                                                             ? string.Empty
129                                                             : estimatedValuesVector[i][modelIndex].ToString();
130          }
131        }
132      }
133
134      StringMatrix matrix = new StringMatrix(values);
135      List<string> columnNames = new List<string>() { "Id", TargetClassValuesColumnName, EstimatedClassValuesColumnName, CorrectClassificationColumnName, ConfidenceColumnName };
136      columnNames.AddRange(Content.ProblemData.ClassNames);
137      columnNames.AddRange(Content.ClassificationSolutions.CheckedItems.Select(s => s.Model.Name));//.Model.Models.Select(m => m.Name));
138      matrix.ColumnNames = columnNames;
139      matrix.SortableView = true;
140      matrixView.Content = matrix;
141    }
142
143    private IEnumerable<int> FindAllIndices(List<double?> list, double value) {
144      List<int> indices = new List<int>();
145      for (int i = 0; i < list.Count; i++) {
146        if (list[i].Equals(value))
147          indices.Add(i);
148      }
149      return indices;
150    }
151
152    private List<List<double?>> GetEstimatedValues(string samplesSelection, int[] rows, IEnumerable<IClassificationSolution> solutions) {
153      List<List<double?>> values = new List<List<double?>>();
154      int solutionIndex = 0;
155      foreach (var solution in solutions) {
156        double[] estimation = solution.GetEstimatedClassValues(rows).ToArray();
157        for (int i = 0; i < rows.Length; i++) {
158          var row = rows[i];
159          if (solutionIndex == 0) values.Add(new List<double?>());
160
161          if (samplesSelection == SamplesComboBoxAllSamples)
162            values[i].Add(estimation[i]);
163          else if (samplesSelection == SamplesComboBoxTrainingSamples && solution.ProblemData.IsTrainingSample(row))
164            values[i].Add(estimation[i]);
165          else if (samplesSelection == SamplesComboBoxTestSamples && solution.ProblemData.IsTestSample(row))
166            values[i].Add(estimation[i]);
167          else
168            values[i].Add(null);
169        }
170        solutionIndex++;
171      }
172      return values;
173    }
174
175    private void DataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
176      if (InvokeRequired) {
177        Invoke(new EventHandler<DataGridViewRowPrePaintEventArgs>(DataGridView_RowPrePaint), sender, e);
178        return;
179      }
180      var cellValue = matrixView.DataGridView[3, e.RowIndex].Value.ToString();
181      if (string.IsNullOrEmpty(cellValue)) return;
182      bool correctClassified = bool.Parse(cellValue);
183      matrixView.DataGridView.Rows[e.RowIndex].DefaultCellStyle.ForeColor = correctClassified ? Color.MediumSeaGreen : Color.Red;
184    }
185  }
186}
Note: See TracBrowser for help on using the repository browser.