Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Algorithms.DataAnalysis/3.4/NonlinearRegression/NonlinearRegression.cs

Last change on this file was 18132, checked in by gkronber, 3 years ago

#3140: merged r18091:18131 from branch to trunk

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