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