Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3140: merged r18091:18131 from branch to trunk

File size: 15.5 KB
RevLine 
[14024]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[14024]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;
[14826]23using System.Collections.Generic;
[14024]24using System.Linq;
[14523]25using System.Threading;
[14319]26using HeuristicLab.Analysis;
[14024]27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
[14316]30using HeuristicLab.Optimization;
[14024]31using HeuristicLab.Parameters;
[16565]32using HEAL.Attic;
[14024]33using HeuristicLab.Problems.DataAnalysis;
34using HeuristicLab.Problems.DataAnalysis.Symbolic;
35using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
[14258]36using HeuristicLab.Random;
[14024]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)]
[16565]44  [StorableType("06E970EA-D366-4F46-BDC5-7156B5787BEF")]
[14024]45  public sealed class NonlinearRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
[14109]46    private const string RegressionSolutionResultName = "Regression solution";
[14024]47    private const string ModelStructureParameterName = "Model structure";
48    private const string IterationsParameterName = "Iterations";
[14258]49    private const string RestartsParameterName = "Restarts";
50    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
51    private const string SeedParameterName = "Seed";
[14319]52    private const string InitParamsRandomlyParameterName = "InitializeParametersRandomly";
[15502]53    private const string ApplyLinearScalingParameterName = "Apply linear scaling";
[14024]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
[14258]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
[14319]74    public IFixedValueParameter<BoolValue> InitParametersRandomlyParameter {
75      get { return (IFixedValueParameter<BoolValue>)Parameters[InitParamsRandomlyParameterName]; }
76    }
77
[15502]78    public IFixedValueParameter<BoolValue> ApplyLinearScalingParameter {
79      get { return (IFixedValueParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
80    }
81
[14024]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
[14258]92    public int Restarts {
93      get { return RestartsParameter.Value.Value; }
94      set { RestartsParameter.Value.Value = value; }
95    }
[14024]96
[14258]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
[14319]107    public bool InitializeParametersRandomly {
108      get { return InitParametersRandomlyParameter.Value.Value; }
109      set { InitParametersRandomlyParameter.Value.Value = value; }
110    }
111
[15502]112    public bool ApplyLinearScaling {
113      get { return ApplyLinearScalingParameter.Value.Value; }
114      set { ApplyLinearScalingParameter.Value.Value = value; }
115    }
116
[14024]117    [StorableConstructor]
[16565]118    private NonlinearRegression(StorableConstructorFlag _) : base(_) { }
[14024]119    private NonlinearRegression(NonlinearRegression original, Cloner cloner)
120      : base(original, cloner) {
121    }
122    public NonlinearRegression()
123      : base() {
124      Problem = new RegressionProblem();
[18132]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)));
[14319]131      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
[14258]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)));
[14319]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)));
[15505]135      Parameters.Add(new FixedValueParameter<BoolValue>(ApplyLinearScalingParameterName, "Switch to determine if linear scaling terms should be added to the model", new BoolValue(true)));
[14319]136
137      SetParameterHiddenState();
138
139      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
140        SetParameterHiddenState();
141      };
[14024]142    }
[14258]143
[14319]144    private void SetParameterHiddenState() {
145      var hide = !InitializeParametersRandomly;
146      RestartsParameter.Hidden = hide;
147      SeedParameter.Hidden = hide;
148      SetSeedRandomlyParameter.Hidden = hide;
149    }
150
[14024]151    [StorableHook(HookType.AfterDeserialization)]
[14258]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)));
[14319]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)));
[15502]163      if (!Parameters.ContainsKey(ApplyLinearScalingParameterName))
[15505]164        Parameters.Add(new FixedValueParameter<BoolValue>(ApplyLinearScalingParameterName, "Switch to determine if linear scaling terms should be added to the model", new BoolValue(true)));
[14319]165
[15502]166
[14319]167      SetParameterHiddenState();
168      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
169        SetParameterHiddenState();
170      };
[14258]171      #endregion
172    }
[14024]173
174    public override IDeepCloneable Clone(Cloner cloner) {
175      return new NonlinearRegression(this, cloner);
176    }
177
178    #region nonlinear regression
[14523]179    protected override void Run(CancellationToken cancellationToken) {
[14319]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;
[14316]188
[14319]189        qualityTable.Rows.Add(trainRMSERow);
190        qualityTable.Rows.Add(testRMSERow);
191        Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
[16071]192        if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
[14319]193        var rand = new MersenneTwister((uint)Seed);
[15502]194        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand);
[14319]195        trainRMSERow.Values.Add(bestSolution.TrainingRootMeanSquaredError);
196        testRMSERow.Values.Add(bestSolution.TestRootMeanSquaredError);
197        for (int r = 0; r < Restarts; r++) {
[15502]198          var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand);
[14319]199          trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
200          testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
201          if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
202            bestSolution = solution;
203          }
[14258]204        }
[14319]205      } else {
[15502]206        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling);
[14258]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
[14024]213    }
214
[14258]215    /// <summary>
[18132]216    /// Fits a model to the data by optimizing parameters.
[14258]217    /// Model is specified as infix expression containing variable names and numbers.
[18132]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
[14258]219    /// used as a starting point.
[14316]220    /// </summary>-
[14258]221    /// <param name="problemData">Training and test data</param>
222    /// <param name="modelStructure">The function as infix expression</param>
[18132]223    /// <param name="maxIterations">Number of Levenberg-Marquardt iterations</param>
224    /// <param name="random">Optional random number generator for random initialization of parameters.</param>
[14258]225    /// <returns></returns>
[15502]226    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, bool applyLinearScaling, IRandom rand = null) {
[14024]227      var parser = new InfixExpressionParser();
228      var tree = parser.Parse(modelStructure);
[14826]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)));
[14258]241
[14826]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
[18132]269      if (!SymbolicRegressionParameterOptimizationEvaluator.CanOptimizeParameters(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
[14024]270
[18132]271      // initialize parameters randomly
[14319]272      if (rand != null) {
[18132]273        foreach (var node in tree.IterateNodesPrefix().OfType<NumberTreeNode>()) {
[14319]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;
[14258]277        }
278      }
[14024]279      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
[14258]280
[18132]281      SymbolicRegressionParameterOptimizationEvaluator.OptimizeParameters(interpreter, tree, problemData, problemData.TrainingIndices,
[15502]282        applyLinearScaling: applyLinearScaling, maxIterations: maxIterations,
[18132]283        updateVariableWeights: false, updateParametersInTree: true);
[14024]284
[15502]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());
[14024]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.