Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/NonlinearRegression/NonlinearRegression.cs @ 14277

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

#2650: merged r14245:14273 from trunk to branch (fixing conflicts in RegressionSolutionTargetResponseGradientView)

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