Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/NonlinearLeastSquaresConstantOptimizationEvaluator.cs @ 17605

Last change on this file since 17605 was 17605, checked in by pfleck, 4 years ago

#3040 Adapted unit test for trunk changes.

File size: 9.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
31using HEAL.Attic;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [StorableType("24B68851-036D-4446-BD6F-3823E9028FF4")]
35  [Item("NonlinearLeastSquaresOptimizer", "")]
36  public class NonlinearLeastSquaresConstantOptimizationEvaluator : SymbolicRegressionConstantOptimizationEvaluator {
37
38    private const string ConstantOptimizationIterationsName = "ConstantOptimizationIterations";
39
40    #region Parameter Properties
41    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
42      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsName]; }
43    }
44    #endregion
45
46    #region Properties
47    public int ConstantOptimizationIterations {
48      get { return ConstantOptimizationIterationsParameter.Value.Value; }
49      set { ConstantOptimizationIterationsParameter.Value.Value = value; }
50    }
51    #endregion
52
53    public NonlinearLeastSquaresConstantOptimizationEvaluator()
54      : base() {
55      Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsName, "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)));
56    }
57
58    protected NonlinearLeastSquaresConstantOptimizationEvaluator(NonlinearLeastSquaresConstantOptimizationEvaluator original, Cloner cloner)
59      : base(original, cloner) {
60    }
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new NonlinearLeastSquaresConstantOptimizationEvaluator(this, cloner);
63    }
64    [StorableConstructor]
65    protected NonlinearLeastSquaresConstantOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }
66
67    protected override ISymbolicExpressionTree OptimizeConstants(
68      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows,
69      CancellationToken cancellationToken = default(CancellationToken), EvaluationsCounter counter = null) {
70      return OptimizeTree(tree,
71        problemData, rows,
72        ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations, UpdateVariableWeights,
73        cancellationToken, counter);
74    }
75
76    public static ISymbolicExpressionTree OptimizeTree(
77      ISymbolicExpressionTree tree,
78      IRegressionProblemData problemData, IEnumerable<int> rows,
79      bool applyLinearScaling, int maxIterations, bool updateVariableWeights,
80      CancellationToken cancellationToken = default(CancellationToken), EvaluationsCounter counter = null, Action<double[], double, object> iterationCallback = null) {
81
82      // numeric constants in the tree become variables for constant opt
83      // variables in the tree become parameters (fixed values) for constant opt
84      // for each parameter (variable in the original tree) we store the
85      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
86      // A dictionary is used to find parameters
87      bool success = TreeToAutoDiffTermConverter.TryConvertToAutoDiff(
88        tree, updateVariableWeights, applyLinearScaling,
89        out var parameters, out var initialConstants, out var func, out var func_grad);
90      if (!success)
91        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
92      if (parameters.Count == 0) return (ISymbolicExpressionTree)tree.Clone();
93      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
94
95      //extract initial constants
96      double[] c;
97      if (applyLinearScaling) {
98        c = new double[initialConstants.Length + 2];
99        c[0] = 0.0;
100        c[1] = 1.0;
101        Array.Copy(initialConstants, 0, c, 2, initialConstants.Length);
102      } else {
103        c = (double[])initialConstants.Clone();
104      }
105
106      IDataset ds = problemData.Dataset;
107      double[,] x = new double[rows.Count(), parameters.Count];
108      int row = 0;
109      foreach (var r in rows) {
110        int col = 0;
111        foreach (var info in parameterEntries) {
112          if (ds.VariableHasType<double>(info.variableName)) {
113            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
114          } else if (ds.VariableHasType<string>(info.variableName)) {
115            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
116          } else throw new InvalidProgramException("found a variable of unknown type");
117          col++;
118        }
119        row++;
120      }
121      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
122      int n = x.GetLength(0);
123      int m = x.GetLength(1);
124      int k = c.Length;
125
126      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
127      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
128      alglib.ndimensional_rep xrep = (p, f, obj) => {
129        iterationCallback?.Invoke(p, f, obj);
130        cancellationToken.ThrowIfCancellationRequested();
131      };
132      var rowEvaluationsCounter = new EvaluationsCounter();
133
134      try {
135        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out var state);
136        alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
137        alglib.lsfitsetxrep(state, iterationCallback != null || cancellationToken != default(CancellationToken));
138        //alglib.lsfitsetgradientcheck(state, 0.001);
139        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
140        alglib.lsfitresults(state, out var retVal, out c, out alglib.lsfitreport rep);
141
142        //retVal == -7  => constant optimization failed due to wrong gradient
143        if (retVal == -1)
144          return (ISymbolicExpressionTree)tree.Clone();
145      } catch (ArithmeticException) {
146        return (ISymbolicExpressionTree)tree.Clone();
147      } catch (alglib.alglibexception) {
148        return (ISymbolicExpressionTree)tree.Clone();
149      }
150
151      if (counter != null) {
152        counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
153        counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
154      }
155
156      var newTree = (ISymbolicExpressionTree)tree.Clone();
157      if (applyLinearScaling) {
158        var tmp = new double[c.Length - 2];
159        Array.Copy(c, 2, tmp, 0, tmp.Length);
160        UpdateConstants(newTree, tmp, updateVariableWeights);
161      } else
162        UpdateConstants(newTree, c, updateVariableWeights);
163
164      return newTree;
165    }
166
167    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
168      int i = 0;
169      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
170        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
171        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
172        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
173        if (constantTreeNode != null)
174          constantTreeNode.Value = constants[i++];
175        else if (updateVariableWeights && variableTreeNodeBase != null)
176          variableTreeNodeBase.Weight = constants[i++];
177        else if (factorVarTreeNode != null) {
178          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
179            factorVarTreeNode.Weights[j] = constants[i++];
180        }
181      }
182    }
183
184    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
185      return (double[] c, double[] x, ref double fx, object o) => {
186        fx = func(c, x);
187        var counter = (EvaluationsCounter)o;
188        counter.FunctionEvaluations++;
189      };
190    }
191
192    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
193      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
194        var tuple = func_grad(c, x);
195        fx = tuple.Item2;
196        Array.Copy(tuple.Item1, grad, grad.Length);
197        var counter = (EvaluationsCounter)o;
198        counter.GradientEvaluations++;
199      };
200    }
201
202    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
203      return TreeToAutoDiffTermConverter.IsCompatible(tree);
204    }
205  }
206}
Note: See TracBrowser for help on using the repository browser.