Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionVariableImpactsCalculator.cs @ 17709

Last change on this file since 17709 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

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