Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/NonlinearRegression/NonlinearRegression.cs @ 15061

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

#2524: merged r14517, r14523, r14527 from trunk to branch

File size: 12.0 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.Linq;
24using System.Threading;
25using HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
35using HeuristicLab.Random;
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> {
45    private const string RegressionSolutionResultName = "Regression solution";
46    private const string ModelStructureParameterName = "Model structure";
47    private const string IterationsParameterName = "Iterations";
48    private const string RestartsParameterName = "Restarts";
49    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
50    private const string SeedParameterName = "Seed";
51    private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly";
52
53    public IFixedValueParameter<StringValue> ModelStructureParameter {
54      get { return (IFixedValueParameter<StringValue>)Parameters[ModelStructureParameterName]; }
55    }
56    public IFixedValueParameter<IntValue> IterationsParameter {
57      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
58    }
59
60    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
61      get { return (IFixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
62    }
63
64    public IFixedValueParameter<IntValue> SeedParameter {
65      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
66    }
67
68    public IFixedValueParameter<IntValue> RestartsParameter {
69      get { return (IFixedValueParameter<IntValue>)Parameters[RestartsParameterName]; }
70    }
71
72    public IFixedValueParameter<BoolValue> InitParametersRandomlyParameter {
73      get { return (IFixedValueParameter<BoolValue>)Parameters[InitParamsRandomlyParameterName]; }
74    }
75
76    public string ModelStructure {
77      get { return ModelStructureParameter.Value.Value; }
78      set { ModelStructureParameter.Value.Value = value; }
79    }
80
81    public int Iterations {
82      get { return IterationsParameter.Value.Value; }
83      set { IterationsParameter.Value.Value = value; }
84    }
85
86    public int Restarts {
87      get { return RestartsParameter.Value.Value; }
88      set { RestartsParameter.Value.Value = value; }
89    }
90
91    public int Seed {
92      get { return SeedParameter.Value.Value; }
93      set { SeedParameter.Value.Value = value; }
94    }
95
96    public bool SetSeedRandomly {
97      get { return SetSeedRandomlyParameter.Value.Value; }
98      set { SetSeedRandomlyParameter.Value.Value = value; }
99    }
100
101    public bool InitializeParametersRandomly {
102      get { return InitParametersRandomlyParameter.Value.Value; }
103      set { InitParametersRandomlyParameter.Value.Value = value; }
104    }
105
106    [StorableConstructor]
107    private NonlinearRegression(bool deserializing) : base(deserializing) { }
108    private NonlinearRegression(NonlinearRegression original, Cloner cloner)
109      : base(original, cloner) {
110    }
111    public NonlinearRegression()
112      : base() {
113      Problem = new RegressionProblem();
114      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")));
115      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
116      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
117      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
118      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
119      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)));
120
121      SetParameterHiddenState();
122
123      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
124        SetParameterHiddenState();
125      };
126    }
127
128    private void SetParameterHiddenState() {
129      var hide = !InitializeParametersRandomly;
130      RestartsParameter.Hidden = hide;
131      SeedParameter.Hidden = hide;
132      SetSeedRandomlyParameter.Hidden = hide;
133    }
134
135    [StorableHook(HookType.AfterDeserialization)]
136    private void AfterDeserialization() {
137      // BackwardsCompatibility3.3
138      #region Backwards compatible code, remove with 3.4
139      if (!Parameters.ContainsKey(RestartsParameterName))
140        Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(1)));
141      if (!Parameters.ContainsKey(SeedParameterName))
142        Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
143      if (!Parameters.ContainsKey(SetSeedRandomlyParameterName))
144        Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
145      if (!Parameters.ContainsKey(InitParamsRandomlyParameterName))
146        Parameters.Add(new FixedValueParameter<BoolValue>(InitParamsRandomlyParameterName, "Switch to determine if the numeric parameters of the model should be initialized randomly.", new BoolValue(false)));
147
148      SetParameterHiddenState();
149      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
150        SetParameterHiddenState();
151      };
152      #endregion
153    }
154
155    public override IDeepCloneable Clone(Cloner cloner) {
156      return new NonlinearRegression(this, cloner);
157    }
158
159    #region nonlinear regression
160    protected override void Run(CancellationToken cancellationToken) {
161      IRegressionSolution bestSolution = null;
162      if (InitializeParametersRandomly) {
163        var qualityTable = new DataTable("RMSE table");
164        qualityTable.VisualProperties.YAxisLogScale = true;
165        var trainRMSERow = new DataRow("RMSE (train)");
166        trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
167        var testRMSERow = new DataRow("RMSE test");
168        testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
169
170        qualityTable.Rows.Add(trainRMSERow);
171        qualityTable.Rows.Add(testRMSERow);
172        Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
173        if (SetSeedRandomly) Seed = (new System.Random()).Next();
174        var rand = new MersenneTwister((uint)Seed);
175        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
176        trainRMSERow.Values.Add(bestSolution.TrainingRootMeanSquaredError);
177        testRMSERow.Values.Add(bestSolution.TestRootMeanSquaredError);
178        for (int r = 0; r < Restarts; r++) {
179          var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, rand);
180          trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
181          testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
182          if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
183            bestSolution = solution;
184          }
185        }
186      } else {
187        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations);
188      }
189
190      Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
191      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)));
192      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)));
193
194    }
195
196    /// <summary>
197    /// Fits a model to the data by optimizing the numeric constants.
198    /// Model is specified as infix expression containing variable names and numbers.
199    /// 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
200    /// used as a starting point.
201    /// </summary>-
202    /// <param name="problemData">Training and test data</param>
203    /// <param name="modelStructure">The function as infix expression</param>
204    /// <param name="maxIterations">Number of constant optimization iterations (using Levenberg-Marquardt algorithm)</param>
205    /// <param name="random">Optional random number generator for random initialization of numeric constants.</param>
206    /// <returns></returns>
207    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, IRandom rand = null) {
208      var parser = new InfixExpressionParser();
209      var tree = parser.Parse(modelStructure);
210
211      if (!SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
212
213      // initialize constants randomly
214      if (rand != null) {
215        foreach (var node in tree.IterateNodesPrefix().OfType<ConstantTreeNode>()) {
216          double f = Math.Exp(NormalDistributedRandom.NextDouble(rand, 0, 1));
217          double s = rand.NextDouble() < 0.5 ? -1 : 1;
218          node.Value = s * node.Value * f;
219        }
220      }
221      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
222
223      SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,
224        applyLinearScaling: false, maxIterations: maxIterations,
225        updateVariableWeights: false, updateConstantsInTree: true);
226
227      var scaledModel = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone());
228      scaledModel.Scale(problemData);
229      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(scaledModel, (IRegressionProblemData)problemData.Clone());
230      solution.Model.Name = "Regression Model";
231      solution.Name = "Regression Solution";
232      return solution;
233    }
234    #endregion
235  }
236}
Note: See TracBrowser for help on using the repository browser.