Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionVariableImpactsCalculator.cs @ 16752

Last change on this file since 16752 was 16565, checked in by gkronber, 6 years ago

#2520: merged changes from PersistenceOverhaul branch (r16451:16564) into trunk

File size: 16.3 KB
RevLine 
[13766]1#region License Information
2
3/* HeuristicLab
[16565]4 * Copyright (C) 2002-2019 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;
[16422]25using System.Collections;
[13766]26using System.Collections.Generic;
27using System.Linq;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Parameters;
[16565]32using HEAL.Attic;
[13986]33using HeuristicLab.Random;
[13766]34
35namespace HeuristicLab.Problems.DataAnalysis {
[16565]36  [StorableType("414B25CD-6643-4E42-9EB2-B9A24F5E1528")]
[13985]37  [Item("RegressionSolution Impacts Calculator", "Calculation of the impacts of input variables for any regression solution")]
[13766]38  public sealed class RegressionSolutionVariableImpactsCalculator : ParameterizedNamedItem {
[16422]39    #region Parameters/Properties
[16565]40    [StorableType("45a48ef7-e1e6-44b7-95b1-ae9d01aa5de4")]
[13766]41    public enum ReplacementMethodEnum {
42      Median,
[13986]43      Average,
44      Shuffle,
45      Noise
[13766]46    }
[16565]47
48    [StorableType("78df33f8-4715-4d25-a69a-f2bc1277fa3b")]
[14826]49    public enum FactorReplacementMethodEnum {
50      Best,
51      Mode,
52      Shuffle
53    }
[16565]54
55    [StorableType("946646da-1c0b-435e-88f9-38d649fc5194")]
[13766]56    public enum DataPartitionEnum {
57      Training,
58      Test,
59      All
60    }
[15796]61
[13766]62    private const string ReplacementParameterName = "Replacement Method";
[16422]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    }
[16422]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    }
[16422]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    }
[16422]88    #endregion
[13766]89
[16422]90    #region Ctor/Cloner
[13766]91    [StorableConstructor]
[16565]92    private RegressionSolutionVariableImpactsCalculator(StorableConstructorFlag _) : base(_) { }
[13766]93    private RegressionSolutionVariableImpactsCalculator(RegressionSolutionVariableImpactsCalculator original, Cloner cloner)
94      : base(original, cloner) { }
95    public RegressionSolutionVariableImpactsCalculator()
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)));
[13985]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
[16422]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) {
[16422]109      return CalculateImpacts(solution, ReplacementMethod, FactorReplacementMethod, DataPartition);
[13766]110    }
111
[14826]112    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
113      IRegressionSolution solution,
[16422]114      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
[15798]115      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
[16422]116      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
[13766]117
[16422]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
[16422]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
[16422]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      }
[16422]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>();
[16422]140      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(model.VariablesUsedForPrediction));
141      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
[13766]142
[16422]143      foreach (var inputVariable in inputvariables) {
144        impacts[inputVariable] = CalculateImpact(inputVariable, model, problemData, modifiableDataset, rows, replacementMethod, factorReplacementMethod, targetValues, originalQuality);
145      }
[14463]146
[16422]147      return impacts.Select(i => Tuple.Create(i.Key, i.Value));
148    }
[13766]149
[16422]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      }
[14826]164
[16422]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      }
[14826]171
[16422]172      IList originalValues = null;
173      IList replacementValues = GetReplacementValues(modifiableDataset, variableName, model, rows, targetValues, out originalValues, replacementMethod, factorReplacementMethod);
[14826]174
[16422]175      double newValue = CalculateQualityForReplacement(model, modifiableDataset, variableName, originalValues, rows, replacementValues, targetValues);
176      double impact = quality - newValue;
[14826]177
[16422]178      return impact;
[13766]179    }
180
[16422]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) {
[15796]189
[16422]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
[16422]213      switch (replacementMethod) {
[13766]214        case ReplacementMethodEnum.Median:
215          replacementValue = rows.Select(r => originalValues[r]).Median();
[16422]216          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[13766]217          break;
218        case ReplacementMethodEnum.Average:
219          replacementValue = rows.Select(r => originalValues[r]).Average();
[16422]220          replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
[13766]221          break;
[13986]222        case ReplacementMethodEnum.Shuffle:
223          // new var has same empirical distribution but the relation to y is broken
[14348]224          // prepare a complete column for the dataset
[16422]225          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[14348]226          // shuffle only the selected rows
[16422]227          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[14348]228          int i = 0;
229          // update column values
230          foreach (var r in rows) {
231            replacementValues[r] = shuffledValues[i++];
232          }
[13986]233          break;
234        case ReplacementMethodEnum.Noise:
235          var avg = rows.Select(r => originalValues[r]).Average();
236          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
[14348]237          // prepare a complete column for the dataset
[16422]238          replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
[14348]239          // update column values
240          foreach (var r in rows) {
[16422]241            replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
[14348]242          }
[13986]243          break;
244
[13766]245        default:
[16422]246          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
[13766]247      }
248
[16422]249      return replacementValues;
[14826]250    }
251
[16422]252    private static IList GetReplacementValuesForString(IRegressionModel model,
253      ModifiableDataset modifiableDataset,
254      string variableName,
[14826]255      IEnumerable<int> rows,
[16422]256      List<string> originalValues,
257      IEnumerable<double> targetValues,
258      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Shuffle) {
[14826]259
[16422]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;
[14826]279        case FactorReplacementMethodEnum.Mode:
280          var mostCommonValue = rows.Select(r => originalValues[r])
281            .GroupBy(v => v)
282            .OrderByDescending(g => g.Count())
283            .First().Key;
[16422]284          replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
[14826]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
[16422]289          replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
[14826]290          // shuffle only the selected rows
[16422]291          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
[14826]292          int i = 0;
293          // update column values
294          foreach (var r in rows) {
295            replacementValues[r] = shuffledValues[i++];
296          }
297          break;
298        default:
[16422]299          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
[14826]300      }
301
[16422]302      return replacementValues;
[14826]303    }
304
[16422]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
[16422]316      var estimates = model.GetEstimatedValues(modifiableDataset, rows).ToList();
317      var ret = CalculateQuality(targetValues, estimates);
318      modifiableDataset.ReplaceVariable(variableName, originalValues);
[13766]319
[16422]320      return ret;
[13766]321    }
[14826]322
[16422]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;
[14826]328    }
[16422]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  }
[16422]350}
Note: See TracBrowser for help on using the repository browser.