Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionBase.cs @ 16628

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

#2971: made branch compile with current version of trunk

File size: 10.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Data;
27using HeuristicLab.Optimization;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29using HeuristicLab.Problems.DataAnalysis.OnlineCalculators;
30using HEAL.Attic;
31
32namespace HeuristicLab.Problems.DataAnalysis {
33  [StorableType("4A461D10-7B42-48CA-8506-610DE870AF06")]
34  public abstract class ClassificationSolutionBase : DataAnalysisSolution, IClassificationSolution {
35    private const string TrainingAccuracyResultName = "Accuracy (training)";
36    private const string TestAccuracyResultName = "Accuracy (test)";
37    private const string TrainingNormalizedGiniCoefficientResultName = "Normalized Gini Coefficient (training)";
38    private const string TestNormalizedGiniCoefficientResultName = "Normalized Gini Coefficient (test)";
39    private const string ClassificationPerformanceMeasuresResultName = "Classification Performance Measures";
40
41    public new IClassificationModel Model {
42      get { return (IClassificationModel)base.Model; }
43      protected set { base.Model = value; }
44    }
45
46    public new IClassificationProblemData ProblemData {
47      get { return (IClassificationProblemData)base.ProblemData; }
48      set {
49        if (value == null) throw new ArgumentNullException("The problemData must not be null.");
50        string errorMessage = string.Empty;
51        if (!Model.IsProblemDataCompatible(value, out errorMessage)) throw new ArgumentException(errorMessage);
52
53        base.ProblemData = value;
54      }
55    }
56
57    #region Results
58    public double TrainingAccuracy {
59      get { return ((DoubleValue)this[TrainingAccuracyResultName].Value).Value; }
60      private set { ((DoubleValue)this[TrainingAccuracyResultName].Value).Value = value; }
61    }
62    public double TestAccuracy {
63      get { return ((DoubleValue)this[TestAccuracyResultName].Value).Value; }
64      private set { ((DoubleValue)this[TestAccuracyResultName].Value).Value = value; }
65    }
66    public double TrainingNormalizedGiniCoefficient {
67      get { return ((DoubleValue)this[TrainingNormalizedGiniCoefficientResultName].Value).Value; }
68      protected set { ((DoubleValue)this[TrainingNormalizedGiniCoefficientResultName].Value).Value = value; }
69    }
70    public double TestNormalizedGiniCoefficient {
71      get { return ((DoubleValue)this[TestNormalizedGiniCoefficientResultName].Value).Value; }
72      protected set { ((DoubleValue)this[TestNormalizedGiniCoefficientResultName].Value).Value = value; }
73    }
74    public ClassificationPerformanceMeasuresResultCollection ClassificationPerformanceMeasures {
75      get { return ((ClassificationPerformanceMeasuresResultCollection)this[ClassificationPerformanceMeasuresResultName].Value); }
76      protected set { (this[ClassificationPerformanceMeasuresResultName].Value) = value; }
77    }
78    #endregion
79
80    [StorableConstructor]
81    protected ClassificationSolutionBase(StorableConstructorFlag _) : base(_) { }
82    protected ClassificationSolutionBase(ClassificationSolutionBase original, Cloner cloner)
83      : base(original, cloner) {
84    }
85    protected ClassificationSolutionBase(IClassificationModel model, IClassificationProblemData problemData)
86      : base(model, problemData) {
87      Add(new Result(TrainingAccuracyResultName, "Accuracy of the model on the training partition (percentage of correctly classified instances).", new PercentValue()));
88      Add(new Result(TestAccuracyResultName, "Accuracy of the model on the test partition (percentage of correctly classified instances).", new PercentValue()));
89      Add(new Result(TrainingNormalizedGiniCoefficientResultName, "Normalized Gini coefficient of the model on the training partition.", new DoubleValue()));
90      Add(new Result(TestNormalizedGiniCoefficientResultName, "Normalized Gini coefficient of the model on the test partition.", new DoubleValue()));
91      Add(new Result(ClassificationPerformanceMeasuresResultName, @"Classification performance measures.\n
92                              In a multiclass classification all misclassifications of the negative class will be treated as true negatives except on positive class estimations.",
93                            new ClassificationPerformanceMeasuresResultCollection()));
94    }
95
96    [StorableHook(HookType.AfterDeserialization)]
97    private void AfterDeserialization() {
98      if (string.IsNullOrEmpty(Model.TargetVariable))
99        Model.TargetVariable = this.ProblemData.TargetVariable;
100
101      if (!this.ContainsKey(TrainingNormalizedGiniCoefficientResultName))
102        Add(new Result(TrainingNormalizedGiniCoefficientResultName, "Normalized Gini coefficient of the model on the training partition.", new DoubleValue()));
103      if (!this.ContainsKey(TestNormalizedGiniCoefficientResultName))
104        Add(new Result(TestNormalizedGiniCoefficientResultName, "Normalized Gini coefficient of the model on the test partition.", new DoubleValue()));
105      if (!this.ContainsKey(ClassificationPerformanceMeasuresResultName)) {
106        Add(new Result(ClassificationPerformanceMeasuresResultName, @"Classification performance measures.\n
107                              In a multiclass classification all misclassifications of the negative class will be treated as true negatives except on positive class estimations.",
108                              new ClassificationPerformanceMeasuresResultCollection()));
109        CalculateClassificationResults();
110      }
111    }
112
113    protected void CalculateClassificationResults() {
114      double[] estimatedTrainingClassValues = EstimatedTrainingClassValues.ToArray(); // cache values
115      double[] originalTrainingClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices).ToArray();
116
117      double[] estimatedTestClassValues = EstimatedTestClassValues.ToArray(); // cache values
118      double[] originalTestClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TestIndices).ToArray();
119
120      var positiveClassName = ProblemData.PositiveClass;
121      double positiveClassValue = ProblemData.GetClassValue(positiveClassName);
122      ClassificationPerformanceMeasuresCalculator trainingPerformanceCalculator = new ClassificationPerformanceMeasuresCalculator(positiveClassName, positiveClassValue);
123      ClassificationPerformanceMeasuresCalculator testPerformanceCalculator = new ClassificationPerformanceMeasuresCalculator(positiveClassName, positiveClassValue);
124
125      OnlineCalculatorError errorState;
126      double trainingAccuracy = OnlineAccuracyCalculator.Calculate(originalTrainingClassValues, estimatedTrainingClassValues, out errorState);
127      if (errorState != OnlineCalculatorError.None) trainingAccuracy = double.NaN;
128      double testAccuracy = OnlineAccuracyCalculator.Calculate(originalTestClassValues, estimatedTestClassValues, out errorState);
129      if (errorState != OnlineCalculatorError.None) testAccuracy = double.NaN;
130
131      TrainingAccuracy = trainingAccuracy;
132      TestAccuracy = testAccuracy;
133
134      double trainingNormalizedGini = NormalizedGiniCalculator.Calculate(originalTrainingClassValues, estimatedTrainingClassValues, out errorState);
135      if (errorState != OnlineCalculatorError.None) trainingNormalizedGini = double.NaN;
136      double testNormalizedGini = NormalizedGiniCalculator.Calculate(originalTestClassValues, estimatedTestClassValues, out errorState);
137      if (errorState != OnlineCalculatorError.None) testNormalizedGini = double.NaN;
138
139      TrainingNormalizedGiniCoefficient = trainingNormalizedGini;
140      TestNormalizedGiniCoefficient = testNormalizedGini;
141
142      ClassificationPerformanceMeasures.Reset();
143
144      trainingPerformanceCalculator.Calculate(originalTrainingClassValues, estimatedTrainingClassValues);
145      if (trainingPerformanceCalculator.ErrorState == OnlineCalculatorError.None)
146        ClassificationPerformanceMeasures.SetTrainingResults(trainingPerformanceCalculator);
147
148      testPerformanceCalculator.Calculate(originalTestClassValues, estimatedTestClassValues);
149      if (testPerformanceCalculator.ErrorState == OnlineCalculatorError.None)
150        ClassificationPerformanceMeasures.SetTestResults(testPerformanceCalculator);
151
152      if (ProblemData.Classes == 2) {
153        var f1Training = FOneScoreCalculator.Calculate(originalTrainingClassValues, estimatedTrainingClassValues, out errorState);
154        if (errorState == OnlineCalculatorError.None) ClassificationPerformanceMeasures.TrainingF1Score = f1Training;
155        var f1Test = FOneScoreCalculator.Calculate(originalTestClassValues, estimatedTestClassValues, out errorState);
156        if (errorState == OnlineCalculatorError.None) ClassificationPerformanceMeasures.TestF1Score = f1Test;
157      }
158
159      var mccTraining = MatthewsCorrelationCoefficientCalculator.Calculate(originalTrainingClassValues, estimatedTrainingClassValues, out errorState);
160      if (errorState == OnlineCalculatorError.None) ClassificationPerformanceMeasures.TrainingMatthewsCorrelation = mccTraining;
161      var mccTest = MatthewsCorrelationCoefficientCalculator.Calculate(originalTestClassValues, estimatedTestClassValues, out errorState);
162      if (errorState == OnlineCalculatorError.None) ClassificationPerformanceMeasures.TestMatthewsCorrelation = mccTest;
163    }
164
165    public abstract IEnumerable<double> EstimatedClassValues { get; }
166    public abstract IEnumerable<double> EstimatedTrainingClassValues { get; }
167    public abstract IEnumerable<double> EstimatedTestClassValues { get; }
168
169    public abstract IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows);
170
171    protected override void RecalculateResults() {
172      CalculateClassificationResults();
173    }
174  }
175}
Note: See TracBrowser for help on using the repository browser.