Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MCTS-SymbReg-2796/HeuristicLab.Algorithms.DataAnalysis/3.4/MctsSymbolicRegression/MctsSymbolicRegressionAlgorithm.cs @ 15360

Last change on this file since 15360 was 15360, checked in by gkronber, 7 years ago

#2796 added collection of Pareto-optimal solutions

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