Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2971: made branch compile with current version of trunk

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