Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15798 was 15798, checked in by fholzing, 6 years ago

#2871: Added additional linebreak for method signature

File size: 14.0 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.Generic;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Random;
33
34namespace HeuristicLab.Problems.DataAnalysis {
35  [StorableClass]
36  [Item("RegressionSolution Impacts Calculator", "Calculation of the impacts of input variables for any regression solution")]
37  public sealed class RegressionSolutionVariableImpactsCalculator : ParameterizedNamedItem {
38    public enum ReplacementMethodEnum {
39      Median,
40      Average,
41      Shuffle,
42      Noise
43    }
44    public enum FactorReplacementMethodEnum {
45      Best,
46      Mode,
47      Shuffle
48    }
49    public enum DataPartitionEnum {
50      Training,
51      Test,
52      All
53    }
54
55    private const string ReplacementParameterName = "Replacement Method";
56    private const string DataPartitionParameterName = "DataPartition";
57
58    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
59      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
60    }
61    public IFixedValueParameter<EnumValue<DataPartitionEnum>> DataPartitionParameter {
62      get { return (IFixedValueParameter<EnumValue<DataPartitionEnum>>)Parameters[DataPartitionParameterName]; }
63    }
64
65    public ReplacementMethodEnum ReplacementMethod {
66      get { return ReplacementParameter.Value.Value; }
67      set { ReplacementParameter.Value.Value = value; }
68    }
69    public DataPartitionEnum DataPartition {
70      get { return DataPartitionParameter.Value.Value; }
71      set { DataPartitionParameter.Value.Value = value; }
72    }
73
74
75    [StorableConstructor]
76    private RegressionSolutionVariableImpactsCalculator(bool deserializing) : base(deserializing) { }
77    private RegressionSolutionVariableImpactsCalculator(RegressionSolutionVariableImpactsCalculator original, Cloner cloner)
78      : base(original, cloner) { }
79    public override IDeepCloneable Clone(Cloner cloner) {
80      return new RegressionSolutionVariableImpactsCalculator(this, cloner);
81    }
82
83    public RegressionSolutionVariableImpactsCalculator()
84      : base() {
85      Parameters.Add(new FixedValueParameter<EnumValue<ReplacementMethodEnum>>(ReplacementParameterName, "The replacement method for variables during impact calculation.", new EnumValue<ReplacementMethodEnum>(ReplacementMethodEnum.Median)));
86      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
87    }
88
89    //mkommend: annoying name clash with static method, open to better naming suggestions
90    public IEnumerable<Tuple<string, double>> Calculate(IRegressionSolution solution) {
91      return CalculateImpacts(solution, DataPartition, ReplacementMethod);
92    }
93
94    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
95      IRegressionSolution solution,
96      DataPartitionEnum data = DataPartitionEnum.Training,
97      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Median,
98      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
99      Func<double, bool> progressCallback = null) {
100
101      var problemData = solution.ProblemData;
102      var dataset = problemData.Dataset;
103
104      IEnumerable<int> rows;
105      IEnumerable<double> targetValues;
106      double originalR2 = -1;
107
108      OnlineCalculatorError error;
109
110      switch (data) {
111        case DataPartitionEnum.All:
112          rows = solution.ProblemData.AllIndices;
113          targetValues = problemData.TargetVariableValues.ToList();
114          originalR2 = OnlinePearsonsRCalculator.Calculate(problemData.TargetVariableValues, solution.EstimatedValues, out error);
115          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation.");
116          originalR2 = originalR2 * originalR2;
117          break;
118        case DataPartitionEnum.Training:
119          rows = problemData.TrainingIndices;
120          targetValues = problemData.TargetVariableTrainingValues.ToList();
121          originalR2 = solution.TrainingRSquared;
122          break;
123        case DataPartitionEnum.Test:
124          rows = problemData.TestIndices;
125          targetValues = problemData.TargetVariableTestValues.ToList();
126          originalR2 = solution.TestRSquared;
127          break;
128        default: throw new ArgumentException(string.Format("DataPartition {0} cannot be handled.", data));
129      }
130
131      var impacts = new Dictionary<string, double>();
132      var modifiableDataset = ((Dataset)dataset).ToModifiable();
133
134      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(solution.Model.VariablesUsedForPrediction));
135      var allowedInputVariables = dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
136
137      int curIdx = 1;
138      int count = allowedInputVariables.Where(problemData.Dataset.VariableHasType<double>).Count();
139      // calculate impacts for double variables
140      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<double>)) {
141        //Report the current progress in percent. If the callback returns true, it means the execution shall be stopped
142        if (progressCallback != null) {
143          if (progressCallback((double)curIdx++ / count)) { return null; }
144        }
145        var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows, replacementMethod);
146        var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
147        if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
148
149        newR2 = newR2 * newR2;
150        var impact = originalR2 - newR2;
151        impacts[inputVariable] = impact;
152      }
153
154      // calculate impacts for string variables
155      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<string>)) {
156        if (factorReplacementMethod == FactorReplacementMethodEnum.Best) {
157          // try replacing with all possible values and find the best replacement value
158          var smallestImpact = double.PositiveInfinity;
159          foreach (var repl in problemData.Dataset.GetStringValues(inputVariable, rows).Distinct()) {
160            var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
161              Enumerable.Repeat(repl, dataset.Rows));
162            var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
163            if (error != OnlineCalculatorError.None)
164              throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
165
166            newR2 = newR2 * newR2;
167            var impact = originalR2 - newR2;
168            if (impact < smallestImpact) smallestImpact = impact;
169          }
170          impacts[inputVariable] = smallestImpact;
171        } else {
172          // for replacement methods shuffle and mode
173          // calculate impacts for factor variables
174
175          var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
176            factorReplacementMethod);
177          var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
178          if (error != OnlineCalculatorError.None)
179            throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
180
181          newR2 = newR2 * newR2;
182          var impact = originalR2 - newR2;
183          impacts[inputVariable] = impact;
184        }
185      } // foreach
186      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
187    }
188
189
190    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, ReplacementMethodEnum replacement = ReplacementMethodEnum.Median) {
191      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
192      double replacementValue;
193      List<double> replacementValues;
194      IRandom rand;
195
196      switch (replacement) {
197        case ReplacementMethodEnum.Median:
198          replacementValue = rows.Select(r => originalValues[r]).Median();
199          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
200          break;
201        case ReplacementMethodEnum.Average:
202          replacementValue = rows.Select(r => originalValues[r]).Average();
203          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
204          break;
205        case ReplacementMethodEnum.Shuffle:
206          // new var has same empirical distribution but the relation to y is broken
207          rand = new FastRandom(31415);
208          // prepare a complete column for the dataset
209          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
210          // shuffle only the selected rows
211          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
212          int i = 0;
213          // update column values
214          foreach (var r in rows) {
215            replacementValues[r] = shuffledValues[i++];
216          }
217          break;
218        case ReplacementMethodEnum.Noise:
219          var avg = rows.Select(r => originalValues[r]).Average();
220          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
221          rand = new FastRandom(31415);
222          // prepare a complete column for the dataset
223          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
224          // update column values
225          foreach (var r in rows) {
226            replacementValues[r] = NormalDistributedRandom.NextDouble(rand, avg, stdDev);
227          }
228          break;
229
230        default:
231          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacement));
232      }
233
234      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
235    }
236
237    private static IEnumerable<double> EvaluateModelWithReplacedVariable(
238      IRegressionModel model, string variable, ModifiableDataset dataset,
239      IEnumerable<int> rows,
240      FactorReplacementMethodEnum replacement = FactorReplacementMethodEnum.Shuffle) {
241      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
242      List<string> replacementValues;
243      IRandom rand;
244
245      switch (replacement) {
246        case FactorReplacementMethodEnum.Mode:
247          var mostCommonValue = rows.Select(r => originalValues[r])
248            .GroupBy(v => v)
249            .OrderByDescending(g => g.Count())
250            .First().Key;
251          replacementValues = Enumerable.Repeat(mostCommonValue, dataset.Rows).ToList();
252          break;
253        case FactorReplacementMethodEnum.Shuffle:
254          // new var has same empirical distribution but the relation to y is broken
255          rand = new FastRandom(31415);
256          // prepare a complete column for the dataset
257          replacementValues = Enumerable.Repeat(string.Empty, dataset.Rows).ToList();
258          // shuffle only the selected rows
259          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
260          int i = 0;
261          // update column values
262          foreach (var r in rows) {
263            replacementValues[r] = shuffledValues[i++];
264          }
265          break;
266        default:
267          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", replacement));
268      }
269
270      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
271    }
272
273    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable,
274      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<double> replacementValues) {
275      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
276      dataset.ReplaceVariable(variable, replacementValues.ToList());
277      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
278      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
279      dataset.ReplaceVariable(variable, originalValues);
280
281      return estimates;
282    }
283    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable,
284      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<string> replacementValues) {
285      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
286      dataset.ReplaceVariable(variable, replacementValues.ToList());
287      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
288      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
289      dataset.ReplaceVariable(variable, originalValues);
290
291      return estimates;
292    }
293  }
294}
Note: See TracBrowser for help on using the repository browser.