Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17999 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

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