source: branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionVariableImpactsCalculator.cs @ 14238

Last change on this file since 14238 was 14238, checked in by gkronber, 3 years ago

#2650:

  • added weight for FactorVariable (necessary for LR)
  • introduced VariableBase and VariableTreeNodeBase and IVariableSymbol
  • support for factors in LR
  • extended variable impacts in solution view
  • fixed ERC view for regression
  • support for FactorVariable in simplifier
  • improved support for FactorVariable in constants optimizer
  • multiple related changes and small fixes
File size: 10.1 KB
Line 
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;
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
45    public enum DataPartitionEnum {
46      Training,
47      Test,
48      All
49    }
50
51    private const string ReplacementParameterName = "Replacement Method";
52    private const string DataPartitionParameterName = "DataPartition";
53
54    public IFixedValueParameter<EnumValue<ReplacementMethodEnum>> ReplacementParameter {
55      get { return (IFixedValueParameter<EnumValue<ReplacementMethodEnum>>)Parameters[ReplacementParameterName]; }
56    }
57    public IFixedValueParameter<EnumValue<DataPartitionEnum>> DataPartitionParameter {
58      get { return (IFixedValueParameter<EnumValue<DataPartitionEnum>>)Parameters[DataPartitionParameterName]; }
59    }
60
61    public ReplacementMethodEnum ReplacementMethod {
62      get { return ReplacementParameter.Value.Value; }
63      set { ReplacementParameter.Value.Value = value; }
64    }
65    public DataPartitionEnum DataPartition {
66      get { return DataPartitionParameter.Value.Value; }
67      set { DataPartitionParameter.Value.Value = value; }
68    }
69
70
71    [StorableConstructor]
72    private RegressionSolutionVariableImpactsCalculator(bool deserializing) : base(deserializing) { }
73    private RegressionSolutionVariableImpactsCalculator(RegressionSolutionVariableImpactsCalculator original, Cloner cloner)
74      : base(original, cloner) { }
75    public override IDeepCloneable Clone(Cloner cloner) {
76      return new RegressionSolutionVariableImpactsCalculator(this, cloner);
77    }
78
79    public RegressionSolutionVariableImpactsCalculator()
80      : base() {
81      Parameters.Add(new FixedValueParameter<EnumValue<ReplacementMethodEnum>>(ReplacementParameterName, "The replacement method for variables during impact calculation.", new EnumValue<ReplacementMethodEnum>(ReplacementMethodEnum.Median)));
82      Parameters.Add(new FixedValueParameter<EnumValue<DataPartitionEnum>>(DataPartitionParameterName, "The data partition on which the impacts are calculated.", new EnumValue<DataPartitionEnum>(DataPartitionEnum.Training)));
83    }
84
85    //mkommend: annoying name clash with static method, open to better naming suggestions
86    public IEnumerable<Tuple<string, double>> Calculate(IRegressionSolution solution) {
87      return CalculateImpacts(solution, DataPartition, ReplacementMethod);
88    }
89
90    public static IEnumerable<Tuple<string, double>> CalculateImpacts(IRegressionSolution solution,
91      DataPartitionEnum data = DataPartitionEnum.Training,
92      ReplacementMethodEnum replacementMethod = ReplacementMethodEnum.Median) {
93
94      var problemData = solution.ProblemData;
95      var dataset = problemData.Dataset;
96
97      IEnumerable<int> rows;
98      IEnumerable<double> targetValues;
99      double originalR2 = -1;
100
101      OnlineCalculatorError error;
102
103      switch (data) {
104        case DataPartitionEnum.All:
105          rows = solution.ProblemData.AllIndices;
106          targetValues = problemData.TargetVariableValues.ToList();
107          originalR2 = OnlinePearsonsRCalculator.Calculate(problemData.TargetVariableValues, solution.EstimatedValues, out error);
108          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation.");
109          originalR2 = originalR2 * originalR2;
110          break;
111        case DataPartitionEnum.Training:
112          rows = problemData.TrainingIndices;
113          targetValues = problemData.TargetVariableTrainingValues.ToList();
114          originalR2 = solution.TrainingRSquared;
115          break;
116        case DataPartitionEnum.Test:
117          rows = problemData.TestIndices;
118          targetValues = problemData.TargetVariableTestValues.ToList();
119          originalR2 = solution.TestRSquared;
120          break;
121        default: throw new ArgumentException(string.Format("DataPartition {0} cannot be handled.", data));
122      }
123
124
125      var impacts = new Dictionary<string, double>();
126      var modifiableDataset = ((Dataset)dataset).ToModifiable();
127
128      // calculate impacts for double variables
129      foreach (var inputVariable in problemData.AllowedInputVariables.Where(problemData.Dataset.VariableHasType<double>)) {
130        var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows, replacementMethod);
131        var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
132        if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
133
134        newR2 = newR2 * newR2;
135        var impact = originalR2 - newR2;
136        impacts[inputVariable] = impact;
137      }
138      // calculate impacts for factor variables
139      foreach (var inputVariable in problemData.AllowedInputVariables.Where(problemData.Dataset.VariableHasType<string>)) {
140        var smallestImpact = double.PositiveInfinity;
141        foreach (var repl in problemData.Dataset.GetStringValues(inputVariable, rows).Distinct()) {
142          var newEstimates = EvaluateModelWithReplacedVariable(solution.Model, inputVariable, modifiableDataset, rows, Enumerable.Repeat(repl, dataset.Rows));
143          var newR2 = OnlinePearsonsRCalculator.Calculate(targetValues, newEstimates, out error);
144          if (error != OnlineCalculatorError.None) throw new InvalidOperationException("Error during R² calculation with replaced inputs.");
145
146          newR2 = newR2 * newR2;
147          var impact = originalR2 - newR2;
148          if (impact < smallestImpact) smallestImpact = impact;
149        }
150        impacts[inputVariable] = smallestImpact;
151      }
152      return impacts.OrderByDescending(i => i.Value).Select(i => Tuple.Create(i.Key, i.Value));
153    }
154
155    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, ReplacementMethodEnum replacement = ReplacementMethodEnum.Median) {
156      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
157      double replacementValue;
158      List<double> replacementValues;
159      IRandom rand;
160
161      switch (replacement) {
162        case ReplacementMethodEnum.Median:
163          replacementValue = rows.Select(r => originalValues[r]).Median();
164          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
165          break;
166        case ReplacementMethodEnum.Average:
167          replacementValue = rows.Select(r => originalValues[r]).Average();
168          replacementValues = Enumerable.Repeat(replacementValue, dataset.Rows).ToList();
169          break;
170        case ReplacementMethodEnum.Shuffle:
171          // new var has same empirical distribution but the relation to y is broken
172          rand = new FastRandom(31415);
173          replacementValues = rows.Select(r => originalValues[r]).Shuffle(rand).ToList();
174          break;
175        case ReplacementMethodEnum.Noise:
176          var avg = rows.Select(r => originalValues[r]).Average();
177          var stdDev = rows.Select(r => originalValues[r]).StandardDeviation();
178          rand = new FastRandom(31415);
179          replacementValues = rows.Select(_ => NormalDistributedRandom.NextDouble(rand, avg, stdDev)).ToList();
180          break;
181
182        default:
183          throw new ArgumentException(string.Format("ReplacementMethod {0} cannot be handled.", replacement));
184      }
185
186      return EvaluateModelWithReplacedVariable(model, variable, dataset, rows, replacementValues);
187    }
188
189    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<double> replacementValues) {
190      var originalValues = dataset.GetReadOnlyDoubleValues(variable).ToList();
191      dataset.ReplaceVariable(variable, replacementValues.ToList());
192      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
193      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
194      dataset.ReplaceVariable(variable, originalValues);
195
196      return estimates;
197    }
198    private static IEnumerable<double> EvaluateModelWithReplacedVariable(IRegressionModel model, string variable, ModifiableDataset dataset, IEnumerable<int> rows, IEnumerable<string> replacementValues) {
199      var originalValues = dataset.GetReadOnlyStringValues(variable).ToList();
200      dataset.ReplaceVariable(variable, replacementValues.ToList());
201      //mkommend: ToList is used on purpose to avoid lazy evaluation that could result in wrong estimates due to variable replacements
202      var estimates = model.GetEstimatedValues(dataset, rows).ToList();
203      dataset.ReplaceVariable(variable, originalValues);
204
205      return estimates;
206    }
207  }
208}
Note: See TracBrowser for help on using the repository browser.