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

Last change on this file since 16036 was 16036, checked in by fholzing, 3 years ago

#2904: Streamlined the variableimpactcalculator code on both Regression and Classification. Taken over the regression-code for classification with some minor adaptations.

File size: 18.0 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<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
94    }
95
96    public override IDeepCloneable Clone(Cloner cloner) {
97      return new ClassificationSolutionVariableImpactsCalculator(this, cloner);
98    }
99    #endregion
100
101    //mkommend: annoying name clash with static method, open to better naming suggestions
102    public IEnumerable<Tuple<string, double>> Calculate(IClassificationSolution solution) {
103      return CalculateImpacts(solution, ReplacementMethod, FactorReplacementMethod, DataPartition);
104    }
105
106    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
107      IClassificationSolution solution,
108      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
109      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
110      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
111      return CalculateImpacts(solution.Model, solution.ProblemData, solution.EstimatedClassValues, replacementMethod, factorReplacementMethod, dataPartition);
112    }
113
114    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
115      IClassificationModel model,
116      IClassificationProblemData problemData,
117      IEnumerable<double> estimatedValues,
118      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
119      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
120      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
121      IEnumerable<int> rows = GetPartitionRows(dataPartition, problemData);
122      return CalculateImpacts(model, problemData, estimatedValues, rows, replacementMethod, factorReplacementMethod);
123    }
124
125
126    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
127     IClassificationModel model,
128     IClassificationProblemData problemData,
129     IEnumerable<double> estimatedClassValues,
130     IEnumerable<int> rows,
131     ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
132     FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
133      //Calculate original quality-values (via calculator, default is Accuracy)
134      OnlineCalculatorError error;
135      IEnumerable<double> targetValuesPartition = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
136      IEnumerable<double> estimatedValuesPartition = rows.Select(v => estimatedClassValues.ElementAt(v));
137      var originalCalculatorValue = CalculateVariableImpact(targetValuesPartition, estimatedValuesPartition, out error);
138      if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation.");
139
140      var impacts = new Dictionary<string, double>();
141      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(model.VariablesUsedForPrediction));
142      var allowedInputVariables = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
143      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
144
145      foreach (var inputVariable in allowedInputVariables) {
146        impacts[inputVariable] = CalculateImpact(inputVariable, model, modifiableDataset, rows, targetValuesPartition, originalCalculatorValue, replacementMethod, factorReplacementMethod);
147      }
148
149      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
150    }
151
152
153    public static double CalculateImpact(string variableName,
154      IClassificationModel model,
155      ModifiableDataset modifiableDataset,
156      IEnumerable<int> rows,
157      IEnumerable<double> targetValues,
158      double originalValue,
159      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
160      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
161      double impact = 0;
162      OnlineCalculatorError error;
163      IRandom random;
164      double replacementValue;
165      IEnumerable<double> newEstimates = null;
166      double newValue = 0;
167
168      if (modifiableDataset.VariableHasType<double>(variableName)) {
169        #region NumericalVariable
170        var originalValues = modifiableDataset.GetReadOnlyDoubleValues(variableName).ToList();
171        List<double> replacementValues;
172        IRandom rand;
173
174        switch (replacementMethod) {
175          case ReplacementMethodEnum.Median:
176            replacementValue = rows.Select(r => originalValues[r]).Median();
177            replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
178            break;
179          case ReplacementMethodEnum.Average:
180            replacementValue = rows.Select(r => originalValues[r]).Average();
181            replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
182            break;
183          case ReplacementMethodEnum.Shuffle:
184            // new var has same empirical distribution but the relation to y is broken
185            rand = new FastRandom(31415);
186            // prepare a complete column for the dataset
187            replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
188            // shuffle only the selected rows
189            var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
190            int i = 0;
191            // update column values
192            foreach (var r in rows) {
193              replacementValues[r] = shuffledValues[i++];
194            }
195            break;
196          case ReplacementMethodEnum.Noise:
197            var avg = rows.Select(r => originalValues[r]).Average();
198            var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
199            rand = new FastRandom(31415);
200            // prepare a complete column for the dataset
201            replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
202            // update column values
203            foreach (var r in rows) {
204              replacementValues[r] = NormalDistributedRandom.NextDouble(rand, avg, stdDev);
205            }
206            break;
207
208          default:
209            throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
210        }
211
212        newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
213        newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
214        if (error != OnlineCalculatorError.None) { throw new InvalidOperationException("Error during calculation with replaced inputs."); }
215
216        impact = originalValue - newValue;
217        #endregion
218      } else if (modifiableDataset.VariableHasType<string>(variableName)) {
219        #region FactorVariable
220        var originalValues = modifiableDataset.GetReadOnlyStringValues(variableName).ToList();
221        List<string> replacementValues;
222
223        switch (factorReplacementMethod) {
224          case FactorReplacementMethodEnum.Best:
225            // try replacing with all possible values and find the best replacement value
226            var smallestImpact = double.PositiveInfinity;
227            foreach (var repl in modifiableDataset.GetStringValues(variableName, rows).Distinct()) {
228              newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, Enumerable.Repeat(repl, modifiableDataset.Rows).ToList());
229              newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
230              if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
231
232              var curImpact = originalValue - newValue;
233              if (curImpact < smallestImpact) smallestImpact = curImpact;
234            }
235            impact = smallestImpact;
236            break;
237          case FactorReplacementMethodEnum.Mode:
238            var mostCommonValue = rows.Select(r => originalValues[r])
239              .GroupBy(v => v)
240              .OrderByDescending(g => g.Count())
241              .First().Key;
242            replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
243
244            newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
245            newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
246            if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
247
248            impact = originalValue - newValue;
249            break;
250          case FactorReplacementMethodEnum.Shuffle:
251            // new var has same empirical distribution but the relation to y is broken
252            random = new FastRandom(31415);
253            // prepare a complete column for the dataset
254            replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
255            // shuffle only the selected rows
256            var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
257            int i = 0;
258            // update column values
259            foreach (var r in rows) {
260              replacementValues[r] = shuffledValues[i++];
261            }
262
263            newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
264            newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
265            if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
266
267            impact = originalValue - newValue;
268            break;
269          default:
270            throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
271        }
272        #endregion
273      } else {
274        throw new NotSupportedException("Variable not supported");
275      }
276
277      return impact;
278    }
279
280    /// <summary>
281    /// Calculates and returns the VariableImpact (calculated via Accuracy).
282    /// </summary>
283    /// <param name="targetValues">The actual values</param>
284    /// <param name="estimatedValues">The calculated/replaced values</param>
285    /// <param name="errorState"></param>
286    /// <returns></returns>
287    public static double CalculateVariableImpact(IEnumerable<double> targetValues, IEnumerable<double> estimatedValues, out OnlineCalculatorError errorState) {
288      //Theoretically, all calculators implement a static Calculate-Method which provides the same functionality
289      //as the code below does. But this way we can easily swap the calculator later on, so the user 
290      //could choose a Calculator during runtime in future versions.
291      IOnlineCalculator calculator = new OnlineAccuracyCalculator();
292      IEnumerator<double> firstEnumerator = targetValues.GetEnumerator();
293      IEnumerator<double> secondEnumerator = estimatedValues.GetEnumerator();
294
295      // always move forward both enumerators (do not use short-circuit evaluation!)
296      while (firstEnumerator.MoveNext() & secondEnumerator.MoveNext()) {
297        double original = firstEnumerator.Current;
298        double estimated = secondEnumerator.Current;
299        calculator.Add(original, estimated);
300        if (calculator.ErrorState != OnlineCalculatorError.None) break;
301      }
302
303      // check if both enumerators are at the end to make sure both enumerations have the same length
304      if (calculator.ErrorState == OnlineCalculatorError.None &&
305           (secondEnumerator.MoveNext() || firstEnumerator.MoveNext())) {
306        throw new ArgumentException("Number of elements in first and second enumeration doesn't match.");
307      } else {
308        errorState = calculator.ErrorState;
309        return calculator.Value;
310      }
311    }
312
313    /// <summary>
314    /// Replaces the values of the original model-variables with the replacement variables, calculates the new estimated values
315    /// and changes the value of the model-variables back to the original ones.
316    /// </summary>
317    /// <param name="originalValues"></param>
318    /// <param name="model"></param>
319    /// <param name="variableName"></param>
320    /// <param name="modifiableDataset"></param>
321    /// <param name="rows"></param>
322    /// <param name="replacementValues"></param>
323    /// <returns></returns>
324    private static IEnumerable<double> GetReplacedEstimates(
325     IList originalValues,
326     IClassificationModel model,
327     string variableName,
328     ModifiableDataset modifiableDataset,
329     IEnumerable<int> rows,
330     IList replacementValues) {
331      modifiableDataset.ReplaceVariable(variableName, replacementValues);
332
333      var discModel = model as IDiscriminantFunctionClassificationModel;
334      if (discModel != null) {
335        var problemData = new ClassificationProblemData(modifiableDataset, modifiableDataset.VariableNames, model.TargetVariable);
336        discModel.RecalculateModelParameters(problemData, rows);
337      }
338
339      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
340      var estimates = model.GetEstimatedClassValues(modifiableDataset, rows).ToList();
341      modifiableDataset.ReplaceVariable(variableName, originalValues);
342
343      return estimates;
344    }
345
346
347    /// <summary>
348    /// Returns a collection of the row-indices for a given DataPartition (training or test)
349    /// </summary>
350    /// <param name="dataPartition"></param>
351    /// <param name="problemData"></param>
352    /// <returns></returns>
353    public static IEnumerable<int> GetPartitionRows(DataPartitionEnum dataPartition, IClassificationProblemData problemData) {
354      IEnumerable<int> rows;
355
356      switch (dataPartition) {
357        case DataPartitionEnum.All:
358          rows = problemData.AllIndices;
359          break;
360        case DataPartitionEnum.Test:
361          rows = problemData.TestIndices;
362          break;
363        case DataPartitionEnum.Training:
364          rows = problemData.TrainingIndices;
365          break;
366        default:
367          throw new NotSupportedException("DataPartition not supported");
368      }
369
370      return rows;
371    }
372
373  }
374}
Note: See TracBrowser for help on using the repository browser.