Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionVariableImpactsCalculator.cs @ 16432

Last change on this file since 16432 was 16432, checked in by mkommend, 5 years ago

#2884: Merged r15638, r15667, r15674, r15729, r15753, r16232 into stable.

File size: 14.0 KB
RevLine 
[15638]1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Collections.Generic;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Random;
33
34namespace HeuristicLab.Problems.DataAnalysis {
35  [StorableClass]
36  [Item("ClassificationSolution Impacts Calculator", "Calculation of the impacts of input variables for any classification solution")]
37  public sealed class ClassificationSolutionVariableImpactsCalculator : ParameterizedNamedItem {
38    public enum ReplacementMethodEnum {
39      Median,
40      Average,
41      Shuffle,
42      Noise
43    }
44    public enum FactorReplacementMethodEnum {
45      Best,
46      Mode,
47      Shuffle
48    }
49    public enum DataPartitionEnum {
50      Training,
51      Test,
52      All
53    }
54
55    private const string ReplacementParameterName = "Replacement Method";
56    private const string DataPartitionParameterName = "DataPartition";
57
58    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
59      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
60    }
61    public IFixedValueParameter<EnumValue<DataPartitionEnum>> DataPartitionParameter {
62      get { return (IFixedValueParameter<EnumValue<DataPartitionEnum>>)Parameters[DataPartitionParameterName]; }
63    }
64
65    public ReplacementMethodEnum ReplacementMethod {
66      get { return ReplacementParameter.Value.Value; }
67      set { ReplacementParameter.Value.Value = value; }
68    }
69    public DataPartitionEnum DataPartition {
70      get { return DataPartitionParameter.Value.Value; }
71      set { DataPartitionParameter.Value.Value = value; }
72    }
73
74
75    [StorableConstructor]
76    private ClassificationSolutionVariableImpactsCalculator(bool deserializing) : base(deserializing) { }
77    private ClassificationSolutionVariableImpactsCalculator(ClassificationSolutionVariableImpactsCalculator original, Cloner cloner)
78      : base(original, cloner) { }
79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new ClassificationSolutionVariableImpactsCalculator(this, cloner);
81    }
82
83    public ClassificationSolutionVariableImpactsCalculator()
84      : base() {
85      Parameters.Add(new FixedValueParameter<EnumValue<ReplacementMethodEnum>>(ReplacementParameterName, "The replacement method for variables during impact calculation.", new EnumValue<ReplacementMethodEnum>(ReplacementMethodEnum.Median)));
86      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
87    }
88
89    //mkommend: annoying name clash with static method, open to better naming suggestions
90    public IEnumerable<Tuple<string, double>> Calculate(IClassificationSolution solution) {
91      return CalculateImpacts(solution, DataPartition, ReplacementMethod);
92    }
93
94    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
95      IClassificationSolution solution,
96      DataPartitionEnum data = DataPartitionEnum.Training,
97      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Median,
98      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
99
100      var problemData = solution.ProblemData;
101      var dataset = problemData.Dataset;
102
103      IEnumerable<int> rows;
104      IEnumerable<double> targetValues;
105      double originalAccuracy;
106
107      OnlineCalculatorError error;
108
109      switch (data) {
110        case DataPartitionEnum.All:
111          rows = problemData.AllIndices;
112          targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.AllIndices).ToList();
113          originalAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, solution.EstimatedClassValues, out error);
114          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during accuracy calculation.");
115          break;
116        case DataPartitionEnum.Training:
117          rows = problemData.TrainingIndices;
118          targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToList();
119          originalAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, solution.EstimatedTrainingClassValues, out error);
120          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during accuracy calculation.");
121          break;
122        case DataPartitionEnum.Test:
123          rows = problemData.TestIndices;
124          targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToList();
125          originalAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, solution.EstimatedTestClassValues, out error);
126          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during accuracy calculation.");
127          break;
128        default: throw new ArgumentException(string.Format("DataPartition {0} cannot be handled.", data));
129      }
130
131      var impacts = new Dictionary<string, double>();
132      var modifiableDataset = ((Dataset)dataset).ToModifiable();
133
134      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(solution.Model.VariablesUsedForPrediction));
135      var allowedInputVariables = dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
136
137      // calculate impacts for double variables
138      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<double>)) {
139        var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows, replacementMethod);
140        var newAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, newEstimates, out error);
141        if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
142
143        impacts[inputVariable] = originalAccuracy - newAccuracy;
144      }
145
146      // calculate impacts for string variables
147      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<string>)) {
148        if (factorReplacementMethod == FactorReplacementMethodEnum.Best) {
149          // try replacing with all possible values and find the best replacement value
150          var smallestImpact = double.PositiveInfinity;
151          foreach (var repl in problemData.Dataset.GetStringValues(inputVariable, rows).Distinct()) {
152            var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
153              Enumerable.Repeat(repl, dataset.Rows));
154            var newAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, newEstimates, out error);
155            if (error != OnlineCalculatorError.None)
156              throw new InvalidOperationException("Error during accuracy calculation with replaced inputs.");
157
158            var impact = originalAccuracy - newAccuracy;
159            if (impact < smallestImpact) smallestImpact = impact;
160          }
161          impacts[inputVariable] = smallestImpact;
162        } else {
163          // for replacement methods shuffle and mode
164          // calculate impacts for factor variables
165
166          var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
167            factorReplacementMethod);
168          var newAccuracy = OnlineAccuracyCalculator.Calculate(targetValues, newEstimates, out error);
169          if (error != OnlineCalculatorError.None)
170            throw new InvalidOperationException("Error during accuracy calculation with replaced inputs.");
171
172          impacts[inputVariable] = originalAccuracy - newAccuracy;
173        }
174      } // foreach
175      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
176    }
177
178    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IClassificationModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, ReplacementMethodEnum replacement = ReplacementMethodEnum.Median) {
179      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
180      double replacementValue;
181      List<double> replacementValues;
182      IRandom rand;
183
184      switch (replacement) {
185        case ReplacementMethodEnum.Median:
186          replacementValue = rows.Select(r => originalValues[r]).Median();
187          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
188          break;
189        case ReplacementMethodEnum.Average:
190          replacementValue = rows.Select(r => originalValues[r]).Average();
191          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
192          break;
193        case ReplacementMethodEnum.Shuffle:
194          // new var has same empirical distribution but the relation to y is broken
195          rand = new FastRandom(31415);
196          // prepare a complete column for the dataset
197          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
198          // shuffle only the selected rows
199          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
200          int i = 0;
201          // update column values
202          foreach (var r in rows) {
203            replacementValues[r] = shuffledValues[i++];
204          }
205          break;
206        case ReplacementMethodEnum.Noise:
207          var avg = rows.Select(r => originalValues[r]).Average();
208          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
209          rand = new FastRandom(31415);
210          // prepare a complete column for the dataset
211          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
212          // update column values
213          foreach (var r in rows) {
214            replacementValues[r] = NormalDistributedRandom.NextDouble(rand, avg, stdDev);
215          }
216          break;
217
218        default:
219          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacement));
220      }
221
222      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
223    }
224
225    private static IEnumerable<double> EvaluateModelWithReplacedVariable(
226      IClassificationModel model, string variable, ModifiableDataset dataset,
227      IEnumerable<int> rows,
228      FactorReplacementMethodEnum replacement = FactorReplacementMethodEnum.Shuffle) {
229      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
230      List<string> replacementValues;
231      IRandom rand;
232
233      switch (replacement) {
234        case FactorReplacementMethodEnum.Mode:
235          var mostCommonValue = rows.Select(r => originalValues[r])
236            .GroupBy(v => v)
237            .OrderByDescending(g => g.Count())
238            .First().Key;
239          replacementValues = Enumerable.Repeat(mostCommonValue, dataset.Rows).ToList();
240          break;
241        case FactorReplacementMethodEnum.Shuffle:
242          // new var has same empirical distribution but the relation to y is broken
243          rand = new FastRandom(31415);
244          // prepare a complete column for the dataset
245          replacementValues = Enumerable.Repeat(string.Empty, dataset.Rows).ToList();
246          // shuffle only the selected rows
247          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
248          int i = 0;
249          // update column values
250          foreach (var r in rows) {
251            replacementValues[r] = shuffledValues[i++];
252          }
253          break;
254        default:
255          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", replacement));
256      }
257
258      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
259    }
260
261    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IClassificationModel model, string variable,
262      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<double> replacementValues) {
263      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
264      dataset.ReplaceVariable(variable, replacementValues.ToList());
265      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
266      var estimates = model.GetEstimatedClassValues(dataset, rows).ToList();
267      dataset.ReplaceVariable(variable, originalValues);
268
269      return estimates;
270    }
271    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IClassificationModel model, string variable,
272      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<string> replacementValues) {
273      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
274      dataset.ReplaceVariable(variable, replacementValues.ToList());
275      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
276      var estimates = model.GetEstimatedClassValues(dataset, rows).ToList();
277      dataset.ReplaceVariable(variable, originalValues);
278
279      return estimates;
280    }
281  }
282}
Note: See TracBrowser for help on using the repository browser.