Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17399 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 16.9 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;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Parameters;
[16565]32using HEAL.Attic;
[15638]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;
175      IList replacementValues = GetReplacementValues(modifiableDataset, variableName, model, rows, targetValues, out originalValues, replacementMethod, factorReplacementMethod);
[15638]176
[16422]177      double newValue = CalculateQualityForReplacement(model, modifiableDataset, variableName, originalValues, rows, replacementValues, targetValues);
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,
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;
[15638]213      double replacementValue;
214
[16422]215      switch (replacementMethod) {
[15638]216        case ReplacementMethodEnum.Median:
217          replacementValue = rows.Select(r => originalValues[r]).Median();
[16422]218          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[15638]219          break;
220        case ReplacementMethodEnum.Average:
221          replacementValue = rows.Select(r => originalValues[r]).Average();
[16422]222          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[15638]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
[16422]227          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[15638]228          // shuffle only the selected rows
[16422]229          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[15638]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
[16422]240          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[15638]241          // update column values
242          foreach (var r in rows) {
[16422]243            replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
[15638]244          }
245          break;
246
247        default:
[16422]248          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
[15638]249      }
250
[16422]251      return replacementValues;
[15638]252    }
253
[16422]254    private static IList GetReplacementValuesForString(IClassificationModel model,
255      ModifiableDataset modifiableDataset,
256      string variableName,
[15638]257      IEnumerable<int> rows,
[16422]258      List<string> originalValues,
259      IEnumerable<double> targetValues,
260      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Shuffle) {
[15638]261
[16422]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;
[15638]281        case FactorReplacementMethodEnum.Mode:
282          var mostCommonValue = rows.Select(r => originalValues[r])
283            .GroupBy(v => v)
284            .OrderByDescending(g => g.Count())
285            .First().Key;
[16422]286          replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
[15638]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
[16422]291          replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
[15638]292          // shuffle only the selected rows
[16422]293          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[15638]294          int i = 0;
295          // update column values
296          foreach (var r in rows) {
297            replacementValues[r] = shuffledValues[i++];
298          }
299          break;
300        default:
[16422]301          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
[15638]302      }
303
[16422]304      return replacementValues;
[15638]305    }
306
[16422]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) {
[15871]315
[16422]316      modifiableDataset.ReplaceVariable(variableName, replacementValues);
[15871]317      var discModel = model as IDiscriminantFunctionClassificationModel;
318      if (discModel != null) {
[16422]319        var problemData = new ClassificationProblemData(modifiableDataset, modifiableDataset.VariableNames, model.TargetVariable);
[15871]320        discModel.RecalculateModelParameters(problemData, rows);
321      }
322
[15638]323      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
[16422]324      var estimates = model.GetEstimatedClassValues(modifiableDataset, rows).ToList();
325      var ret = CalculateQuality(targetValues, estimates);
326      modifiableDataset.ReplaceVariable(variableName, originalValues);
[15638]327
[16422]328      return ret;
[15638]329    }
[15871]330
[16422]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    }
[15871]337
[16422]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");
[15871]353      }
354
[16422]355      return rows;
[15638]356    }
357  }
[16422]358}
Note: See TracBrowser for help on using the repository browser.