Free cookie consent management tool by TermsFeed Policy Generator

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

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

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

File size: 17.1 KB
RevLine 
[15638]1#region License Information
2
3/* HeuristicLab
[17180]4 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[15638]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;
[16422]25using System.Collections;
[15638]26using System.Collections.Generic;
27using System.Linq;
[17422]28using HEAL.Attic;
[15638]29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.Parameters;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Problems.DataAnalysis {
[16565]36  [StorableType("768AFEDB-5641-429E-85A1-A0BE8DFDD56F")]
[15638]37  [Item("ClassificationSolution Impacts Calculator", "Calculation of the impacts of input variables for any classification solution")]
38  public sealed class ClassificationSolutionVariableImpactsCalculator : ParameterizedNamedItem {
[16422]39    #region Parameters/Properties
[16565]40    [StorableType("e6cd2226-10cd-4765-ae1a-924e316b6aac")]
[15638]41    public enum ReplacementMethodEnum {
42      Median,
43      Average,
44      Shuffle,
45      Noise
46    }
[16565]47
48    [StorableType("84d84ccf-5d6d-432f-a946-eb499935e5c8")]
[15638]49    public enum FactorReplacementMethodEnum {
50      Best,
51      Mode,
52      Shuffle
53    }
[16565]54
55    [StorableType("70f30113-df01-41b4-9e3b-2982035de498")]
[15638]56    public enum DataPartitionEnum {
57      Training,
58      Test,
59      All
60    }
61
62    private const string ReplacementParameterName = "Replacement Method";
[16422]63    private const string FactorReplacementParameterName = "Factor Replacement Method";
[15638]64    private const string DataPartitionParameterName = "DataPartition";
65
66    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
67      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
68    }
[16422]69    public IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>> FactorReplacementParameter {
70      get { return (IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>>)Parameters[FactorReplacementParameterName]; }
71    }
[15638]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    }
[16422]80    public FactorReplacementMethodEnum FactorReplacementMethod {
81      get { return FactorReplacementParameter.Value.Value; }
82      set { FactorReplacementParameter.Value.Value = value; }
83    }
[15638]84    public DataPartitionEnum DataPartition {
85      get { return DataPartitionParameter.Value.Value; }
86      set { DataPartitionParameter.Value.Value = value; }
87    }
[16422]88    #endregion
[15638]89
[16422]90    #region Ctor/Cloner
[15638]91    [StorableConstructor]
[16565]92    private ClassificationSolutionVariableImpactsCalculator(StorableConstructorFlag _) : base(_) { }
[15638]93    private ClassificationSolutionVariableImpactsCalculator(ClassificationSolutionVariableImpactsCalculator original, Cloner cloner)
94      : base(original, cloner) { }
95    public ClassificationSolutionVariableImpactsCalculator()
96      : base() {
[16422]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)));
[15638]99      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
100    }
101
[16422]102    public override IDeepCloneable Clone(Cloner cloner) {
103      return new ClassificationSolutionVariableImpactsCalculator(this, cloner);
104    }
105    #endregion
106
[15638]107    //mkommend: annoying name clash with static method, open to better naming suggestions
108    public IEnumerable<Tuple<string, double>> Calculate(IClassificationSolution solution) {
[16422]109      return CalculateImpacts(solution, ReplacementMethod, FactorReplacementMethod, DataPartition);
[15638]110    }
111
112    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
113      IClassificationSolution solution,
[16422]114      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
115      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
116      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
[15638]117
[16422]118      IEnumerable<int> rows = GetPartitionRows(dataPartition, solution.ProblemData);
119      IEnumerable<double> estimatedClassValues = solution.GetEstimatedClassValues(rows);
[15871]120      var model = (IClassificationModel)solution.Model.Clone(); //mkommend: clone of model is necessary, because the thresholds for IDiscriminantClassificationModels are updated
[15638]121
[16422]122      return CalculateImpacts(model, solution.ProblemData, estimatedClassValues, rows, replacementMethod, factorReplacementMethod);
123    }
[15638]124
[16422]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) {
[15638]132
[16422]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)));
[15638]137      }
[16422]138      IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
139      var originalQuality = CalculateQuality(targetValues, estimatedClassValues);
[15638]140
141      var impacts = new Dictionary<string, double>();
[16422]142      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(model.VariablesUsedForPrediction));
143      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
[15638]144
[16422]145      foreach (var inputVariable in inputvariables) {
146        impacts[inputVariable] = CalculateImpact(inputVariable, model, problemData, modifiableDataset, rows, replacementMethod, factorReplacementMethod, targetValues, originalQuality);
147      }
[15638]148
[16422]149      return impacts.Select(i => Tuple.Create(i.Key, i.Value));
150    }
[15638]151
[16422]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));
[15638]165      }
166
[16422]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      }
[15638]173
[16422]174      IList originalValues = null;
[17422]175      IList replacementValues = GetReplacementValues(modifiableDataset, variableName, model, problemData.AllowedInputVariables, rows, targetValues, out originalValues, replacementMethod, factorReplacementMethod);
[15638]176
[17422]177      double newValue = CalculateQualityForReplacement(model, modifiableDataset, problemData.AllowedInputVariables, variableName, originalValues, rows, replacementValues, targetValues);
[16422]178      double impact = quality - newValue;
[15638]179
[16422]180      return impact;
[15638]181    }
182
[16422]183    private static IList GetReplacementValues(ModifiableDataset modifiableDataset,
184      string variableName,
185      IClassificationModel model,
[17422]186      IEnumerable<string> allowedInputVariables,
[16422]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();
[17422]199        replacementValues = GetReplacementValuesForString(model, modifiableDataset, allowedInputVariables, variableName, rows, (List<string>)originalValues, targetValues, factorReplacementMethod);
[16422]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;
[15638]214      double replacementValue;
215
[16422]216      switch (replacementMethod) {
[15638]217        case ReplacementMethodEnum.Median:
218          replacementValue = rows.Select(r => originalValues[r]).Median();
[16422]219          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[15638]220          break;
221        case ReplacementMethodEnum.Average:
222          replacementValue = rows.Select(r => originalValues[r]).Average();
[16422]223          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[15638]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
[16422]228          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[15638]229          // shuffle only the selected rows
[16422]230          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[15638]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
[16422]241          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[15638]242          // update column values
243          foreach (var r in rows) {
[16422]244            replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
[15638]245          }
246          break;
247
248        default:
[16422]249          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
[15638]250      }
251
[16422]252      return replacementValues;
[15638]253    }
254
[16422]255    private static IList GetReplacementValuesForString(IClassificationModel model,
256      ModifiableDataset modifiableDataset,
[17422]257      IEnumerable<string> allowedInputVariables,
[16422]258      string variableName,
[15638]259      IEnumerable<int> rows,
[16422]260      List<string> originalValues,
261      IEnumerable<double> targetValues,
262      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Shuffle) {
[15638]263
[16422]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
[17422]274            var newValue = CalculateQualityForReplacement(model, modifiableDataset, allowedInputVariables, variableName, originalValues, rows, curReplacementValues, targetValues);
[16422]275            var curQuality = newValue;
276
277            if (curQuality > bestQuality) {
278              bestQuality = curQuality;
279              replacementValues = curReplacementValues;
280            }
281          }
282          break;
[15638]283        case FactorReplacementMethodEnum.Mode:
284          var mostCommonValue = rows.Select(r => originalValues[r])
285            .GroupBy(v => v)
286            .OrderByDescending(g => g.Count())
287            .First().Key;
[16422]288          replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
[15638]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
[16422]293          replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
[15638]294          // shuffle only the selected rows
[16422]295          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[15638]296          int i = 0;
297          // update column values
298          foreach (var r in rows) {
299            replacementValues[r] = shuffledValues[i++];
300          }
301          break;
302        default:
[16422]303          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
[15638]304      }
305
[16422]306      return replacementValues;
[15638]307    }
308
[16422]309    private static double CalculateQualityForReplacement(
310      IClassificationModel model,
311      ModifiableDataset modifiableDataset,
[17422]312      IEnumerable<string> allowedInputVariables,
[16422]313      string variableName,
314      IList originalValues,
315      IEnumerable<int> rows,
316      IList replacementValues,
317      IEnumerable<double> targetValues) {
[15871]318
[16422]319      modifiableDataset.ReplaceVariable(variableName, replacementValues);
[15871]320      var discModel = model as IDiscriminantFunctionClassificationModel;
321      if (discModel != null) {
[17422]322        var problemData = new ClassificationProblemData(modifiableDataset, allowedInputVariables, model.TargetVariable);
[15871]323        discModel.RecalculateModelParameters(problemData, rows);
324      }
325
[15638]326      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
[16422]327      var estimates = model.GetEstimatedClassValues(modifiableDataset, rows).ToList();
328      var ret = CalculateQuality(targetValues, estimates);
329      modifiableDataset.ReplaceVariable(variableName, originalValues);
[15638]330
[16422]331      return ret;
[15638]332    }
[15871]333
[16422]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    }
[15871]340
[16422]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");
[15871]356      }
357
[16422]358      return rows;
[15638]359    }
360  }
[16422]361}
Note: See TracBrowser for help on using the repository browser.