[6256] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[15583] | 3 | * Copyright (C) 2002-2018 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;
|
---|
[15448] | 29 | using HeuristicLab.Optimization;
|
---|
[6256] | 30 | using HeuristicLab.Parameters;
|
---|
| 31 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 32 |
|
---|
| 33 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
|
---|
[6555] | 34 | [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
|
---|
[6256] | 35 | [StorableClass]
|
---|
| 36 | public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
|
---|
| 37 | private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
|
---|
| 38 | private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
|
---|
| 39 | private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
|
---|
| 40 | private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
|
---|
[8823] | 41 | private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
|
---|
[13670] | 42 | private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
|
---|
[6256] | 43 |
|
---|
[15448] | 44 | private const string FunctionEvaluationsResultParameterName = "Constants Optimization Function Evaluations";
|
---|
| 45 | private const string GradientEvaluationsResultParameterName = "Constants Optimization Gradient Evaluations";
|
---|
[15483] | 46 | private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations";
|
---|
[15448] | 47 |
|
---|
[6256] | 48 | public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
|
---|
| 49 | get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
|
---|
| 50 | }
|
---|
| 51 | public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
|
---|
| 52 | get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
|
---|
| 53 | }
|
---|
| 54 | public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
|
---|
| 55 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
|
---|
| 56 | }
|
---|
| 57 | public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
|
---|
| 58 | get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
|
---|
| 59 | }
|
---|
[8823] | 60 | public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
|
---|
| 61 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
|
---|
| 62 | }
|
---|
[13670] | 63 | public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
|
---|
| 64 | get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
|
---|
| 65 | }
|
---|
[6256] | 66 |
|
---|
[15448] | 67 | public IResultParameter<IntValue> FunctionEvaluationsResultParameter {
|
---|
| 68 | get { return (IResultParameter<IntValue>)Parameters[FunctionEvaluationsResultParameterName]; }
|
---|
| 69 | }
|
---|
| 70 | public IResultParameter<IntValue> GradientEvaluationsResultParameter {
|
---|
| 71 | get { return (IResultParameter<IntValue>)Parameters[GradientEvaluationsResultParameterName]; }
|
---|
| 72 | }
|
---|
[15483] | 73 | public IFixedValueParameter<BoolValue> CountEvaluationsParameter {
|
---|
| 74 | get { return (IFixedValueParameter<BoolValue>)Parameters[CountEvaluationsParameterName]; }
|
---|
| 75 | }
|
---|
[13670] | 76 |
|
---|
[15448] | 77 |
|
---|
[6256] | 78 | public IntValue ConstantOptimizationIterations {
|
---|
| 79 | get { return ConstantOptimizationIterationsParameter.Value; }
|
---|
| 80 | }
|
---|
| 81 | public DoubleValue ConstantOptimizationImprovement {
|
---|
| 82 | get { return ConstantOptimizationImprovementParameter.Value; }
|
---|
| 83 | }
|
---|
| 84 | public PercentValue ConstantOptimizationProbability {
|
---|
| 85 | get { return ConstantOptimizationProbabilityParameter.Value; }
|
---|
| 86 | }
|
---|
| 87 | public PercentValue ConstantOptimizationRowsPercentage {
|
---|
| 88 | get { return ConstantOptimizationRowsPercentageParameter.Value; }
|
---|
| 89 | }
|
---|
[8823] | 90 | public bool UpdateConstantsInTree {
|
---|
| 91 | get { return UpdateConstantsInTreeParameter.Value.Value; }
|
---|
| 92 | set { UpdateConstantsInTreeParameter.Value.Value = value; }
|
---|
| 93 | }
|
---|
[6256] | 94 |
|
---|
[13670] | 95 | public bool UpdateVariableWeights {
|
---|
| 96 | get { return UpdateVariableWeightsParameter.Value.Value; }
|
---|
| 97 | set { UpdateVariableWeightsParameter.Value.Value = value; }
|
---|
| 98 | }
|
---|
| 99 |
|
---|
[15483] | 100 | public bool CountEvaluations {
|
---|
| 101 | get { return CountEvaluationsParameter.Value.Value; }
|
---|
| 102 | set { CountEvaluationsParameter.Value.Value = value; }
|
---|
| 103 | }
|
---|
| 104 |
|
---|
[6256] | 105 | public override bool Maximization {
|
---|
| 106 | get { return true; }
|
---|
| 107 | }
|
---|
| 108 |
|
---|
| 109 | [StorableConstructor]
|
---|
| 110 | protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
|
---|
| 111 | protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
|
---|
| 112 | : base(original, cloner) {
|
---|
| 113 | }
|
---|
| 114 | public SymbolicRegressionConstantOptimizationEvaluator()
|
---|
| 115 | : base() {
|
---|
[8938] | 116 | 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] | 117 | 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] | 118 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
|
---|
| 119 | Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
|
---|
[13916] | 120 | 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 });
|
---|
| 121 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)) { Hidden = true });
|
---|
[15448] | 122 |
|
---|
[15483] | 123 | Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
|
---|
[15448] | 124 | Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
|
---|
| 125 | Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
|
---|
[6256] | 126 | }
|
---|
| 127 |
|
---|
| 128 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 129 | return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
|
---|
| 130 | }
|
---|
| 131 |
|
---|
[8823] | 132 | [StorableHook(HookType.AfterDeserialization)]
|
---|
| 133 | private void AfterDeserialization() {
|
---|
| 134 | if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
|
---|
| 135 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
|
---|
[13670] | 136 | if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
|
---|
| 137 | Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be optimized.", new BoolValue(true)));
|
---|
[15448] | 138 |
|
---|
[15483] | 139 | if (!Parameters.ContainsKey(CountEvaluationsParameterName))
|
---|
| 140 | Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
|
---|
| 141 | if (Parameters.ContainsKey(FunctionEvaluationsResultParameterName) && Parameters.ContainsKey(GradientEvaluationsResultParameterName))
|
---|
| 142 | CountEvaluations = true;
|
---|
| 143 |
|
---|
[15448] | 144 | if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName))
|
---|
| 145 | Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
|
---|
| 146 | if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName))
|
---|
| 147 | Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
|
---|
[8823] | 148 | }
|
---|
| 149 |
|
---|
[15448] | 150 | private static readonly object locker = new object();
|
---|
[10291] | 151 | public override IOperation InstrumentedApply() {
|
---|
[6256] | 152 | var solution = SymbolicExpressionTreeParameter.ActualValue;
|
---|
| 153 | double quality;
|
---|
| 154 | if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
|
---|
| 155 | IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
|
---|
[15448] | 156 | var counter = new EvaluationsCounter();
|
---|
[6256] | 157 | quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
|
---|
[15448] | 158 | constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);
|
---|
[8938] | 159 |
|
---|
[6256] | 160 | if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
|
---|
| 161 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 162 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 163 | }
|
---|
[15448] | 164 |
|
---|
[15483] | 165 | if (CountEvaluations) {
|
---|
| 166 | lock (locker) {
|
---|
| 167 | FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
|
---|
| 168 | GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
|
---|
| 169 | }
|
---|
[15448] | 170 | }
|
---|
| 171 |
|
---|
[6256] | 172 | } else {
|
---|
| 173 | var evaluationRows = GenerateRowsToEvaluate();
|
---|
[8664] | 174 | quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 175 | }
|
---|
| 176 | QualityParameter.ActualValue = new DoubleValue(quality);
|
---|
| 177 |
|
---|
[10291] | 178 | return base.InstrumentedApply();
|
---|
[6256] | 179 | }
|
---|
| 180 |
|
---|
| 181 | public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
|
---|
| 182 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
|
---|
| 183 | EstimationLimitsParameter.ExecutionContext = context;
|
---|
[8664] | 184 | ApplyLinearScalingParameter.ExecutionContext = context;
|
---|
[15448] | 185 | FunctionEvaluationsResultParameter.ExecutionContext = context;
|
---|
| 186 | GradientEvaluationsResultParameter.ExecutionContext = context;
|
---|
[6256] | 187 |
|
---|
[9209] | 188 | // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
|
---|
| 189 | // because Evaluate() is used to get the quality of evolved models on
|
---|
| 190 | // different partitions of the dataset (e.g., best validation model)
|
---|
[8664] | 191 | double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
|
---|
[6256] | 192 |
|
---|
| 193 | SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
|
---|
| 194 | EstimationLimitsParameter.ExecutionContext = null;
|
---|
[9209] | 195 | ApplyLinearScalingParameter.ExecutionContext = null;
|
---|
[15448] | 196 | FunctionEvaluationsResultParameter.ExecutionContext = null;
|
---|
| 197 | GradientEvaluationsResultParameter.ExecutionContext = null;
|
---|
[6256] | 198 |
|
---|
| 199 | return r2;
|
---|
| 200 | }
|
---|
| 201 |
|
---|
[15448] | 202 | public class EvaluationsCounter {
|
---|
| 203 | public int FunctionEvaluations = 0;
|
---|
| 204 | public int GradientEvaluations = 0;
|
---|
| 205 | }
|
---|
| 206 |
|
---|
[14826] | 207 | public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
|
---|
| 208 | ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
|
---|
| 209 | int maxIterations, bool updateVariableWeights = true,
|
---|
| 210 | double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
|
---|
[15448] | 211 | bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
|
---|
[8704] | 212 |
|
---|
[14826] | 213 | // numeric constants in the tree become variables for constant opt
|
---|
| 214 | // variables in the tree become parameters (fixed values) for constant opt
|
---|
| 215 | // for each parameter (variable in the original tree) we store the
|
---|
| 216 | // variable name, variable value (for factor vars) and lag as a DataForVariable object.
|
---|
| 217 | // A dictionary is used to find parameters
|
---|
[14840] | 218 | double[] initialConstants;
|
---|
[14843] | 219 | var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
|
---|
[14826] | 220 |
|
---|
[14843] | 221 | TreeToAutoDiffTermConverter.ParametricFunction func;
|
---|
| 222 | TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
|
---|
[15447] | 223 | if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialConstants, out func, out func_grad))
|
---|
[8828] | 224 | throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
|
---|
[14826] | 225 | if (parameters.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
|
---|
| 226 | var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
|
---|
[14400] | 227 |
|
---|
[13670] | 228 | //extract inital constants
|
---|
[15447] | 229 | double[] c;
|
---|
| 230 | if (applyLinearScaling) {
|
---|
| 231 | c = new double[initialConstants.Length + 2];
|
---|
[15481] | 232 | c[0] = 0.0;
|
---|
| 233 | c[1] = 1.0;
|
---|
| 234 | Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
|
---|
[15447] | 235 | } else {
|
---|
| 236 | c = (double[])initialConstants.Clone();
|
---|
[14400] | 237 | }
|
---|
[15447] | 238 |
|
---|
[8938] | 239 | double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
[6256] | 240 |
|
---|
[15448] | 241 | if (counter == null) counter = new EvaluationsCounter();
|
---|
| 242 | var rowEvaluationsCounter = new EvaluationsCounter();
|
---|
| 243 |
|
---|
[8704] | 244 | alglib.lsfitstate state;
|
---|
| 245 | alglib.lsfitreport rep;
|
---|
[14826] | 246 | int retVal;
|
---|
[6256] | 247 |
|
---|
[12509] | 248 | IDataset ds = problemData.Dataset;
|
---|
[14826] | 249 | double[,] x = new double[rows.Count(), parameters.Count];
|
---|
[8704] | 250 | int row = 0;
|
---|
| 251 | foreach (var r in rows) {
|
---|
[14826] | 252 | int col = 0;
|
---|
[14840] | 253 | foreach (var info in parameterEntries) {
|
---|
[14826] | 254 | if (ds.VariableHasType<double>(info.variableName)) {
|
---|
[14946] | 255 | x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
|
---|
[14826] | 256 | } else if (ds.VariableHasType<string>(info.variableName)) {
|
---|
| 257 | x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
|
---|
| 258 | } else throw new InvalidProgramException("found a variable of unknown type");
|
---|
| 259 | col++;
|
---|
[8704] | 260 | }
|
---|
| 261 | row++;
|
---|
| 262 | }
|
---|
| 263 | double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
|
---|
| 264 | int n = x.GetLength(0);
|
---|
| 265 | int m = x.GetLength(1);
|
---|
| 266 | int k = c.Length;
|
---|
[6256] | 267 |
|
---|
[14840] | 268 | alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
|
---|
| 269 | alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
|
---|
[15371] | 270 | alglib.ndimensional_rep xrep = (p, f, obj) => iterationCallback(p, f, obj);
|
---|
[6256] | 271 |
|
---|
[8704] | 272 | try {
|
---|
| 273 | alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
|
---|
[8938] | 274 | alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
|
---|
[15371] | 275 | alglib.lsfitsetxrep(state, iterationCallback != null);
|
---|
[8938] | 276 | //alglib.lsfitsetgradientcheck(state, 0.001);
|
---|
[15448] | 277 | alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
|
---|
[14826] | 278 | alglib.lsfitresults(state, out retVal, out c, out rep);
|
---|
[15447] | 279 | } catch (ArithmeticException) {
|
---|
[8984] | 280 | return originalQuality;
|
---|
[15447] | 281 | } catch (alglib.alglibexception) {
|
---|
[8984] | 282 | return originalQuality;
|
---|
[8704] | 283 | }
|
---|
[8823] | 284 |
|
---|
[15448] | 285 | counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
|
---|
| 286 | counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
|
---|
| 287 |
|
---|
[14826] | 288 | //retVal == -7 => constant optimization failed due to wrong gradient
|
---|
[15447] | 289 | if (retVal != -7) {
|
---|
[15481] | 290 | if (applyLinearScaling) {
|
---|
| 291 | var tmp = new double[c.Length - 2];
|
---|
| 292 | Array.Copy(c, 2, tmp, 0, tmp.Length);
|
---|
| 293 | UpdateConstants(tree, tmp, updateVariableWeights);
|
---|
| 294 | } else UpdateConstants(tree, c, updateVariableWeights);
|
---|
[15447] | 295 | }
|
---|
[8938] | 296 | var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
|
---|
| 297 |
|
---|
[15480] | 298 | if (!updateConstantsInTree) UpdateConstants(tree, initialConstants, updateVariableWeights);
|
---|
[15447] | 299 |
|
---|
[8938] | 300 | if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
|
---|
[15480] | 301 | UpdateConstants(tree, initialConstants, updateVariableWeights);
|
---|
[8938] | 302 | return originalQuality;
|
---|
[8704] | 303 | }
|
---|
[8938] | 304 | return quality;
|
---|
[6256] | 305 | }
|
---|
| 306 |
|
---|
[13670] | 307 | private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
|
---|
[8938] | 308 | int i = 0;
|
---|
| 309 | foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
|
---|
| 310 | ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
|
---|
[14951] | 311 | VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
|
---|
[14826] | 312 | FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
|
---|
[8938] | 313 | if (constantTreeNode != null)
|
---|
| 314 | constantTreeNode.Value = constants[i++];
|
---|
[14951] | 315 | else if (updateVariableWeights && variableTreeNodeBase != null)
|
---|
| 316 | variableTreeNodeBase.Weight = constants[i++];
|
---|
[14826] | 317 | else if (factorVarTreeNode != null) {
|
---|
| 318 | for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
|
---|
| 319 | factorVarTreeNode.Weights[j] = constants[i++];
|
---|
| 320 | }
|
---|
[8938] | 321 | }
|
---|
| 322 | }
|
---|
| 323 |
|
---|
[14843] | 324 | private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
|
---|
[14840] | 325 | return (double[] c, double[] x, ref double fx, object o) => {
|
---|
| 326 | fx = func(c, x);
|
---|
[15448] | 327 | var counter = (EvaluationsCounter)o;
|
---|
| 328 | counter.FunctionEvaluations++;
|
---|
[8704] | 329 | };
|
---|
| 330 | }
|
---|
[6256] | 331 |
|
---|
[14843] | 332 | private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
|
---|
[14840] | 333 | return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
|
---|
[15480] | 334 | var tuple = func_grad(c, x);
|
---|
| 335 | fx = tuple.Item2;
|
---|
| 336 | Array.Copy(tuple.Item1, grad, grad.Length);
|
---|
[15448] | 337 | var counter = (EvaluationsCounter)o;
|
---|
| 338 | counter.GradientEvaluations++;
|
---|
[6256] | 339 | };
|
---|
| 340 | }
|
---|
[8730] | 341 | public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
|
---|
[14843] | 342 | return TreeToAutoDiffTermConverter.IsCompatible(tree);
|
---|
[8730] | 343 | }
|
---|
[6256] | 344 | }
|
---|
| 345 | }
|
---|