Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionVariableImpactsCalculator.cs @ 16640

Last change on this file since 16640 was 16640, checked in by gkronber, 5 years ago

#2971: merged r16565:16631 from trunk/HeuristicLab.Problems.DataAnalysis to branch/HeuristicLab.Problems.DataAnalysis (resolving all conflicts)

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