Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionVariableImpactsCalculator.cs @ 17422

Last change on this file since 17422 was 17422, checked in by fholzing, 5 years ago

#3054: Explicitly used problemData.AllowedInputVariables instead of modifiableDataset.VariableNames

File size: 17.1 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 HEAL.Attic;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Parameters;
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, problemData.AllowedInputVariables, rows, targetValues, out originalValues, replacementMethod, factorReplacementMethod);
176
177      double newValue = CalculateQualityForReplacement(model, modifiableDataset, problemData.AllowedInputVariables, 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<string> allowedInputVariables,
187      IEnumerable<int> rows,
188      IEnumerable<double> targetValues,
189      out IList originalValues,
190      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
191      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
192
193      IList replacementValues = null;
194      if (modifiableDataset.VariableHasType<double>(variableName)) {
195        originalValues = modifiableDataset.GetReadOnlyDoubleValues(variableName).ToList();
196        replacementValues = GetReplacementValuesForDouble(modifiableDataset, rows, (List<double>)originalValues, replacementMethod);
197      } else if (modifiableDataset.VariableHasType<string>(variableName)) {
198        originalValues = modifiableDataset.GetReadOnlyStringValues(variableName).ToList();
199        replacementValues = GetReplacementValuesForString(model, modifiableDataset, allowedInputVariables, variableName, rows, (List<string>)originalValues, targetValues, factorReplacementMethod);
200      } else {
201        throw new NotSupportedException("Variable not supported");
202      }
203
204      return replacementValues;
205    }
206
207    private static IList GetReplacementValuesForDouble(ModifiableDataset modifiableDataset,
208      IEnumerable<int> rows,
209      List<double> originalValues,
210      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle) {
211
212      IRandom random = new FastRandom(31415);
213      List<double> replacementValues;
214      double replacementValue;
215
216      switch (replacementMethod) {
217        case ReplacementMethodEnum.Median:
218          replacementValue = rows.Select(r => originalValues[r]).Median();
219          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
220          break;
221        case ReplacementMethodEnum.Average:
222          replacementValue = rows.Select(r => originalValues[r]).Average();
223          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
224          break;
225        case ReplacementMethodEnum.Shuffle:
226          // new var has same empirical distribution but the relation to y is broken
227          // prepare a complete column for the dataset
228          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
229          // shuffle only the selected rows
230          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
231          int i = 0;
232          // update column values
233          foreach (var r in rows) {
234            replacementValues[r] = shuffledValues[i++];
235          }
236          break;
237        case ReplacementMethodEnum.Noise:
238          var avg = rows.Select(r => originalValues[r]).Average();
239          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
240          // prepare a complete column for the dataset
241          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
242          // update column values
243          foreach (var r in rows) {
244            replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
245          }
246          break;
247
248        default:
249          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
250      }
251
252      return replacementValues;
253    }
254
255    private static IList GetReplacementValuesForString(IClassificationModel model,
256      ModifiableDataset modifiableDataset,
257      IEnumerable<string> allowedInputVariables,
258      string variableName,
259      IEnumerable<int> rows,
260      List<string> originalValues,
261      IEnumerable<double> targetValues,
262      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Shuffle) {
263
264      List<string> replacementValues = null;
265      IRandom random = new FastRandom(31415);
266
267      switch (factorReplacementMethod) {
268        case FactorReplacementMethodEnum.Best:
269          // try replacing with all possible values and find the best replacement value
270          var bestQuality = double.NegativeInfinity;
271          foreach (var repl in modifiableDataset.GetStringValues(variableName, rows).Distinct()) {
272            List<string> curReplacementValues = Enumerable.Repeat(repl, modifiableDataset.Rows).ToList();
273            //fholzing: this result could be used later on (theoretically), but is neglected for better readability/method consistency
274            var newValue = CalculateQualityForReplacement(model, modifiableDataset, allowedInputVariables, variableName, originalValues, rows, curReplacementValues, targetValues);
275            var curQuality = newValue;
276
277            if (curQuality > bestQuality) {
278              bestQuality = curQuality;
279              replacementValues = curReplacementValues;
280            }
281          }
282          break;
283        case FactorReplacementMethodEnum.Mode:
284          var mostCommonValue = rows.Select(r => originalValues[r])
285            .GroupBy(v => v)
286            .OrderByDescending(g => g.Count())
287            .First().Key;
288          replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
289          break;
290        case FactorReplacementMethodEnum.Shuffle:
291          // new var has same empirical distribution but the relation to y is broken
292          // prepare a complete column for the dataset
293          replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
294          // shuffle only the selected rows
295          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
296          int i = 0;
297          // update column values
298          foreach (var r in rows) {
299            replacementValues[r] = shuffledValues[i++];
300          }
301          break;
302        default:
303          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
304      }
305
306      return replacementValues;
307    }
308
309    private static double CalculateQualityForReplacement(
310      IClassificationModel model,
311      ModifiableDataset modifiableDataset,
312      IEnumerable<string> allowedInputVariables,
313      string variableName,
314      IList originalValues,
315      IEnumerable<int> rows,
316      IList replacementValues,
317      IEnumerable<double> targetValues) {
318
319      modifiableDataset.ReplaceVariable(variableName, replacementValues);
320      var discModel = model as IDiscriminantFunctionClassificationModel;
321      if (discModel != null) {
322        var problemData = new ClassificationProblemData(modifiableDataset, allowedInputVariables, model.TargetVariable);
323        discModel.RecalculateModelParameters(problemData, rows);
324      }
325
326      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
327      var estimates = model.GetEstimatedClassValues(modifiableDataset, rows).ToList();
328      var ret = CalculateQuality(targetValues, estimates);
329      modifiableDataset.ReplaceVariable(variableName, originalValues);
330
331      return ret;
332    }
333
334    public static double CalculateQuality(IEnumerable<double> targetValues, IEnumerable<double> estimatedClassValues) {
335      OnlineCalculatorError errorState;
336      var ret = OnlineAccuracyCalculator.Calculate(targetValues, estimatedClassValues, out errorState);
337      if (errorState != OnlineCalculatorError.None) { throw new InvalidOperationException("Error during calculation with replaced inputs."); }
338      return ret;
339    }
340
341    public static IEnumerable<int> GetPartitionRows(DataPartitionEnum dataPartition, IClassificationProblemData problemData) {
342      IEnumerable<int> rows;
343
344      switch (dataPartition) {
345        case DataPartitionEnum.All:
346          rows = problemData.AllIndices;
347          break;
348        case DataPartitionEnum.Test:
349          rows = problemData.TestIndices;
350          break;
351        case DataPartitionEnum.Training:
352          rows = problemData.TrainingIndices;
353          break;
354        default:
355          throw new NotSupportedException("DataPartition not supported");
356      }
357
358      return rows;
359    }
360  }
361}
Note: See TracBrowser for help on using the repository browser.