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

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

#1776:

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