Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NonlinearRegression/NonlinearRegression.cs @ 14258

Last change on this file since 14258 was 14258, checked in by gkronber, 8 years ago

#2657: added random restarts for NonlinearRegression (curve fitting) algorithm

File size: 9.2 KB
RevLine 
[14024]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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Parameters;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
[14258]35using HeuristicLab.Random;
[14024]36
37namespace HeuristicLab.Algorithms.DataAnalysis {
38  /// <summary>
39  /// Nonlinear regression data analysis algorithm.
40  /// </summary>
41  [Item("Nonlinear Regression (NLR)", "Nonlinear regression (curve fitting) data analysis algorithm (wrapper for ALGLIB).")]
42  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 120)]
43  [StorableClass]
44  public sealed class NonlinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
[14109]45    private const string RegressionSolutionResultName = "Regression solution";
[14024]46    private const string ModelStructureParameterName = "Model structure";
47    private const string IterationsParameterName = "Iterations";
[14258]48    private const string RestartsParameterName = "Restarts";
49    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
50    private const string SeedParameterName = "Seed";
[14024]51
52    public IFixedValueParameter<StringValue> ModelStructureParameter {
53      get { return (IFixedValueParameter<StringValue>)Parameters[ModelStructureParameterName]; }
54    }
55    public IFixedValueParameter<IntValue> IterationsParameter {
56      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
57    }
58
[14258]59    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
60      get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
61    }
62
63    public IFixedValueParameter<IntValue> SeedParameter {
64      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
65    }
66
67    public IFixedValueParameter<IntValue> RestartsParameter {
68      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
69    }
70
[14024]71    public string ModelStructure {
72      get { return ModelStructureParameter.Value.Value; }
73      set { ModelStructureParameter.Value.Value = value; }
74    }
75
76    public int Iterations {
77      get { return IterationsParameter.Value.Value; }
78      set { IterationsParameter.Value.Value = value; }
79    }
80
[14258]81    public int Restarts {
82      get { return RestartsParameter.Value.Value; }
83      set { RestartsParameter.Value.Value = value; }
84    }
[14024]85
[14258]86    public int Seed {
87      get { return SeedParameter.Value.Value; }
88      set { SeedParameter.Value.Value = value; }
89    }
90
91    public bool SetSeedRandomly {
92      get { return SetSeedRandomlyParameter.Value.Value; }
93      set { SetSeedRandomlyParameter.Value.Value = value; }
94    }
95
[14024]96    [StorableConstructor]
97    private NonlinearRegression(bool deserializing) : base(deserializing) { }
98    private NonlinearRegression(NonlinearRegression original, Cloner cloner)
99      : base(original, cloner) {
100    }
101    public NonlinearRegression()
102      : base() {
103      Problem = new RegressionProblem();
104      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")));
105      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
[14258]106      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(10)));
107      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
108      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
[14024]109    }
[14258]110
[14024]111    [StorableHook(HookType.AfterDeserialization)]
[14258]112    private void AfterDeserialization() {
113      // BackwardsCompatibility3.3
114      #region Backwards compatible code, remove with 3.4
115      if (!Parameters.ContainsKey(RestartsParameterName))
116        Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(1)));
117      if (!Parameters.ContainsKey(SeedParameterName))
118        Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
119      if (!Parameters.ContainsKey(SetSeedRandomlyParameterName))
120        Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
121      #endregion
122    }
[14024]123
124    public override IDeepCloneable Clone(Cloner cloner) {
125      return new NonlinearRegression(this, cloner);
126    }
127
128    #region nonlinear regression
129    protected override void Run() {
[14258]130      if (SetSeedRandomly) Seed = (new System.Random()).Next();
131      var rand = new MersenneTwister((uint)Seed);
132      IRegressionSolution bestSolution = null;
133      for (int r = 0; r < Restarts; r++) {
134        var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
135        if (bestSolution == null || solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
136          bestSolution = solution;
137        }
138      }
139
140      Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
141      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)));
142      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)));
143
[14024]144    }
145
[14258]146    /// <summary>
147    /// Fits a model to the data by optimizing the numeric constants.
148    /// Model is specified as infix expression containing variable names and numbers.
149    /// 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
150    /// used as a starting point.
151    /// </summary>
152    /// <param name="problemData">Training and test data</param>
153    /// <param name="modelStructure">The function as infix expression</param>
154    /// <param name="maxIterations">Number of constant optimization iterations (using Levenberg-Marquardt algorithm)</param>
155    /// <param name="random">Optional random number generator for random initialization of numeric constants.</param>
156    /// <returns></returns>
157    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, IRandom random = null) {
[14024]158      var parser = new InfixExpressionParser();
159      var tree = parser.Parse(modelStructure);
[14258]160
[14024]161      if (!SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
162
[14258]163      // initialize constants randomly
164      if (random != null) {
165        foreach (var node in tree.IterateNodesPrefix().OfType<ConstantTreeNode>()) {
166          node.Value = NormalDistributedRandom.NextDouble(random, 0, 1);
167        }
168      }
[14024]169      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
[14258]170
171      SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,
[14024]172        applyLinearScaling: false, maxIterations: maxIterations,
173        updateVariableWeights: false, updateConstantsInTree: true);
174
175      var scaledModel = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone());
176      scaledModel.Scale(problemData);
177      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(scaledModel, (IRegressionProblemData)problemData.Clone());
178      solution.Model.Name = "Regression Model";
179      solution.Name = "Regression Solution";
180      return solution;
181    }
182    #endregion
183  }
184}
Note: See TracBrowser for help on using the repository browser.