Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MathNetNumerics-Exploration-2789/HeuristicLab.Algorithms.DataAnalysis.Experimental/NonlinearRegression.cs @ 15576

Last change on this file since 15576 was 15311, checked in by gkronber, 7 years ago

#2789 exploration of alglib solver for non-linear optimization with non-linear constraints

File size: 14.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Analysis;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Problems.DataAnalysis;
34using HeuristicLab.Problems.DataAnalysis.Symbolic;
35using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
36using HeuristicLab.Random;
37
38namespace HeuristicLab.Algorithms.DataAnalysis.Experimental {
39  /// <summary>
40  /// Nonlinear regression data analysis algorithm.
41  /// </summary>
42  [Item("Nonlinear Regression (NLR) With Contraints", "Nonlinear regression (curve fitting) data analysis algorithm (wrapper for ALGLIB).")]
43  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 120)]
44  [StorableClass]
45  public sealed class NonlinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
46    private const string RegressionSolutionResultName = "Regression solution";
47    private const string ModelStructureParameterName = "Model structure";
48    private const string IterationsParameterName = "Iterations";
49    private const string RestartsParameterName = "Restarts";
50    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
51    private const string SeedParameterName = "Seed";
52    private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly";
53
54    public IFixedValueParameter<StringValue> ModelStructureParameter {
55      get { return (IFixedValueParameter<StringValue>)Parameters[ModelStructureParameterName]; }
56    }
57    public IFixedValueParameter<IntValue> IterationsParameter {
58      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
59    }
60
61    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
62      get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
63    }
64
65    public IFixedValueParameter<IntValue> SeedParameter {
66      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
67    }
68
69    public IFixedValueParameter<IntValue> RestartsParameter {
70      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
71    }
72
73    public IFixedValueParameter<BoolValue> InitParametersRandomlyParameter {
74      get { return (IFixedValueParameter<BoolValue>)Parameters[InitParamsRandomlyParameterName]; }
75    }
76
77    public string ModelStructure {
78      get { return ModelStructureParameter.Value.Value; }
79      set { ModelStructureParameter.Value.Value = value; }
80    }
81
82    public int Iterations {
83      get { return IterationsParameter.Value.Value; }
84      set { IterationsParameter.Value.Value = value; }
85    }
86
87    public int Restarts {
88      get { return RestartsParameter.Value.Value; }
89      set { RestartsParameter.Value.Value = value; }
90    }
91
92    public int Seed {
93      get { return SeedParameter.Value.Value; }
94      set { SeedParameter.Value.Value = value; }
95    }
96
97    public bool SetSeedRandomly {
98      get { return SetSeedRandomlyParameter.Value.Value; }
99      set { SetSeedRandomlyParameter.Value.Value = value; }
100    }
101
102    public bool InitializeParametersRandomly {
103      get { return InitParametersRandomlyParameter.Value.Value; }
104      set { InitParametersRandomlyParameter.Value.Value = value; }
105    }
106
107    [StorableConstructor]
108    private NonlinearRegression(bool deserializing) : base(deserializing) { }
109    private NonlinearRegression(NonlinearRegression original, Cloner cloner)
110      : base(original, cloner) {
111    }
112    public NonlinearRegression()
113      : base() {
114      Problem = new RegressionProblem();
115      Parameters.Add(new FixedValueParameter<StringValue>(ModelStructureParameterName, "The function for which the parameters must be fit (only numeric constants are tuned).", new StringValue("1.0 * x*x + 0.0")));
116      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
117      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
118      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
119      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
120      Parameters.Add(new FixedValueParameter<BoolValue>(InitParamsRandomlyParameterName, "Switch to determine if the real-valued model parameters should be initialized randomly in each restart.", new BoolValue(false)));
121
122      SetParameterHiddenState();
123
124      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
125        SetParameterHiddenState();
126      };
127    }
128
129    private void SetParameterHiddenState() {
130      var hide = !InitializeParametersRandomly;
131      RestartsParameter.Hidden = hide;
132      SeedParameter.Hidden = hide;
133      SetSeedRandomlyParameter.Hidden = hide;
134    }
135
136    [StorableHook(HookType.AfterDeserialization)]
137    private void AfterDeserialization() {
138      // BackwardsCompatibility3.3
139      #region Backwards compatible code, remove with 3.4
140      if (!Parameters.ContainsKey(RestartsParameterName))
141        Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(1)));
142      if (!Parameters.ContainsKey(SeedParameterName))
143        Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
144      if (!Parameters.ContainsKey(SetSeedRandomlyParameterName))
145        Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
146      if (!Parameters.ContainsKey(InitParamsRandomlyParameterName))
147        Parameters.Add(new FixedValueParameter<BoolValue>(InitParamsRandomlyParameterName, "Switch to determine if the numeric parameters of the model should be initialized randomly.", new BoolValue(false)));
148
149      SetParameterHiddenState();
150      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
151        SetParameterHiddenState();
152      };
153      #endregion
154    }
155
156    public override IDeepCloneable Clone(Cloner cloner) {
157      return new NonlinearRegression(this, cloner);
158    }
159
160    #region nonlinear regression
161    protected override void Run(CancellationToken cancellationToken) {
162      IRegressionSolution bestSolution = null;
163      if (InitializeParametersRandomly) {
164        var qualityTable = new DataTable("RMSE table");
165        qualityTable.VisualProperties.YAxisLogScale = true;
166        var trainRMSERow = new DataRow("RMSE (train)");
167        trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
168        var testRMSERow = new DataRow("RMSE test");
169        testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
170
171        qualityTable.Rows.Add(trainRMSERow);
172        qualityTable.Rows.Add(testRMSERow);
173        Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
174        if (SetSeedRandomly) Seed = (new System.Random()).Next();
175        var rand = new MersenneTwister((uint)Seed);
176        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
177        trainRMSERow.Values.Add(bestSolution.TrainingRootMeanSquaredError);
178        testRMSERow.Values.Add(bestSolution.TestRootMeanSquaredError);
179        for (int r = 0; r < Restarts; r++) {
180          var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
181          trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
182          testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
183          if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
184            bestSolution = solution;
185          }
186        }
187      } else {
188        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations);
189      }
190
191      Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
192      Results.Add(new Result("Root mean square error (train)", "The root of the mean of squared errors of the regression solution on the training set.", new DoubleValue(bestSolution.TrainingRootMeanSquaredError)));
193      Results.Add(new Result("Root mean square error (test)", "The root of the mean of squared errors of the regression solution on the test set.", new DoubleValue(bestSolution.TestRootMeanSquaredError)));
194
195    }
196
197    /// <summary>
198    /// Fits a model to the data by optimizing the numeric constants.
199    /// Model is specified as infix expression containing variable names and numbers.
200    /// The starting point for the numeric constants is initialized randomly if a random number generator is specified (~N(0,1)). Otherwise the user specified constants are
201    /// used as a starting point.
202    /// </summary>-
203    /// <param name="problemData">Training and test data</param>
204    /// <param name="modelStructure">The function as infix expression</param>
205    /// <param name="maxIterations">Number of constant optimization iterations (using Levenberg-Marquardt algorithm)</param>
206    /// <param name="random">Optional random number generator for random initialization of numeric constants.</param>
207    /// <returns></returns>
208    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, IRandom rand = null) {
209      var parser = new InfixExpressionParser();
210      var tree = parser.Parse(modelStructure);
211      // parser handles double and string variables equally by creating a VariableTreeNode
212      // post-process to replace VariableTreeNodes by FactorVariableTreeNodes for all string variables
213      var factorSymbol = new FactorVariable();
214      factorSymbol.VariableNames =
215        problemData.AllowedInputVariables.Where(name => problemData.Dataset.VariableHasType<string>(name));
216      factorSymbol.AllVariableNames = factorSymbol.VariableNames;
217      factorSymbol.VariableValues =
218        factorSymbol.VariableNames.Select(name =>
219        new KeyValuePair<string, Dictionary<string, int>>(name,
220        problemData.Dataset.GetReadOnlyStringValues(name).Distinct()
221        .Select((n, i) => Tuple.Create(n, i))
222        .ToDictionary(tup => tup.Item1, tup => tup.Item2)));
223
224      foreach (var parent in tree.IterateNodesPrefix().ToArray()) {
225        for (int i = 0; i < parent.SubtreeCount; i++) {
226          var varChild = parent.GetSubtree(i) as VariableTreeNode;
227          var factorVarChild = parent.GetSubtree(i) as FactorVariableTreeNode;
228          if (varChild != null && factorSymbol.VariableNames.Contains(varChild.VariableName)) {
229            parent.RemoveSubtree(i);
230            var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode();
231            factorTreeNode.VariableName = varChild.VariableName;
232            factorTreeNode.Weights =
233              factorTreeNode.Symbol.GetVariableValues(factorTreeNode.VariableName).Select(_ => 1.0).ToArray();
234            // weight = 1.0 for each value
235            parent.InsertSubtree(i, factorTreeNode);
236          } else if (factorVarChild != null && factorSymbol.VariableNames.Contains(factorVarChild.VariableName)) {
237            if (factorSymbol.GetVariableValues(factorVarChild.VariableName).Count() != factorVarChild.Weights.Length)
238              throw new ArgumentException(
239                string.Format("Factor variable {0} needs exactly {1} weights",
240                factorVarChild.VariableName,
241                factorSymbol.GetVariableValues(factorVarChild.VariableName).Count()));
242            parent.RemoveSubtree(i);
243            var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode();
244            factorTreeNode.VariableName = factorVarChild.VariableName;
245            factorTreeNode.Weights = factorVarChild.Weights;
246            parent.InsertSubtree(i, factorTreeNode);
247          }
248        }
249      }
250
251      if (!SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
252
253      // initialize constants randomly
254      if (rand != null) {
255        foreach (var node in tree.IterateNodesPrefix().OfType<ConstantTreeNode>()) {
256          double f = Math.Exp(NormalDistributedRandom.NextDouble(rand, 0, 1));
257          double s = rand.NextDouble() < 0.5 ? -1 : 1;
258          node.Value = s * node.Value * f;
259        }
260      }
261      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
262
263      SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,
264        applyLinearScaling: false, maxIterations: maxIterations,
265        updateVariableWeights: false, updateConstantsInTree: true);
266
267      var scaledModel = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone());
268      scaledModel.Scale(problemData);
269      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(scaledModel, (IRegressionProblemData)problemData.Clone());
270      solution.Model.Name = "Regression Model";
271      solution.Name = "Regression Solution";
272      return solution;
273    }
274    #endregion
275  }
276}
Note: See TracBrowser for help on using the repository browser.