Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.GeneticProgramming/3.3/BasicSymbolicRegression/Problem.cs @ 17382

Last change on this file since 17382 was 17382, checked in by mkommend, 4 years ago

#2521: Refactored single-objective problems to use EvaluationResult instead of double as return type from Evaluate.

File size: 8.0 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 HEAL.Attic;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.Instances;
34
35
36namespace HeuristicLab.Problems.GeneticProgramming.BasicSymbolicRegression {
37  [Item("Koza-style Symbolic Regression", "An implementation of symbolic regression without bells-and-whistles. Use \"Symbolic Regression Problem (single-objective)\" if you want to use all features.")]
38  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 900)]
39  [StorableType("72011B73-28C6-4D5E-BEDF-27425BC87B9C")]
40  public sealed class Problem : SymbolicExpressionTreeProblem, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData>, IProblemInstanceExporter<IRegressionProblemData> {
41
42    #region parameter names
43    private const string ProblemDataParameterName = "ProblemData";
44    #endregion
45
46    #region Parameter Properties
47    IParameter IDataAnalysisProblem.ProblemDataParameter { get { return ProblemDataParameter; } }
48
49    public IValueParameter<IRegressionProblemData> ProblemDataParameter {
50      get { return (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; }
51    }
52    #endregion
53
54    #region Properties
55    public IRegressionProblemData ProblemData {
56      get { return ProblemDataParameter.Value; }
57      set { ProblemDataParameter.Value = value; }
58    }
59    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData { get { return ProblemData; } }
60    #endregion
61
62    public event EventHandler ProblemDataChanged;
63
64    #region item cloning and persistence
65    // persistence
66    [StorableConstructor]
67    private Problem(StorableConstructorFlag _) : base(_) { }
68    [StorableHook(HookType.AfterDeserialization)]
69    private void AfterDeserialization() {
70      RegisterEventHandlers();
71    }
72
73    // cloning
74    private Problem(Problem original, Cloner cloner)
75      : base(original, cloner) {
76      RegisterEventHandlers();
77    }
78    public override IDeepCloneable Clone(Cloner cloner) { return new Problem(this, cloner); }
79    #endregion
80
81    public Problem() : base(new SymbolicExpressionTreeEncoding()) {
82      Maximization = true;
83      Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, "The data for the regression problem", new RegressionProblemData()));
84
85      Encoding.TreeLength = 100;
86      Encoding.TreeDepth = 17;
87
88      UpdateGrammar();
89      RegisterEventHandlers();
90    }
91
92
93    public override ISingleObjectiveEvaluationResult Evaluate(ISymbolicExpressionTree tree, IRandom random, CancellationToken cancellationToken) {
94      // Doesn't use classes from HeuristicLab.Problems.DataAnalysis.Symbolic to make sure that the implementation can be fully understood easily.
95      // HeuristicLab.Problems.DataAnalysis.Symbolic would already provide all the necessary functionality (esp. interpreter) but at a much higher complexity.
96      // Another argument is that we don't need a reference to HeuristicLab.Problems.DataAnalysis.Symbolic
97
98      var problemData = ProblemData;
99      var rows = ProblemData.TrainingIndices.ToArray();
100      var target = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
101      var predicted = Interpret(tree, problemData.Dataset, rows);
102
103      OnlineCalculatorError errorState;
104      var r = OnlinePearsonsRCalculator.Calculate(target, predicted, out errorState);
105      if (errorState != OnlineCalculatorError.None) r = 0;
106      var quality = r * r;
107
108      return new SingleObjectiveEvaluationResult(quality);
109    }
110
111    private IEnumerable<double> Interpret(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
112      // skip programRoot and startSymbol
113      return InterpretRec(tree.Root.GetSubtree(0).GetSubtree(0), dataset, rows);
114    }
115
116    private IEnumerable<double> InterpretRec(ISymbolicExpressionTreeNode node, IDataset dataset, IEnumerable<int> rows) {
117      Func<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode, Func<double, double, double>, IEnumerable<double>> binaryEval =
118        (left, right, f) => InterpretRec(left, dataset, rows).Zip(InterpretRec(right, dataset, rows), f);
119
120      switch (node.Symbol.Name) {
121        case "+": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x + y);
122        case "*": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x * y);
123        case "-": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x - y);
124        case "%": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => y.IsAlmost(0.0) ? 0.0 : x / y); // protected division
125        default: {
126            double erc;
127            if (double.TryParse(node.Symbol.Name, out erc)) {
128              return rows.Select(_ => erc);
129            } else {
130              // assume that this is a variable name
131              return dataset.GetDoubleValues(node.Symbol.Name, rows);
132            }
133          }
134      }
135    }
136
137
138    #region events
139    private void RegisterEventHandlers() {
140      ProblemDataParameter.ValueChanged += new EventHandler(ProblemDataParameter_ValueChanged);
141      if (ProblemDataParameter.Value != null) ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
142    }
143
144    private void ProblemDataParameter_ValueChanged(object sender, EventArgs e) {
145      ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
146      OnProblemDataChanged();
147      OnReset();
148    }
149
150    private void ProblemData_Changed(object sender, EventArgs e) {
151      OnReset();
152    }
153
154    private void OnProblemDataChanged() {
155      UpdateGrammar();
156
157      var handler = ProblemDataChanged;
158      if (handler != null) handler(this, EventArgs.Empty);
159    }
160
161    private void UpdateGrammar() {
162      // whenever ProblemData is changed we create a new grammar with the necessary symbols
163      var g = new SimpleSymbolicExpressionGrammar();
164      g.AddSymbols(new[] { "+", "*", "%", "-" }, 2, 2); // % is protected division 1/0 := 0
165
166      foreach (var variableName in ProblemData.AllowedInputVariables)
167        g.AddTerminalSymbol(variableName);
168
169      // generate ephemeral random consts in the range [-10..+10[ (2*number of variables)
170      var rand = new System.Random();
171      for (int i = 0; i < ProblemData.AllowedInputVariables.Count() * 2; i++) {
172        string newErcSy;
173        do {
174          newErcSy = string.Format("{0:F2}", rand.NextDouble() * 20 - 10);
175        } while (g.Symbols.Any(sy => sy.Name == newErcSy)); // it might happen that we generate the same constant twice
176        g.AddTerminalSymbol(newErcSy);
177      }
178
179      Encoding.GrammarParameter.ReadOnly = false;
180      Encoding.Grammar = g;
181      Encoding.GrammarParameter.ReadOnly = true;
182    }
183    #endregion
184
185    #region Import & Export
186    public void Load(IRegressionProblemData data) {
187      Name = data.Name;
188      Description = data.Description;
189      ProblemData = data;
190    }
191
192    public IRegressionProblemData Export() {
193      return ProblemData;
194    }
195    #endregion
196  }
197}
Note: See TracBrowser for help on using the repository browser.