Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2904_CalculateImpacts/3.4/Implementation/Regression/RegressionSolutionVariableImpactsCalculator.cs @ 16041

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

#2904: Removed ElementAt

File size: 17.4 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;
34
35namespace HeuristicLab.Problems.DataAnalysis {
36  [StorableClass]
37  [Item("RegressionSolution Impacts Calculator", "Calculation of the impacts of input variables for any regression solution")]
38  public sealed class RegressionSolutionVariableImpactsCalculator : ParameterizedNamedItem {
39    #region Parameters/Properties
40    public enum ReplacementMethodEnum {
41      Median,
42      Average,
43      Shuffle,
44      Noise
45    }
46    public enum FactorReplacementMethodEnum {
47      Best,
48      Mode,
49      Shuffle
50    }
51    public enum DataPartitionEnum {
52      Training,
53      Test,
54      All
55    }
56
57    private const string ReplacementParameterName = "Replacement Method";
58    private const string FactorReplacementParameterName = "Factor Replacement Method";
59    private const string DataPartitionParameterName = "DataPartition";
60
61    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
62      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
63    }
64    public IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>> FactorReplacementParameter {
65      get { return (IFixedValueParameter<EnumValue<FactorReplacementMethodEnum>>)Parameters[FactorReplacementParameterName]; }
66    }
67    public IFixedValueParameter<EnumValue<DataPartitionEnum>> DataPartitionParameter {
68      get { return (IFixedValueParameter<EnumValue<DataPartitionEnum>>)Parameters[DataPartitionParameterName]; }
69    }
70
71    public ReplacementMethodEnum ReplacementMethod {
72      get { return ReplacementParameter.Value.Value; }
73      set { ReplacementParameter.Value.Value = value; }
74    }
75    public FactorReplacementMethodEnum FactorReplacementMethod {
76      get { return FactorReplacementParameter.Value.Value; }
77      set { FactorReplacementParameter.Value.Value = value; }
78    }
79    public DataPartitionEnum DataPartition {
80      get { return DataPartitionParameter.Value.Value; }
81      set { DataPartitionParameter.Value.Value = value; }
82    }
83    #endregion
84
85    #region Ctor/Cloner
86    [StorableConstructor]
87    private RegressionSolutionVariableImpactsCalculator(bool deserializing) : base(deserializing) { }
88    private RegressionSolutionVariableImpactsCalculator(RegressionSolutionVariableImpactsCalculator original, Cloner cloner)
89      : base(original, cloner) { }
90    public RegressionSolutionVariableImpactsCalculator()
91      : base() {
92      Parameters.Add(new FixedValueParameter<EnumValue<ReplacementMethodEnum>>(ReplacementParameterName, "The replacement method for variables during impact calculation.", new EnumValue<ReplacementMethodEnum>(ReplacementMethodEnum.Median)));
93      Parameters.Add(new FixedValueParameter<EnumValue<FactorReplacementMethodEnum>>(FactorReplacementParameterName, "The replacement method for factor variables during impact calculation.", new EnumValue<FactorReplacementMethodEnum>(FactorReplacementMethodEnum.Best)));
94      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
95    }
96
97    public override IDeepCloneable Clone(Cloner cloner) {
98      return new RegressionSolutionVariableImpactsCalculator(this, cloner);
99    }
100    #endregion
101
102    //mkommend: annoying name clash with static method, open to better naming suggestions
103    public IEnumerable<Tuple<string, double>> Calculate(IRegressionSolution solution) {
104      return CalculateImpacts(solution, ReplacementMethod, FactorReplacementMethod, DataPartition);
105    }
106
107    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
108      IRegressionSolution solution,
109      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
110      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best,
111      DataPartitionEnum dataPartition = DataPartitionEnum.Training) {
112      IEnumerable<int> rows = (GetPartitionRows(dataPartition, solution.ProblemData));
113      IEnumerable<double> estimatedValues = solution.GetEstimatedValues(rows);
114      return CalculateImpacts(solution.Model, solution.ProblemData, estimatedValues, rows, replacementMethod, factorReplacementMethod);
115    }
116
117    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
118     IRegressionModel model,
119     IRegressionProblemData problemData,
120     IEnumerable<double> estimatedValues,
121     IEnumerable<int> rows,
122     ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
123     FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
124      //Calculate original quality-values (via calculator, default is R²)
125      OnlineCalculatorError error;
126      IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
127      var originalCalculatorValue = CalculateVariableImpact(targetValues, estimatedValues, out error);
128      if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation.");
129
130      var impacts = new Dictionary<string, double>();
131      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(model.VariablesUsedForPrediction));
132      var allowedInputVariables = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
133      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
134
135
136      foreach (var inputVariable in allowedInputVariables) {
137        if (model.VariablesUsedForPrediction.Contains(inputVariable)) {
138          impacts[inputVariable] = CalculateImpact(inputVariable, model, modifiableDataset, rows, targetValues, originalCalculatorValue, replacementMethod, factorReplacementMethod);
139        } else {
140          impacts[inputVariable] = 0;
141        }
142      }
143
144      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
145    }
146
147    public static double CalculateImpact(string variableName,
148      IRegressionModel model,
149      ModifiableDataset modifiableDataset,
150      IEnumerable<int> rows,
151      IEnumerable<double> targetValues,
152      double originalValue,
153      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Shuffle,
154      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
155      double impact = 0;
156      OnlineCalculatorError error;
157      IRandom random;
158      double replacementValue;
159      IEnumerable<double> newEstimates = null;
160      double newValue = 0;
161
162      if (modifiableDataset.VariableHasType<double>(variableName)) {
163        #region NumericalVariable
164        var originalValues = modifiableDataset.GetReadOnlyDoubleValues(variableName).ToList();
165        List<double> replacementValues;
166
167        switch (replacementMethod) {
168          case ReplacementMethodEnum.Median:
169            replacementValue = rows.Select(r => originalValues[r]).Median();
170            replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
171            break;
172          case ReplacementMethodEnum.Average:
173            replacementValue = rows.Select(r => originalValues[r]).Average();
174            replacementValues = Enumerable.Repeat(replacementValue, modifiableDataset.Rows).ToList();
175            break;
176          case ReplacementMethodEnum.Shuffle:
177            // new var has same empirical distribution but the relation to y is broken
178            random = new FastRandom(31415);
179            // prepare a complete column for the dataset
180            replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
181            // shuffle only the selected rows
182            var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
183            int i = 0;
184            // update column values
185            foreach (var r in rows) {
186              replacementValues[r] = shuffledValues[i++];
187            }
188            break;
189          case ReplacementMethodEnum.Noise:
190            var avg = rows.Select(r => originalValues[r]).Average();
191            var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
192            random = new FastRandom(31415);
193            // prepare a complete column for the dataset
194            replacementValues = Enumerable.Repeat(double.NaN, modifiableDataset.Rows).ToList();
195            // update column values
196            foreach (var r in rows) {
197              replacementValues[r] = NormalDistributedRandom.NextDouble(random, avg, stdDev);
198            }
199            break;
200
201          default:
202            throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacementMethod));
203        }
204
205        newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
206        newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
207        if (error != OnlineCalculatorError.None) { throw new InvalidOperationException("Error during calculation with replaced inputs."); }
208
209        impact = originalValue - newValue;
210        #endregion
211      } else if (modifiableDataset.VariableHasType<string>(variableName)) {
212        #region FactorVariable
213        var originalValues = modifiableDataset.GetReadOnlyStringValues(variableName).ToList();
214        List<string> replacementValues;
215
216        switch (factorReplacementMethod) {
217          case FactorReplacementMethodEnum.Best:
218            // try replacing with all possible values and find the best replacement value
219            var smallestImpact = double.PositiveInfinity;
220            foreach (var repl in modifiableDataset.GetStringValues(variableName, rows).Distinct()) {
221              newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, Enumerable.Repeat(repl, modifiableDataset.Rows).ToList());
222              newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
223              if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
224
225              var curImpact = originalValue - newValue;
226              if (curImpact < smallestImpact) smallestImpact = curImpact;
227            }
228            impact = smallestImpact;
229            break;
230          case FactorReplacementMethodEnum.Mode:
231            var mostCommonValue = rows.Select(r => originalValues[r])
232              .GroupBy(v => v)
233              .OrderByDescending(g => g.Count())
234              .First().Key;
235            replacementValues = Enumerable.Repeat(mostCommonValue, modifiableDataset.Rows).ToList();
236
237            newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
238            newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
239            if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
240
241            impact = originalValue - newValue;
242            break;
243          case FactorReplacementMethodEnum.Shuffle:
244            // new var has same empirical distribution but the relation to y is broken
245            random = new FastRandom(31415);
246            // prepare a complete column for the dataset
247            replacementValues = Enumerable.Repeat(string.Empty, modifiableDataset.Rows).ToList();
248            // shuffle only the selected rows
249            var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(random).ToList();
250            int i = 0;
251            // update column values
252            foreach (var r in rows) {
253              replacementValues[r] = shuffledValues[i++];
254            }
255
256            newEstimates = GetReplacedEstimates(originalValues, model, variableName, modifiableDataset, rows, replacementValues);
257            newValue = CalculateVariableImpact(targetValues, newEstimates, out error);
258            if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during calculation with replaced inputs.");
259
260            impact = originalValue - newValue;
261            break;
262          default:
263            throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", factorReplacementMethod));
264        }
265        #endregion
266      } else {
267        throw new NotSupportedException("Variable not supported");
268      }
269
270      return impact;
271    }
272
273    /// <summary>
274    /// Replaces the values of the original model-variables with the replacement variables, calculates the new estimated values
275    /// and changes the value of the model-variables back to the original ones.
276    /// </summary>
277    /// <param name="originalValues"></param>
278    /// <param name="model"></param>
279    /// <param name="variableName"></param>
280    /// <param name="modifiableDataset"></param>
281    /// <param name="rows"></param>
282    /// <param name="replacementValues"></param>
283    /// <returns></returns>
284    private static IEnumerable<double> GetReplacedEstimates(
285      IList originalValues,
286      IRegressionModel model,
287      string variableName,
288      ModifiableDataset modifiableDataset,
289      IEnumerable<int> rows,
290      IList replacementValues) {
291      modifiableDataset.ReplaceVariable(variableName, replacementValues);
292      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
293      var estimates = model.GetEstimatedValues(modifiableDataset, rows).ToList();
294      modifiableDataset.ReplaceVariable(variableName, originalValues);
295
296      return estimates;
297    }
298
299    /// <summary>
300    /// Calculates and returns the VariableImpact (calculated via Pearsons R²).
301    /// </summary>
302    /// <param name="targetValues">The actual values</param>
303    /// <param name="estimatedValues">The calculated/replaced values</param>
304    /// <param name="errorState"></param>
305    /// <returns></returns>
306    public static double CalculateVariableImpact(IEnumerable<double> targetValues, IEnumerable<double> estimatedValues, out OnlineCalculatorError errorState) {
307      //Theoretically, all calculators implement a static Calculate-Method which provides the same functionality
308      //as the code below does. But this way we can easily swap the calculator later on, so the user 
309      //could choose a Calculator during runtime in future versions.
310      IOnlineCalculator calculator = new OnlinePearsonsRSquaredCalculator();
311      IEnumerator<double> firstEnumerator = targetValues.GetEnumerator();
312      IEnumerator<double> secondEnumerator = estimatedValues.GetEnumerator();
313
314      // always move forward both enumerators (do not use short-circuit evaluation!)
315      while (firstEnumerator.MoveNext() & secondEnumerator.MoveNext()) {
316        double original = firstEnumerator.Current;
317        double estimated = secondEnumerator.Current;
318        calculator.Add(original, estimated);
319        if (calculator.ErrorState != OnlineCalculatorError.None) break;
320      }
321
322      // check if both enumerators are at the end to make sure both enumerations have the same length
323      if (calculator.ErrorState == OnlineCalculatorError.None &&
324           (secondEnumerator.MoveNext() || firstEnumerator.MoveNext())) {
325        throw new ArgumentException("Number of elements in first and second enumeration doesn't match.");
326      } else {
327        errorState = calculator.ErrorState;
328        return calculator.Value;
329      }
330    }
331
332    /// <summary>
333    /// Returns a collection of the row-indices for a given DataPartition (training or test)
334    /// </summary>
335    /// <param name="dataPartition"></param>
336    /// <param name="problemData"></param>
337    /// <returns></returns>
338    public static IEnumerable<int> GetPartitionRows(DataPartitionEnum dataPartition, IRegressionProblemData problemData) {
339      IEnumerable<int> rows;
340
341      switch (dataPartition) {
342        case DataPartitionEnum.All:
343          rows = problemData.AllIndices;
344          break;
345        case DataPartitionEnum.Test:
346          rows = problemData.TestIndices;
347          break;
348        case DataPartitionEnum.Training:
349          rows = problemData.TrainingIndices;
350          break;
351        default:
352          throw new NotSupportedException("DataPartition not supported");
353      }
354
355      return rows;
356    }
357  }
358}
Note: See TracBrowser for help on using the repository browser.