Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/MctsSymbolicRegression/MctsSymbolicRegressionAlgorithm.cs @ 13650

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

#2581: fixed License header

File size: 14.2 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> MaxSizeParameter {
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 MaxSize {
118      get { return MaxSizeParameter.Value.Value; }
119      set { MaxSizeParameter.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      // same as in SymbolicRegressionSingleObjectiveProblem
224      var y = Problem.ProblemData.Dataset.GetDoubleValues(Problem.ProblemData.TargetVariable,
225        Problem.ProblemData.TrainingIndices);
226      var avgY = y.Average();
227      var minY = y.Min();
228      var maxY = y.Max();
229      var range = maxY - minY;
230      var lowerLimit = avgY - PunishmentFactor * range;
231      var upperLimit = avgY + PunishmentFactor * range;
232
233      // init
234      var problemData = (IRegressionProblemData)Problem.ProblemData.Clone();
235      if (!AllowedFactors.CheckedItems.Any()) throw new ArgumentException("At least on type of factor must be allowed");
236      var state = MctsSymbolicRegressionStatic.CreateState(problemData, (uint)Seed, MaxSize, C, ScaleVariables, ConstantOptimizationIterations,
237        lowerLimit, upperLimit,
238        allowProdOfVars: AllowedFactors.CheckedItems.Any(s => s.Value.Value == VariableProductFactorName),
239        allowExp: AllowedFactors.CheckedItems.Any(s => s.Value.Value == ExpFactorName),
240        allowLog: AllowedFactors.CheckedItems.Any(s => s.Value.Value == LogFactorName),
241        allowInv: AllowedFactors.CheckedItems.Any(s => s.Value.Value == InvFactorName),
242        allowMultipleTerms: AllowedFactors.CheckedItems.Any(s => s.Value.Value == FactorSumsName)
243        );
244
245      var updateInterval = UpdateIntervalParameter.Value.Value;
246      double sumQ = 0.0;
247      double bestQ = 0.0;
248      double curBestQ = 0.0;
249      double q = 0.0;
250      int n = 0;
251      // Loop until iteration limit reached or canceled.
252      for (int i = 0; i < Iterations && !state.Done; i++) {
253        cancellationToken.ThrowIfCancellationRequested();
254
255        q = MctsSymbolicRegressionStatic.MakeStep(state);
256        sumQ += q; // sum of qs in the last updateinterval iterations
257        curBestQ = Math.Max(q, curBestQ); // the best q in the last updateinterval iterations
258        bestQ = Math.Max(q, bestQ); // the best q overall
259        n++;
260        // iteration results
261        if (n == updateInterval) {
262          bestQuality.Value = bestQ;
263          curQuality.Value = curBestQ;
264          avgQuality.Value = sumQ / n;
265          sumQ = 0.0;
266          curBestQ = 0.0;
267
268          table.Rows["Best quality"].Values.Add(bestQuality.Value);
269          table.Rows["Current best quality"].Values.Add(curQuality.Value);
270          table.Rows["Average quality"].Values.Add(avgQuality.Value);
271          iterations.Value += n;
272          n = 0;
273        }
274      }
275
276      // final results
277      if (n > 0) {
278        bestQuality.Value = bestQ;
279        curQuality.Value = curBestQ;
280        avgQuality.Value = sumQ / n;
281
282        table.Rows["Best quality"].Values.Add(bestQuality.Value);
283        table.Rows["Current best quality"].Values.Add(curQuality.Value);
284        table.Rows["Average quality"].Values.Add(avgQuality.Value);
285        iterations.Value = iterations.Value + n;
286      }
287
288
289      Results.Add(new Result("Best solution quality (train)", new DoubleValue(state.BestSolutionTrainingQuality)));
290      Results.Add(new Result("Best solution quality (test)", new DoubleValue(state.BestSolutionTestQuality)));
291
292      // produce solution
293      if (CreateSolution) {
294        var model = state.BestModel;
295
296        // otherwise we produce a regression solution
297        Results.Add(new Result("Solution", model.CreateRegressionSolution(problemData)));
298      }
299    }
300  }
301}
Note: See TracBrowser for help on using the repository browser.