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