Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15529 was 14826, checked in by gkronber, 8 years ago

#2650: merged the factors branch into trunk

File size: 13.6 KB
RevLine 
[13766]1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2016 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;
[13986]32using HeuristicLab.Random;
[13766]33
34namespace HeuristicLab.Problems.DataAnalysis {
35  [StorableClass]
[13985]36  [Item("RegressionSolution Impacts Calculator", "Calculation of the impacts of input variables for any regression solution")]
[13766]37  public sealed class RegressionSolutionVariableImpactsCalculator : ParameterizedNamedItem {
38    public enum ReplacementMethodEnum {
39      Median,
[13986]40      Average,
41      Shuffle,
42      Noise
[13766]43    }
[14826]44    public enum FactorReplacementMethodEnum {
45      Best,
46      Mode,
47      Shuffle
48    }
[13766]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)));
[13985]86      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
[13766]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
[14826]94    public static IEnumerable<Tuple<string, double>> CalculateImpacts(
95      IRegressionSolution solution,
[13766]96      DataPartitionEnum data = DataPartitionEnum.Training,
[14826]97      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Median,
98      FactorReplacementMethodEnum factorReplacementMethod = FactorReplacementMethodEnum.Best) {
[13766]99
100      var problemData = solution.ProblemData;
101      var dataset = problemData.Dataset;
102
103      IEnumerable<int> rows;
104      IEnumerable<double> targetValues;
105      double originalR2 = -1;
106
107      OnlineCalculatorError error;
108
109      switch (data) {
110        case DataPartitionEnum.All:
111          rows = solution.ProblemData.AllIndices;
112          targetValues = problemData.TargetVariableValues.ToList();
113          originalR2 = OnlinePearsonsRCalculator.Calculate(problemData.TargetVariableValues, solution.EstimatedValues, out error);
114          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation.");
115          originalR2 = originalR2 * originalR2;
116          break;
117        case DataPartitionEnum.Training:
118          rows = problemData.TrainingIndices;
119          targetValues = problemData.TargetVariableTrainingValues.ToList();
120          originalR2 = solution.TrainingRSquared;
121          break;
122        case DataPartitionEnum.Test:
123          rows = problemData.TestIndices;
124          targetValues = problemData.TargetVariableTestValues.ToList();
125          originalR2 = solution.TestRSquared;
126          break;
127        default: throw new ArgumentException(string.Format("DataPartition {0} cannot be handled.", data));
128      }
129
130      var impacts = new Dictionary<string, double>();
131      var modifiableDataset = ((Dataset)dataset).ToModifiable();
132
[14463]133      var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(solution.Model.VariablesUsedForPrediction));
134      var allowedInputVariables = dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
135
[14826]136      // calculate impacts for double variables
137      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<double>)) {
138        var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows, replacementMethod);
[13766]139        var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
140        if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
141
142        newR2 = newR2 * newR2;
143        var impact = originalR2 - newR2;
144        impacts[inputVariable] = impact;
145      }
[14826]146
147      // calculate impacts for string variables
148      foreach (var inputVariable in allowedInputVariables.Where(problemData.Dataset.VariableHasType<string>)) {
149        if (factorReplacementMethod == FactorReplacementMethodEnum.Best) {
150          // try replacing with all possible values and find the best replacement value
151          var smallestImpact = double.PositiveInfinity;
152          foreach (var repl in problemData.Dataset.GetStringValues(inputVariable, rows).Distinct()) {
153            var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
154              Enumerable.Repeat(repl, dataset.Rows));
155            var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
156            if (error != OnlineCalculatorError.None)
157              throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
158
159            newR2 = newR2 * newR2;
160            var impact = originalR2 - newR2;
161            if (impact < smallestImpact) smallestImpact = impact;
162          }
163          impacts[inputVariable] = smallestImpact;
164        } else {
165          // for replacement methods shuffle and mode
166          // calculate impacts for factor variables
167
168          var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows,
169            factorReplacementMethod);
170          var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
171          if (error != OnlineCalculatorError.None)
172            throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
173
174          newR2 = newR2 * newR2;
175          var impact = originalR2 - newR2;
176          impacts[inputVariable] = impact;
177        }
178      } // foreach
[13766]179      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
180    }
181
182    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, ReplacementMethodEnum replacement = ReplacementMethodEnum.Median) {
183      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
184      double replacementValue;
[13986]185      List<double> replacementValues;
186      IRandom rand;
[13766]187
188      switch (replacement) {
189        case ReplacementMethodEnum.Median:
190          replacementValue = rows.Select(r => originalValues[r]).Median();
[13986]191          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
[13766]192          break;
193        case ReplacementMethodEnum.Average:
194          replacementValue = rows.Select(r => originalValues[r]).Average();
[13986]195          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
[13766]196          break;
[13986]197        case ReplacementMethodEnum.Shuffle:
198          // new var has same empirical distribution but the relation to y is broken
199          rand = new FastRandom(31415);
[14348]200          // prepare a complete column for the dataset
201          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
202          // shuffle only the selected rows
203          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
204          int i = 0;
205          // update column values
206          foreach (var r in rows) {
207            replacementValues[r] = shuffledValues[i++];
208          }
[13986]209          break;
210        case ReplacementMethodEnum.Noise:
211          var avg = rows.Select(r => originalValues[r]).Average();
212          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
213          rand = new FastRandom(31415);
[14348]214          // prepare a complete column for the dataset
215          replacementValues = Enumerable.Repeat(double.NaN, dataset.Rows).ToList();
216          // update column values
217          foreach (var r in rows) {
218            replacementValues[r] = NormalDistributedRandom.NextDouble(rand, avg, stdDev);
219          }
[13986]220          break;
221
[13766]222        default:
223          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacement));
224      }
225
[14826]226      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
227    }
228
229    private static IEnumerable<double> EvaluateModelWithReplacedVariable(
230      IRegressionModel model, string variable, ModifiableDataset dataset,
231      IEnumerable<int> rows,
232      FactorReplacementMethodEnum replacement = FactorReplacementMethodEnum.Shuffle) {
233      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
234      List<string> replacementValues;
235      IRandom rand;
236
237      switch (replacement) {
238        case FactorReplacementMethodEnum.Mode:
239          var mostCommonValue = rows.Select(r => originalValues[r])
240            .GroupBy(v => v)
241            .OrderByDescending(g => g.Count())
242            .First().Key;
243          replacementValues = Enumerable.Repeat(mostCommonValue, dataset.Rows).ToList();
244          break;
245        case FactorReplacementMethodEnum.Shuffle:
246          // new var has same empirical distribution but the relation to y is broken
247          rand = new FastRandom(31415);
248          // prepare a complete column for the dataset
249          replacementValues = Enumerable.Repeat(string.Empty, dataset.Rows).ToList();
250          // shuffle only the selected rows
251          var shuffledValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
252          int i = 0;
253          // update column values
254          foreach (var r in rows) {
255            replacementValues[r] = shuffledValues[i++];
256          }
257          break;
258        default:
259          throw new ArgumentException(string.Format("FactorReplacementMethod {0} cannot be handled.", replacement));
260      }
261
262      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
263    }
264
265    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable,
266      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<double> replacementValues) {
267      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
268      dataset.ReplaceVariable(variable, replacementValues.ToList());
[13766]269      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
270      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
271      dataset.ReplaceVariable(variable, originalValues);
272
273      return estimates;
274    }
[14826]275    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable,
276      ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<string> replacementValues) {
277      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
278      dataset.ReplaceVariable(variable, replacementValues.ToList());
279      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
280      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
281      dataset.ReplaceVariable(variable, originalValues);
282
283      return estimates;
284    }
[13766]285  }
286}
Note: See TracBrowser for help on using the repository browser.