Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17347 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 15.4 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, "The function for which the parameters must be fit (only numeric constants are tuned).", new StringValue("1.0 * x*x + 0.0")));
126      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "The maximum number of iterations for constants optimization.", new IntValue(200)));
127      Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts (>0)", new IntValue(10)));
128      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
129      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
130      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)));
131      Parameters.Add(new FixedValueParameter<BoolValue>(ApplyLinearScalingParameterName, "Switch to determine if linear scaling terms should be added to the model", new BoolValue(true)));
132
133      SetParameterHiddenState();
134
135      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
136        SetParameterHiddenState();
137      };
138    }
139
140    private void SetParameterHiddenState() {
141      var hide = !InitializeParametersRandomly;
142      RestartsParameter.Hidden = hide;
143      SeedParameter.Hidden = hide;
144      SetSeedRandomlyParameter.Hidden = hide;
145    }
146
147    [StorableHook(HookType.AfterDeserialization)]
148    private void AfterDeserialization() {
149      // BackwardsCompatibility3.3
150      #region Backwards compatible code, remove with 3.4
151      if (!Parameters.ContainsKey(RestartsParameterName))
152        Parameters.Add(new FixedValueParameter<IntValue>(RestartsParameterName, "The number of independent random restarts", new IntValue(1)));
153      if (!Parameters.ContainsKey(SeedParameterName))
154        Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The PRNG seed value.", new IntValue()));
155      if (!Parameters.ContainsKey(SetSeedRandomlyParameterName))
156        Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "Switch to determine if the random number seed should be initialized randomly.", new BoolValue(true)));
157      if (!Parameters.ContainsKey(InitParamsRandomlyParameterName))
158        Parameters.Add(new FixedValueParameter<BoolValue>(InitParamsRandomlyParameterName, "Switch to determine if the numeric parameters of the model should be initialized randomly.", new BoolValue(false)));
159      if (!Parameters.ContainsKey(ApplyLinearScalingParameterName))
160        Parameters.Add(new FixedValueParameter<BoolValue>(ApplyLinearScalingParameterName, "Switch to determine if linear scaling terms should be added to the model", new BoolValue(true)));
161
162
163      SetParameterHiddenState();
164      InitParametersRandomlyParameter.Value.ValueChanged += (sender, args) => {
165        SetParameterHiddenState();
166      };
167      #endregion
168    }
169
170    public override IDeepCloneable Clone(Cloner cloner) {
171      return new NonlinearRegression(this, cloner);
172    }
173
174    #region nonlinear regression
175    protected override void Run(CancellationToken cancellationToken) {
176      IRegressionSolution bestSolution = null;
177      if (InitializeParametersRandomly) {
178        var qualityTable = new DataTable("RMSE table");
179        qualityTable.VisualProperties.YAxisLogScale = true;
180        var trainRMSERow = new DataRow("RMSE (train)");
181        trainRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
182        var testRMSERow = new DataRow("RMSE test");
183        testRMSERow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
184
185        qualityTable.Rows.Add(trainRMSERow);
186        qualityTable.Rows.Add(testRMSERow);
187        Results.Add(new Result(qualityTable.Name, qualityTable.Name + " for all restarts", qualityTable));
188        if (SetSeedRandomly) Seed = RandomSeedGenerator.GetSeed();
189        var rand = new MersenneTwister((uint)Seed);
190        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand);
191        trainRMSERow.Values.Add(bestSolution.TrainingRootMeanSquaredError);
192        testRMSERow.Values.Add(bestSolution.TestRootMeanSquaredError);
193        for (int r = 0; r < Restarts; r++) {
194          var solution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling, rand);
195          trainRMSERow.Values.Add(solution.TrainingRootMeanSquaredError);
196          testRMSERow.Values.Add(solution.TestRootMeanSquaredError);
197          if (solution.TrainingRootMeanSquaredError < bestSolution.TrainingRootMeanSquaredError) {
198            bestSolution = solution;
199          }
200        }
201      } else {
202        bestSolution = CreateRegressionSolution(Problem.ProblemData, ModelStructure, Iterations, ApplyLinearScaling);
203      }
204
205      Results.Add(new Result(RegressionSolutionResultName, "The nonlinear regression solution.", bestSolution));
206      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)));
207      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)));
208
209    }
210
211    /// <summary>
212    /// Fits a model to the data by optimizing the numeric constants.
213    /// Model is specified as infix expression containing variable names and numbers.
214    /// 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
215    /// used as a starting point.
216    /// </summary>-
217    /// <param name="problemData">Training and test data</param>
218    /// <param name="modelStructure">The function as infix expression</param>
219    /// <param name="maxIterations">Number of constant optimization iterations (using Levenberg-Marquardt algorithm)</param>
220    /// <param name="random">Optional random number generator for random initialization of numeric constants.</param>
221    /// <returns></returns>
222    public static ISymbolicRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData, string modelStructure, int maxIterations, bool applyLinearScaling, IRandom rand = null) {
223      var parser = new InfixExpressionParser();
224      var tree = parser.Parse(modelStructure);
225      // parser handles double and string variables equally by creating a VariableTreeNode
226      // post-process to replace VariableTreeNodes by FactorVariableTreeNodes for all string variables
227      var factorSymbol = new FactorVariable();
228      factorSymbol.VariableNames =
229        problemData.AllowedInputVariables.Where(name => problemData.Dataset.VariableHasType<string>(name));
230      factorSymbol.AllVariableNames = factorSymbol.VariableNames;
231      factorSymbol.VariableValues =
232        factorSymbol.VariableNames.Select(name =>
233        new KeyValuePair<string, Dictionary<string, int>>(name,
234        problemData.Dataset.GetReadOnlyStringValues(name).Distinct()
235        .Select((n, i) => Tuple.Create(n, i))
236        .ToDictionary(tup => tup.Item1, tup => tup.Item2)));
237
238      foreach (var parent in tree.IterateNodesPrefix().ToArray()) {
239        for (int i = 0; i < parent.SubtreeCount; i++) {
240          var varChild = parent.GetSubtree(i) as VariableTreeNode;
241          var factorVarChild = parent.GetSubtree(i) as FactorVariableTreeNode;
242          if (varChild != null && factorSymbol.VariableNames.Contains(varChild.VariableName)) {
243            parent.RemoveSubtree(i);
244            var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode();
245            factorTreeNode.VariableName = varChild.VariableName;
246            factorTreeNode.Weights =
247              factorTreeNode.Symbol.GetVariableValues(factorTreeNode.VariableName).Select(_ => 1.0).ToArray();
248            // weight = 1.0 for each value
249            parent.InsertSubtree(i, factorTreeNode);
250          } else if (factorVarChild != null && factorSymbol.VariableNames.Contains(factorVarChild.VariableName)) {
251            if (factorSymbol.GetVariableValues(factorVarChild.VariableName).Count() != factorVarChild.Weights.Length)
252              throw new ArgumentException(
253                string.Format("Factor variable {0} needs exactly {1} weights",
254                factorVarChild.VariableName,
255                factorSymbol.GetVariableValues(factorVarChild.VariableName).Count()));
256            parent.RemoveSubtree(i);
257            var factorTreeNode = (FactorVariableTreeNode)factorSymbol.CreateTreeNode();
258            factorTreeNode.VariableName = factorVarChild.VariableName;
259            factorTreeNode.Weights = factorVarChild.Weights;
260            parent.InsertSubtree(i, factorTreeNode);
261          }
262        }
263      }
264
265      if (!SymbolicRegressionConstantOptimizationEvaluator.CanOptimizeConstants(tree)) throw new ArgumentException("The optimizer does not support the specified model structure.");
266
267      // initialize constants randomly
268      if (rand != null) {
269        foreach (var node in tree.IterateNodesPrefix().OfType<ConstantTreeNode>()) {
270          double f = Math.Exp(NormalDistributedRandom.NextDouble(rand, 0, 1));
271          double s = rand.NextDouble() < 0.5 ? -1 : 1;
272          node.Value = s * node.Value * f;
273        }
274      }
275      var interpreter = new SymbolicDataAnalysisExpressionTreeLinearInterpreter();
276
277      SymbolicRegressionConstantOptimizationEvaluator.OptimizeConstants(interpreter, tree, problemData, problemData.TrainingIndices,
278        applyLinearScaling: applyLinearScaling, maxIterations: maxIterations,
279        updateVariableWeights: false, updateConstantsInTree: true);
280
281      var model = new SymbolicRegressionModel(problemData.TargetVariable, tree, (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter.Clone());
282      if (applyLinearScaling)
283        model.Scale(problemData);
284
285      SymbolicRegressionSolution solution = new SymbolicRegressionSolution(model, (IRegressionProblemData)problemData.Clone());
286      solution.Model.Name = "Regression Model";
287      solution.Name = "Regression Solution";
288      return solution;
289    }
290    #endregion
291  }
292}
Note: See TracBrowser for help on using the repository browser.