source: branches/2904_CalculateImpacts/3.4/Implementation/Classification/ClassificationSolutionVariableImpactsCalculator.cs @ 16190

Last change on this file since 16190 was 16190, checked in by fholzing, 12 months ago

#2904: Added changes from #2910 to ClassificationSolutionVariableImpactsCalculator

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