Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17514 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 16.9 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 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;
26using System.Collections.Generic;
27using System.Linq;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Parameters;
32using HEAL.Attic;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Problems.DataAnalysis {
36  [StorableType("768AFEDB-5641-429E-85A1-A0BE8DFDD56F")]
37  [Item("ClassificationSolution Impacts Calculator", "Calculation of the impacts of input variables for any classification solution")]
38  public sealed class ClassificationSolutionVariableImpactsCalculator : ParameterizedNamedItem {
39    #region Parameters/Properties
40    [StorableType("e6cd2226-10cd-4765-ae1a-924e316b6aac")]
41    public enum ReplacementMethodEnum {
42      Median,
43      Average,
44      Shuffle,
45      Noise
46    }
47
48    [StorableType("84d84ccf-5d6d-432f-a946-eb499935e5c8")]
49    public enum FactorReplacementMethodEnum {
50      Best,
51      Mode,
52      Shuffle
53    }
54
55    [StorableType("70f30113-df01-41b4-9e3b-2982035de498")]
56    public enum DataPartitionEnum {
57      Training,
58      Test,
59      All
60    }
61
62    private const string ReplacementParameterName = "Replacement Method";
63    private const string FactorReplacementParameterName = "Factor Replacement Method";
64    private const string DataPartitionParameterName = "DataPartition";
65
66    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
67      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
68    }
69    public IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>> FactorReplacementParameter {
70      get { return (IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>>)Parameters[FactorReplacementParameterName]; }
71    }
72    public IFixedValueParameter<EnumValue<DataPartitionEnum>> DataPartitionParameter {
73      get { return (IFixedValueParameter<EnumValue<DataPartitionEnum>>)Parameters[DataPartitionParameterName]; }
74    }
75
76    public ReplacementMethodEnum ReplacementMethod {
77      get { return ReplacementParameter.Value.Value; }
78      set { ReplacementParameter.Value.Value = value; }
79    }
80    public FactorReplacementMethodEnum FactorReplacementMethod {
81      get { return FactorReplacementParameter.Value.Value; }
82      set { FactorReplacementParameter.Value.Value = value; }
83    }
84    public DataPartitionEnum DataPartition {
85      get { return DataPartitionParameter.Value.Value; }
86      set { DataPartitionParameter.Value.Value = value; }
87    }
88    #endregion
89
90    #region Ctor/Cloner
91    [StorableConstructor]
92    private ClassificationSolutionVariableImpactsCalculator(StorableConstructorFlag _) : base(_) { }
93    private ClassificationSolutionVariableImpactsCalculator(ClassificationSolutionVariableImpactsCalculator original, Cloner cloner)
94      : base(original, cloner) { }
95    public ClassificationSolutionVariableImpactsCalculator()
96      : base() {
97      Parameters.Add(new FixedValueParameter<EnumValue<ReplacementMethodEnum>>(ReplacementParameterName, "The replacement method for variables during impact calculation.", new EnumValue<ReplacementMethodEnum>(ReplacementMethodEnum.Shuffle)));
98      Parameters.Add(new FixedValueParameter<EnumValue<FactorReplacementMethodEnum>>(FactorReplacementParameterName, "The replacement method for factor variables during impact calculation.", new EnumValue<FactorReplacementMethodEnum>(FactorReplacementMethodEnum.Best)));
99      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
100    }
101
102    public override IDeepCloneable Clone(Cloner cloner) {
103      return new ClassificationSolutionVariableImpactsCalculator(this, cloner);
104    }
105    #endregion
106
107    //mkommend: annoying name clash with static method, open to better naming suggestions
108    public IEnumerable<Tuple<string, double>> Calculate(IClassificationSolution solution) {
109      return CalculateImpacts(solution, ReplacementMethod, FactorReplacementMethod, DataPartition);
110    }
111
112    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
113      IClassificationSolution solution,
114      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
115      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
116      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
117
118      IEnumerable<int> rows = GetPartitionRows(dataPartition, solution.ProblemData);
119      IEnumerable<double> estimatedClassValues = solution.GetEstimatedClassValues(rows);
120      var model = (IClassificationModel)solution.Model.Clone(); //mkommend: clone of model is necessary, because the thresholds for IDiscriminantClassificationModels are updated
121
122      return CalculateImpacts(model, solution.ProblemData, estimatedClassValues, rows, replacementMethod, factorReplacementMethod);
123    }
124
125    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
126     IClassificationModel model,
127     IClassificationProblemData problemData,
128     IEnumerable<double> estimatedClassValues,
129     IEnumerable<int> rows,
130     ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
131     FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
132
133      //fholzing: try and catch in case a different dataset is loaded, otherwise statement is neglectable
134      var missingVariables = model.VariablesUsedForPrediction.Except(problemData.Dataset.VariableNames);
135      if (missingVariables.Any()) {
136        throw new InvalidOperationException(string.Format("Can not calculate variable impacts, because the model uses inputs missing in the dataset ({0})", string.Join(", ", missingVariables)));
137      }
138      IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
139      var originalQuality = CalculateQuality(targetValues, estimatedClassValues);
140
141      var impacts = new Dictionary<string, double>();
142      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(model.VariablesUsedForPrediction));
143      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
144
145      foreach (var inputVariable in inputvariables) {
146        impacts[inputVariable] = CalculateImpact(inputVariable, model, problemData, modifiableDataset, rows, replacementMethod, factorReplacementMethod, targetValues, originalQuality);
147      }
148
149      return impacts.Select(i => Tuple.Create(i.Key, i.Value));
150    }
151
152    public static double CalculateImpact(string variableName,
153      IClassificationModel model,
154      IClassificationProblemData problemData,
155      ModifiableDataset modifiableDataset,
156      IEnumerable<int> rows,
157      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
158      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
159      IEnumerable<double> targetValues = null,
160      double quality = double.NaN) {
161
162      if (!model.VariablesUsedForPrediction.Contains(variableName)) { return 0.0; }
163      if (!problemData.Dataset.VariableNames.Contains(variableName)) {
164        throw new InvalidOperationException(string.Format("Can not calculate variable impact, because the model uses inputs missing in the dataset ({0})", variableName));
165      }
166
167      if (targetValues == null) {
168        targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
169      }
170      if (quality == double.NaN) {
171        quality = CalculateQuality(model.GetEstimatedClassValues(modifiableDataset, rows), targetValues);
172      }
173
174      IList originalValues = null;
175      IList replacementValues = GetReplacementValues(modifiableDataset, variableName, model, rows, targetValues, out originalValues, replacementMethod, factorReplacementMethod);
176
177      double newValue = CalculateQualityForReplacement(model, modifiableDataset, variableName, originalValues, rows, replacementValues, targetValues);
178      double impact = quality - newValue;
179
180      return impact;
181    }
182
183    private static IList GetReplacementValues(ModifiableDataset modifiableDataset,
184      string variableName,
185      IClassificationModel model,
186      IEnumerable<int> rows,
187      IEnumerable<double> targetValues,
188      out IList originalValues,
189      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
190      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
191
192      IList replacementValues = null;
193      if (modifiableDataset.VariableHasType<double>(variableName)) {
194        originalValues = modifiableDataset.GetReadOnlyDoubleValues(variableName).ToList();
195        replacementValues = GetReplacementValuesForDouble(modifiableDataset, rows, (List<double>)originalValues, replacementMethod);
196      } else if (modifiableDataset.VariableHasType<string>(variableName)) {
197        originalValues = modifiableDataset.GetReadOnlyStringValues(variableName).ToList();
198        replacementValues = GetReplacementValuesForString(model, modifiableDataset, variableName, rows, (List<string>)originalValues, targetValues, factorReplacementMethod);
199      } else {
200        throw new NotSupportedException("Variable not supported");
201      }
202
203      return replacementValues;
204    }
205
206    private static IList GetReplacementValuesForDouble(ModifiableDataset modifiableDataset,
207      IEnumerable<int> rows,
208      List<double> originalValues,
209      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle) {
210
211      IRandom random = new FastRandom(31415);
212      List<double> replacementValues;
213      double replacementValue;
214
215      switch (replacementMethod) {
216        case ReplacementMethodEnum.Median:
217          replacementValue = rows.Select(r => originalValues[r]).Median();
218          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
219          break;
220        case ReplacementMethodEnum.Average:
221          replacementValue = rows.Select(r => originalValues[r]).Average();
222          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
223          break;
224        case ReplacementMethodEnum.Shuffle:
225          // new var has same empirical distribution but the relation to y is broken
226          // prepare a complete column for the dataset
227          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
228          // shuffle only the selected rows
229          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
230          int i = 0;
231          // update column values
232          foreach (var r in rows) {
233            replacementValues[r] = shuffledValues[i++];
234          }
235          break;
236        case ReplacementMethodEnum.Noise:
237          var avg = rows.Select(r => originalValues[r]).Average();
238          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
239          // prepare a complete column for the dataset
240          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
241          // update column values
242          foreach (var r in rows) {
243            replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
244          }
245          break;
246
247        default:
248          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
249      }
250
251      return replacementValues;
252    }
253
254    private static IList GetReplacementValuesForString(IClassificationModel model,
255      ModifiableDataset modifiableDataset,
256      string variableName,
257      IEnumerable<int> rows,
258      List<string> originalValues,
259      IEnumerable<double> targetValues,
260      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Shuffle) {
261
262      List<string> replacementValues = null;
263      IRandom random = new FastRandom(31415);
264
265      switch (factorReplacementMethod) {
266        case FactorReplacementMethodEnum.Best:
267          // try replacing with all possible values and find the best replacement value
268          var bestQuality = double.NegativeInfinity;
269          foreach (var repl in modifiableDataset.GetStringValues(variableName, rows).Distinct()) {
270            List<string> curReplacementValues = Enumerable.Repeat(repl, modifiableDataset.Rows).ToList();
271            //fholzing: this result could be used later on (theoretically), but is neglected for better readability/method consistency
272            var newValue = CalculateQualityForReplacement(model, modifiableDataset, variableName, originalValues, rows, curReplacementValues, targetValues);
273            var curQuality = newValue;
274
275            if (curQuality > bestQuality) {
276              bestQuality = curQuality;
277              replacementValues = curReplacementValues;
278            }
279          }
280          break;
281        case FactorReplacementMethodEnum.Mode:
282          var mostCommonValue = rows.Select(r => originalValues[r])
283            .GroupBy(v => v)
284            .OrderByDescending(g => g.Count())
285            .First().Key;
286          replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
287          break;
288        case FactorReplacementMethodEnum.Shuffle:
289          // new var has same empirical distribution but the relation to y is broken
290          // prepare a complete column for the dataset
291          replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
292          // shuffle only the selected rows
293          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
294          int i = 0;
295          // update column values
296          foreach (var r in rows) {
297            replacementValues[r] = shuffledValues[i++];
298          }
299          break;
300        default:
301          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
302      }
303
304      return replacementValues;
305    }
306
307    private static double CalculateQualityForReplacement(
308      IClassificationModel model,
309      ModifiableDataset modifiableDataset,
310      string variableName,
311      IList originalValues,
312      IEnumerable<int> rows,
313      IList replacementValues,
314      IEnumerable<double> targetValues) {
315
316      modifiableDataset.ReplaceVariable(variableName, replacementValues);
317      var discModel = model as IDiscriminantFunctionClassificationModel;
318      if (discModel != null) {
319        var problemData = new ClassificationProblemData(modifiableDataset, modifiableDataset.VariableNames, model.TargetVariable);
320        discModel.RecalculateModelParameters(problemData, rows);
321      }
322
323      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
324      var estimates = model.GetEstimatedClassValues(modifiableDataset, rows).ToList();
325      var ret = CalculateQuality(targetValues, estimates);
326      modifiableDataset.ReplaceVariable(variableName, originalValues);
327
328      return ret;
329    }
330
331    public static double CalculateQuality(IEnumerable<double> targetValues, IEnumerable<double> estimatedClassValues) {
332      OnlineCalculatorError errorState;
333      var ret = OnlineAccuracyCalculator.Calculate(targetValues, estimatedClassValues, out errorState);
334      if (errorState != OnlineCalculatorError.None) { throw new InvalidOperationException("Error during calculation with replaced inputs."); }
335      return ret;
336    }
337
338    public static IEnumerable<int> GetPartitionRows(DataPartitionEnum dataPartition, IClassificationProblemData problemData) {
339      IEnumerable<int> rows;
340
341      switch (dataPartition) {
342        case DataPartitionEnum.All:
343          rows = problemData.AllIndices;
344          break;
345        case DataPartitionEnum.Test:
346          rows = problemData.TestIndices;
347          break;
348        case DataPartitionEnum.Training:
349          rows = problemData.TrainingIndices;
350          break;
351        default:
352          throw new NotSupportedException("DataPartition not supported");
353      }
354
355      return rows;
356    }
357  }
358}
Note: See TracBrowser for help on using the repository browser.