[6256] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[14185] | 3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[6256] | 4 | *
|
---|
| 5 | * This file is part of HeuristicLab.
|
---|
| 6 | *
|
---|
| 7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
| 8 | * it under the terms of the GNU General Public License as published by
|
---|
| 9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
| 10 | * (at your option) any later version.
|
---|
| 11 | *
|
---|
| 12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
| 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 15 | * GNU General Public License for more details.
|
---|
| 16 | *
|
---|
| 17 | * You should have received a copy of the GNU General Public License
|
---|
| 18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
| 19 | */
|
---|
| 20 | #endregion
|
---|
| 21 |
|
---|
[8704] | 22 | using System;
|
---|
[6256] | 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Linq;
|
---|
| 25 | using HeuristicLab.Common;
|
---|
| 26 | using HeuristicLab.Core;
|
---|
| 27 | using HeuristicLab.Data;
|
---|
| 28 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
| 29 | using HeuristicLab.Parameters;
|
---|
| 30 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 31 |
|
---|
| 32 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
[6555] | 33 | [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
|
---|
[6256] | 34 | [StorableClass]
|
---|
| 35 | public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
|
---|
| 36 | private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
|
---|
| 37 | private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
|
---|
| 38 | private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
|
---|
| 39 | private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
|
---|
[8823] | 40 | private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
|
---|
[13670] | 41 | private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
|
---|
[6256] | 42 |
|
---|
| 43 | public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
|
---|
| 44 | get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
|
---|
| 45 | }
|
---|
| 46 | public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
|
---|
| 47 | get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
|
---|
| 48 | }
|
---|
| 49 | public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
|
---|
| 50 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
|
---|
| 51 | }
|
---|
| 52 | public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
|
---|
| 53 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
|
---|
| 54 | }
|
---|
[8823] | 55 | public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
|
---|
| 56 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
|
---|
| 57 | }
|
---|
[13670] | 58 | public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
|
---|
| 59 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
|
---|
| 60 | }
|
---|
[6256] | 61 |
|
---|
[13670] | 62 |
|
---|
[6256] | 63 | public IntValue ConstantOptimizationIterations {
|
---|
| 64 | get { return ConstantOptimizationIterationsParameter.Value; }
|
---|
| 65 | }
|
---|
| 66 | public DoubleValue ConstantOptimizationImprovement {
|
---|
| 67 | get { return ConstantOptimizationImprovementParameter.Value; }
|
---|
| 68 | }
|
---|
| 69 | public PercentValue ConstantOptimizationProbability {
|
---|
| 70 | get { return ConstantOptimizationProbabilityParameter.Value; }
|
---|
| 71 | }
|
---|
| 72 | public PercentValue ConstantOptimizationRowsPercentage {
|
---|
| 73 | get { return ConstantOptimizationRowsPercentageParameter.Value; }
|
---|
| 74 | }
|
---|
[8823] | 75 | public bool UpdateConstantsInTree {
|
---|
| 76 | get { return UpdateConstantsInTreeParameter.Value.Value; }
|
---|
| 77 | set { UpdateConstantsInTreeParameter.Value.Value = value; }
|
---|
| 78 | }
|
---|
[6256] | 79 |
|
---|
[13670] | 80 | public bool UpdateVariableWeights {
|
---|
| 81 | get { return UpdateVariableWeightsParameter.Value.Value; }
|
---|
| 82 | set { UpdateVariableWeightsParameter.Value.Value = value; }
|
---|
| 83 | }
|
---|
| 84 |
|
---|
[6256] | 85 | public override bool Maximization {
|
---|
| 86 | get { return true; }
|
---|
| 87 | }
|
---|
| 88 |
|
---|
| 89 | [StorableConstructor]
|
---|
| 90 | protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
|
---|
| 91 | protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
|
---|
| 92 | : base(original, cloner) {
|
---|
| 93 | }
|
---|
| 94 | public SymbolicRegressionConstantOptimizationEvaluator()
|
---|
| 95 | : base() {
|
---|
[8938] | 96 | Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the constant of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10), true));
|
---|
[13916] | 97 | Parameters.Add(new FixedValueParameter<DoubleValue>(ConstantOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the constant optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0), true) { Hidden = true });
|
---|
[6256] | 98 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
|
---|
| 99 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
|
---|
[13916] | 100 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)) { Hidden = true });
|
---|
| 101 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)) { Hidden = true });
|
---|
[6256] | 102 | }
|
---|
| 103 |
|
---|
| 104 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 105 | return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
|
---|
| 106 | }
|
---|
| 107 |
|
---|
[8823] | 108 | [StorableHook(HookType.AfterDeserialization)]
|
---|
| 109 | private void AfterDeserialization() {
|
---|
| 110 | if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
|
---|
| 111 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
|
---|
[13670] | 112 | if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
|
---|
| 113 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)));
|
---|
[8823] | 114 | }
|
---|
| 115 |
|
---|
[10291] | 116 | public override IOperation InstrumentedApply() {
|
---|
[6256] | 117 | var solution = SymbolicExpressionTreeParameter.ActualValue;
|
---|
| 118 | double quality;
|
---|
| 119 | if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
|
---|
| 120 | IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
|
---|
| 121 | quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
|
---|
[13670] | 122 | constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree);
|
---|
[8938] | 123 |
|
---|
[6256] | 124 | if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
|
---|
| 125 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 126 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 127 | }
|
---|
| 128 | } else {
|
---|
| 129 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 130 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 131 | }
|
---|
| 132 | QualityParameter.ActualValue = new DoubleValue(quality);
|
---|
| 133 |
|
---|
[10291] | 134 | return base.InstrumentedApply();
|
---|
[6256] | 135 | }
|
---|
| 136 |
|
---|
| 137 | public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
|
---|
| 138 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
|
---|
| 139 | EstimationLimitsParameter.ExecutionContext = context;
|
---|
[8664] | 140 | ApplyLinearScalingParameter.ExecutionContext = context;
|
---|
[6256] | 141 |
|
---|
[9209] | 142 | // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
|
---|
| 143 | // because Evaluate() is used to get the quality of evolved models on
|
---|
| 144 | // different partitions of the dataset (e.g., best validation model)
|
---|
[8664] | 145 | double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 146 |
|
---|
| 147 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
|
---|
| 148 | EstimationLimitsParameter.ExecutionContext = null;
|
---|
[9209] | 149 | ApplyLinearScalingParameter.ExecutionContext = null;
|
---|
[6256] | 150 |
|
---|
| 151 | return r2;
|
---|
| 152 | }
|
---|
| 153 |
|
---|
[14826] | 154 | public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
|
---|
| 155 | ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
|
---|
| 156 | int maxIterations, bool updateVariableWeights = true,
|
---|
| 157 | double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
|
---|
| 158 | bool updateConstantsInTree = true) {
|
---|
[8704] | 159 |
|
---|
[14826] | 160 | // numeric constants in the tree become variables for constant opt
|
---|
| 161 | // variables in the tree become parameters (fixed values) for constant opt
|
---|
| 162 | // for each parameter (variable in the original tree) we store the
|
---|
| 163 | // variable name, variable value (for factor vars) and lag as a DataForVariable object.
|
---|
| 164 | // A dictionary is used to find parameters
|
---|
[14840] | 165 | double[] initialConstants;
|
---|
[14843] | 166 | var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
|
---|
[14826] | 167 |
|
---|
[14843] | 168 | TreeToAutoDiffTermConverter.ParametricFunction func;
|
---|
| 169 | TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
|
---|
| 170 | if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, out parameters, out initialConstants, out func, out func_grad))
|
---|
[8828] | 171 | throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
|
---|
[14826] | 172 | if (parameters.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
|
---|
[8704] | 173 |
|
---|
[14826] | 174 | var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
|
---|
[14400] | 175 |
|
---|
[13670] | 176 | //extract inital constants
|
---|
[14843] | 177 | double[] c = new double[initialConstants.Length + 2];
|
---|
[14400] | 178 | {
|
---|
| 179 | c[0] = 0.0;
|
---|
| 180 | c[1] = 1.0;
|
---|
[14840] | 181 | Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
|
---|
[14400] | 182 | }
|
---|
[8938] | 183 | double[] originalConstants = (double[])c.Clone();
|
---|
| 184 | double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
[6256] | 185 |
|
---|
[8704] | 186 | alglib.lsfitstate state;
|
---|
| 187 | alglib.lsfitreport rep;
|
---|
[14826] | 188 | int retVal;
|
---|
[6256] | 189 |
|
---|
[12509] | 190 | IDataset ds = problemData.Dataset;
|
---|
[14826] | 191 | double[,] x = new double[rows.Count(), parameters.Count];
|
---|
[8704] | 192 | int row = 0;
|
---|
| 193 | foreach (var r in rows) {
|
---|
[14826] | 194 | int col = 0;
|
---|
[14840] | 195 | foreach (var info in parameterEntries) {
|
---|
[14826] | 196 | int lag = info.lag;
|
---|
| 197 | if (ds.VariableHasType<double>(info.variableName)) {
|
---|
| 198 | x[row, col] = ds.GetDoubleValue(info.variableName, r + lag);
|
---|
| 199 | } else if (ds.VariableHasType<string>(info.variableName)) {
|
---|
| 200 | x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
|
---|
| 201 | } else throw new InvalidProgramException("found a variable of unknown type");
|
---|
| 202 | col++;
|
---|
[8704] | 203 | }
|
---|
| 204 | row++;
|
---|
| 205 | }
|
---|
| 206 | double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
|
---|
| 207 | int n = x.GetLength(0);
|
---|
| 208 | int m = x.GetLength(1);
|
---|
| 209 | int k = c.Length;
|
---|
[6256] | 210 |
|
---|
[14840] | 211 | alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
|
---|
| 212 | alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
|
---|
[6256] | 213 |
|
---|
[8704] | 214 | try {
|
---|
| 215 | alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
|
---|
[8938] | 216 | alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
|
---|
| 217 | //alglib.lsfitsetgradientcheck(state, 0.001);
|
---|
[8704] | 218 | alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
|
---|
[14826] | 219 | alglib.lsfitresults(state, out retVal, out c, out rep);
|
---|
[14349] | 220 | } catch (ArithmeticException) {
|
---|
[8984] | 221 | return originalQuality;
|
---|
[14349] | 222 | } catch (alglib.alglibexception) {
|
---|
[8984] | 223 | return originalQuality;
|
---|
[8704] | 224 | }
|
---|
[8823] | 225 |
|
---|
[14826] | 226 | //retVal == -7 => constant optimization failed due to wrong gradient
|
---|
| 227 | if (retVal != -7) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 228 | var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
| 229 |
|
---|
[13670] | 230 | if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 231 | if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
|
---|
[13670] | 232 | UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
|
---|
[8938] | 233 | return originalQuality;
|
---|
[8704] | 234 | }
|
---|
[8938] | 235 | return quality;
|
---|
[6256] | 236 | }
|
---|
| 237 |
|
---|
[13670] | 238 | private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
|
---|
[8938] | 239 | int i = 0;
|
---|
| 240 | foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
|
---|
| 241 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
| 242 | VariableTreeNode variableTreeNode = node as VariableTreeNode;
|
---|
[14826] | 243 | BinaryFactorVariableTreeNode binFactorVarTreeNode = node as BinaryFactorVariableTreeNode;
|
---|
| 244 | FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
|
---|
[8938] | 245 | if (constantTreeNode != null)
|
---|
| 246 | constantTreeNode.Value = constants[i++];
|
---|
[13670] | 247 | else if (updateVariableWeights && variableTreeNode != null)
|
---|
[8938] | 248 | variableTreeNode.Weight = constants[i++];
|
---|
[14826] | 249 | else if (updateVariableWeights && binFactorVarTreeNode != null)
|
---|
| 250 | binFactorVarTreeNode.Weight = constants[i++];
|
---|
| 251 | else if (factorVarTreeNode != null) {
|
---|
| 252 | for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
|
---|
| 253 | factorVarTreeNode.Weights[j] = constants[i++];
|
---|
| 254 | }
|
---|
[8938] | 255 | }
|
---|
| 256 | }
|
---|
| 257 |
|
---|
[14843] | 258 | private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
|
---|
[14840] | 259 | return (double[] c, double[] x, ref double fx, object o) => {
|
---|
| 260 | fx = func(c, x);
|
---|
[8704] | 261 | };
|
---|
| 262 | }
|
---|
[6256] | 263 |
|
---|
[14843] | 264 | private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
|
---|
[14840] | 265 | return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
|
---|
| 266 | var tupel = func_grad(c, x);
|
---|
| 267 | fx = tupel.Item2;
|
---|
[8704] | 268 | Array.Copy(tupel.Item1, grad, grad.Length);
|
---|
[6256] | 269 | };
|
---|
| 270 | }
|
---|
[8730] | 271 | public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
|
---|
[14843] | 272 | return TreeToAutoDiffTermConverter.IsCompatible(tree);
|
---|
[8730] | 273 | }
|
---|
[6256] | 274 | }
|
---|
| 275 | }
|
---|