Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17226 was 17226, checked in by mkommend, 5 years ago

#2521: Merged trunk changes into problem refactoring branch.

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