Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Algorithms.DataAnalysis/3.4/MctsSymbolicRegression/MctsSymbolicRegressionAlgorithm.cs @ 17578

Last change on this file since 17578 was 13652, checked in by gkronber, 9 years ago

#2581:

  • removed simplification of trees (temporarily for better debugging)
  • renamed MaxSize parameter
  • fixed a small bug in MCTS
  • changed SymbolicExpressionGenerator to produce trees in the correct order
File size: 15.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Runtime.CompilerServices;
25using System.Threading;
26using HeuristicLab.Analysis;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Problems.DataAnalysis;
34
35namespace HeuristicLab.Algorithms.DataAnalysis.MctsSymbolicRegression {
36  [Item("MCTS Symbolic Regression", "Monte carlo tree search for symbolic regression. Useful mainly as a base learner in gradient boosting.")]
37  [StorableClass]
38  [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 250)]
39  public class MctsSymbolicRegressionAlgorithm : BasicAlgorithm {
40    public override Type ProblemType {
41      get { return typeof(IRegressionProblem); }
42    }
43    public new IRegressionProblem Problem {
44      get { return (IRegressionProblem)base.Problem; }
45      set { base.Problem = value; }
46    }
47
48    #region ParameterNames
49    private const string IterationsParameterName = "Iterations";
50    private const string MaxVariablesParameterName = "Maximum variables";
51    private const string ScaleVariablesParameterName = "Scale variables";
52    private const string AllowedFactorsParameterName = "Allowed factors";
53    private const string ConstantOptimizationIterationsParameterName = "Iterations (constant optimization)";
54    private const string CParameterName = "C";
55    private const string SeedParameterName = "Seed";
56    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
57    private const string UpdateIntervalParameterName = "UpdateInterval";
58    private const string CreateSolutionParameterName = "CreateSolution";
59    private const string PunishmentFactorParameterName = "PunishmentFactor";
60
61    private const string VariableProductFactorName = "product(xi)";
62    private const string ExpFactorName = "exp(c * product(xi))";
63    private const string LogFactorName = "log(c + sum(c*product(xi))";
64    private const string InvFactorName = "1 / (1 + sum(c*product(xi))";
65    private const string FactorSumsName = "sum of multiple terms";
66    #endregion
67
68    #region ParameterProperties
69    public IFixedValueParameter<IntValue> IterationsParameter {
70      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
71    }
72    public IFixedValueParameter<IntValue> MaxVariableReferencesParameter {
73      get { return (IFixedValueParameter<IntValue>)Parameters[MaxVariablesParameterName]; }
74    }
75    public IFixedValueParameter<BoolValue> ScaleVariablesParameter {
76      get { return (IFixedValueParameter<BoolValue>)Parameters[ScaleVariablesParameterName]; }
77    }
78    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
79      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
80    }
81    public IFixedValueParameter<DoubleValue> CParameter {
82      get { return (IFixedValueParameter<DoubleValue>)Parameters[CParameterName]; }
83    }
84    public IFixedValueParameter<DoubleValue> PunishmentFactorParameter {
85      get { return (IFixedValueParameter<DoubleValue>)Parameters[PunishmentFactorParameterName]; }
86    }
87    public IValueParameter<ICheckedItemList<StringValue>> AllowedFactorsParameter {
88      get { return (IValueParameter<ICheckedItemList<StringValue>>)Parameters[AllowedFactorsParameterName]; }
89    }
90    public IFixedValueParameter<IntValue> SeedParameter {
91      get { return (IFixedValueParameter<IntValue>)Parameters[SeedParameterName]; }
92    }
93    public FixedValueParameter<BoolValue> SetSeedRandomlyParameter {
94      get { return (FixedValueParameter<BoolValue>)Parameters[SetSeedRandomlyParameterName]; }
95    }
96    public IFixedValueParameter<IntValue> UpdateIntervalParameter {
97      get { return (IFixedValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
98    }
99    public IFixedValueParameter<BoolValue> CreateSolutionParameter {
100      get { return (IFixedValueParameter<BoolValue>)Parameters[CreateSolutionParameterName]; }
101    }
102    #endregion
103
104    #region Properties
105    public int Iterations {
106      get { return IterationsParameter.Value.Value; }
107      set { IterationsParameter.Value.Value = value; }
108    }
109    public int Seed {
110      get { return SeedParameter.Value.Value; }
111      set { SeedParameter.Value.Value = value; }
112    }
113    public bool SetSeedRandomly {
114      get { return SetSeedRandomlyParameter.Value.Value; }
115      set { SetSeedRandomlyParameter.Value.Value = value; }
116    }
117    public int MaxVariableReferences {
118      get { return MaxVariableReferencesParameter.Value.Value; }
119      set { MaxVariableReferencesParameter.Value.Value = value; }
120    }
121    public double C {
122      get { return CParameter.Value.Value; }
123      set { CParameter.Value.Value = value; }
124    }
125
126    public double PunishmentFactor {
127      get { return PunishmentFactorParameter.Value.Value; }
128      set { PunishmentFactorParameter.Value.Value = value; }
129    }
130    public ICheckedItemList<StringValue> AllowedFactors {
131      get { return AllowedFactorsParameter.Value; }
132    }
133    public int ConstantOptimizationIterations {
134      get { return ConstantOptimizationIterationsParameter.Value.Value; }
135      set { ConstantOptimizationIterationsParameter.Value.Value = value; }
136    }
137    public bool ScaleVariables {
138      get { return ScaleVariablesParameter.Value.Value; }
139      set { ScaleVariablesParameter.Value.Value = value; }
140    }
141    public bool CreateSolution {
142      get { return CreateSolutionParameter.Value.Value; }
143      set { CreateSolutionParameter.Value.Value = value; }
144    }
145    #endregion
146
147    [StorableConstructor]
148    protected MctsSymbolicRegressionAlgorithm(bool deserializing) : base(deserializing) { }
149
150    protected MctsSymbolicRegressionAlgorithm(MctsSymbolicRegressionAlgorithm original, Cloner cloner)
151      : base(original, cloner) {
152    }
153
154    public override IDeepCloneable Clone(Cloner cloner) {
155      return new MctsSymbolicRegressionAlgorithm(this, cloner);
156    }
157
158    public MctsSymbolicRegressionAlgorithm() {
159      Problem = new RegressionProblem(); // default problem
160
161      var defaultFactorsList = new CheckedItemList<StringValue>(
162        new string[] { VariableProductFactorName, ExpFactorName, LogFactorName, InvFactorName, FactorSumsName }
163        .Select(s => new StringValue(s).AsReadOnly())
164        ).AsReadOnly();
165      defaultFactorsList.SetItemCheckedState(defaultFactorsList.First(s => s.Value == FactorSumsName), false);
166
167      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName,
168        "Number of iterations", new IntValue(100000)));
169      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName,
170        "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
171      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName,
172        "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
173      Parameters.Add(new FixedValueParameter<IntValue>(MaxVariablesParameterName,
174        "Maximal number of variables references in the symbolic regression models (multiple usages of the same variable are counted)", new IntValue(5)));
175      Parameters.Add(new FixedValueParameter<DoubleValue>(CParameterName,
176        "Balancing parameter in UCT formula (0 < c < 1000). Small values: greedy search. Large values: enumeration. Default: 1.0", new DoubleValue(1.0)));
177      Parameters.Add(new ValueParameter<ICheckedItemList<StringValue>>(AllowedFactorsParameterName,
178        "Choose which expressions are allowed as factors in the model.", defaultFactorsList));
179
180      Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName,
181        "Number of iterations for constant optimization. A small number of iterations should be sufficient for most models. " +
182        "Set to 0 to disable constants optimization.", new IntValue(10)));
183      Parameters.Add(new FixedValueParameter<BoolValue>(ScaleVariablesParameterName,
184        "Set to true to scale all input variables to the range [0..1]", new BoolValue(false)));
185      Parameters[ScaleVariablesParameterName].Hidden = true;
186      Parameters.Add(new FixedValueParameter<DoubleValue>(PunishmentFactorParameterName, "Estimations of models can be bounded. The estimation limits are calculated in the following way (lb = mean(y) - punishmentFactor*range(y), ub = mean(y) + punishmentFactor*range(y))", new DoubleValue(10)));
187      Parameters[PunishmentFactorParameterName].Hidden = true;
188      Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName,
189        "Number of iterations until the results are updated", new IntValue(100)));
190      Parameters[UpdateIntervalParameterName].Hidden = true;
191      Parameters.Add(new FixedValueParameter<BoolValue>(CreateSolutionParameterName,
192        "Flag that indicates if a solution should be produced at the end of the run", new BoolValue(true)));
193      Parameters[CreateSolutionParameterName].Hidden = true;
194    }
195
196    [StorableHook(HookType.AfterDeserialization)]
197    private void AfterDeserialization() {
198    }
199
200    protected override void Run(CancellationToken cancellationToken) {
201      // Set up the algorithm
202      if (SetSeedRandomly) Seed = new System.Random().Next();
203
204      // Set up the results display
205      var iterations = new IntValue(0);
206      Results.Add(new Result("Iterations", iterations));
207
208      var table = new DataTable("Qualities");
209      table.Rows.Add(new DataRow("Best quality"));
210      table.Rows.Add(new DataRow("Current best quality"));
211      table.Rows.Add(new DataRow("Average quality"));
212      Results.Add(new Result("Qualities", table));
213
214      var bestQuality = new DoubleValue();
215      Results.Add(new Result("Best quality", bestQuality));
216
217      var curQuality = new DoubleValue();
218      Results.Add(new Result("Current best quality", curQuality));
219
220      var avgQuality = new DoubleValue();
221      Results.Add(new Result("Average quality", avgQuality));
222
223      var totalRollouts = new IntValue();
224      Results.Add(new Result("Total rollouts", totalRollouts));
225      var effRollouts = new IntValue();
226      Results.Add(new Result("Effective rollouts", effRollouts));
227      var funcEvals = new IntValue();
228      Results.Add(new Result("Function evaluations", funcEvals));
229      var gradEvals = new IntValue();
230      Results.Add(new Result("Gradient evaluations", gradEvals));
231
232
233      // same as in SymbolicRegressionSingleObjectiveProblem
234      var y = Problem.ProblemData.Dataset.GetDoubleValues(Problem.ProblemData.TargetVariable,
235        Problem.ProblemData.TrainingIndices);
236      var avgY = y.Average();
237      var minY = y.Min();
238      var maxY = y.Max();
239      var range = maxY - minY;
240      var lowerLimit = avgY - PunishmentFactor * range;
241      var upperLimit = avgY + PunishmentFactor * range;
242
243      // init
244      var problemData = (IRegressionProblemData)Problem.ProblemData.Clone();
245      if (!AllowedFactors.CheckedItems.Any()) throw new ArgumentException("At least on type of factor must be allowed");
246      var state = MctsSymbolicRegressionStatic.CreateState(problemData, (uint)Seed, MaxVariableReferences, C, ScaleVariables, ConstantOptimizationIterations,
247        lowerLimit, upperLimit,
248        allowProdOfVars: AllowedFactors.CheckedItems.Any(s => s.Value.Value == VariableProductFactorName),
249        allowExp: AllowedFactors.CheckedItems.Any(s => s.Value.Value == ExpFactorName),
250        allowLog: AllowedFactors.CheckedItems.Any(s => s.Value.Value == LogFactorName),
251        allowInv: AllowedFactors.CheckedItems.Any(s => s.Value.Value == InvFactorName),
252        allowMultipleTerms: AllowedFactors.CheckedItems.Any(s => s.Value.Value == FactorSumsName)
253        );
254
255      var updateInterval = UpdateIntervalParameter.Value.Value;
256      double sumQ = 0.0;
257      double bestQ = 0.0;
258      double curBestQ = 0.0;
259      double q = 0.0;
260      int n = 0;
261      // Loop until iteration limit reached or canceled.
262      for (int i = 0; i < Iterations && !state.Done; i++) {
263        cancellationToken.ThrowIfCancellationRequested();
264
265        q = MctsSymbolicRegressionStatic.MakeStep(state);
266        sumQ += q; // sum of qs in the last updateinterval iterations
267        curBestQ = Math.Max(q, curBestQ); // the best q in the last updateinterval iterations
268        bestQ = Math.Max(q, bestQ); // the best q overall
269        n++;
270        // iteration results
271        if (n == updateInterval) {
272          bestQuality.Value = bestQ;
273          curQuality.Value = curBestQ;
274          avgQuality.Value = sumQ / n;
275          sumQ = 0.0;
276          curBestQ = 0.0;
277
278          funcEvals.Value = state.FuncEvaluations;
279          gradEvals.Value = state.GradEvaluations;
280          effRollouts.Value = state.EffectiveRollouts;
281          totalRollouts.Value = state.TotalRollouts;
282
283          table.Rows["Best quality"].Values.Add(bestQuality.Value);
284          table.Rows["Current best quality"].Values.Add(curQuality.Value);
285          table.Rows["Average quality"].Values.Add(avgQuality.Value);
286          iterations.Value += n;
287          n = 0;
288        }
289      }
290
291      // final results
292      if (n > 0) {
293        bestQuality.Value = bestQ;
294        curQuality.Value = curBestQ;
295        avgQuality.Value = sumQ / n;
296
297        funcEvals.Value = state.FuncEvaluations;
298        gradEvals.Value = state.GradEvaluations;
299        effRollouts.Value = state.EffectiveRollouts;
300        totalRollouts.Value = state.TotalRollouts;
301
302        table.Rows["Best quality"].Values.Add(bestQuality.Value);
303        table.Rows["Current best quality"].Values.Add(curQuality.Value);
304        table.Rows["Average quality"].Values.Add(avgQuality.Value);
305        iterations.Value = iterations.Value + n;
306
307      }
308
309
310      Results.Add(new Result("Best solution quality (train)", new DoubleValue(state.BestSolutionTrainingQuality)));
311      Results.Add(new Result("Best solution quality (test)", new DoubleValue(state.BestSolutionTestQuality)));
312
313
314      // produce solution
315      if (CreateSolution) {
316        var model = state.BestModel;
317
318        // otherwise we produce a regression solution
319        Results.Add(new Result("Solution", model.CreateRegressionSolution(problemData)));
320      }
321    }
322  }
323}
Note: See TracBrowser for help on using the repository browser.