Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Problems.GrammaticalOptimization.SymbReg/SymbolicRegressionProblem.cs @ 11902

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

#2283: preparations for transformation of expressions to canonical form

File size: 9.1 KB
Line 
1using System;
2using System.CodeDom.Compiler;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.Linq;
6using System.Security;
7using System.Security.AccessControl;
8using System.Security.Authentication.ExtendedProtection.Configuration;
9using System.Text;
10using AutoDiff;
11using HeuristicLab.Common;
12using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
13using HeuristicLab.Problems.DataAnalysis;
14using HeuristicLab.Problems.Instances;
15using HeuristicLab.Problems.Instances.DataAnalysis;
16
17namespace HeuristicLab.Problems.GrammaticalOptimization.SymbReg {
18  // provides bridge to HL regression problem instances
19  public class SymbolicRegressionProblem : ISymbolicExpressionTreeProblem {
20
21    // C represents Koza-style ERC (the symbol is the index of the ERC), the values are initialized below
22    private const string grammarString = @"
23        G(E):
24        E -> V | C | V+E | V-E | V*E | V%E | (E) | C+E | C-E | C*E | C%E
25        C -> 0..9
26        V -> <variables>
27        ";
28
29    // when using constant opt optimal constants are generated in the evaluation step so we don't need them in the grammar
30    private const string grammarConstOptString = @"
31        G(E):
32        E -> V | V+E | V*E | V%E | (E)
33        V -> <variables>
34        ";
35
36    // S .. Sum (+), N .. Neg. sum (-), P .. Product (*), D .. Division (%)
37    private const string treeGrammarString = @"
38        G(E):
39        E -> V | C | S | N | P | D
40        S -> EE | EEE
41        N -> EE | EEE
42        P -> EE | EEE
43        D -> EE
44        C -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
45        V -> <variables>
46        ";
47    private const string treeGrammarConstOptString = @"
48        G(E):
49        E -> V | S | P | D
50        S -> EE | EEE
51        P -> EE | EEE
52        D -> EE
53        V -> <variables>
54        ";
55
56    // when we use constants optimization we can completely ignore all constants by a simple strategy:
57    // introduce a constant factor for each complete term
58    // introduce a constant offset for each complete expression (including expressions in brackets)
59    // e.g. 1*(2*a + b - 3 + 4) is the same as c0*a + c1*b + c2
60
61    private readonly IGrammar grammar;
62
63    private readonly int N;
64    private readonly double[,] x;
65    private readonly double[] y;
66    private readonly int d;
67    private readonly double[] erc;
68    private readonly bool useConstantOpt;
69
70
71    public SymbolicRegressionProblem(Random random, string partOfName, bool useConstantOpt = true) {
72      var instanceProvider = new RegressionRealWorldInstanceProvider();
73      var dds = instanceProvider.GetDataDescriptors().OfType<RegressionDataDescriptor>();
74      this.useConstantOpt = useConstantOpt;
75
76      var problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
77
78      this.N = problemData.TrainingIndices.Count();
79      this.d = problemData.AllowedInputVariables.Count();
80      if (d > 26) throw new NotSupportedException(); // we only allow single-character terminal symbols so far
81      this.x = new double[N, d];
82      this.y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
83
84      int i = 0;
85      foreach (var r in problemData.TrainingIndices) {
86        int j = 0;
87        foreach (var inputVariable in problemData.AllowedInputVariables) {
88          x[i, j++] = problemData.Dataset.GetDoubleValue(inputVariable, r);
89        }
90        i++;
91      }
92      // initialize ERC values
93      erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
94
95      char firstVar = 'a';
96      char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
97      if (!useConstantOpt) {
98        this.grammar = new Grammar(grammarString.Replace("<variables>", firstVar + " .. " + lastVar));
99        this.TreeBasedGPGrammar = new Grammar(treeGrammarString.Replace("<variables>", firstVar + " .. " + lastVar));
100      } else {
101        this.grammar = new Grammar(grammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
102        this.TreeBasedGPGrammar = new Grammar(treeGrammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
103      }
104    }
105
106
107    public double BestKnownQuality(int maxLen) {
108      // for now only an upper bound is returned, ideally we have an R² of 1.0
109      return 1.0;
110    }
111
112    public IGrammar Grammar {
113      get { return grammar; }
114    }
115
116    public double Evaluate(string sentence) {
117      if (useConstantOpt)
118        return OptimizeConstantsAndEvaluate(sentence);
119      else {
120        return SimpleEvaluate(sentence);
121      }
122    }
123
124    public double SimpleEvaluate(string sentence) {
125      var interpreter = new ExpressionInterpreter();
126      var rowData = new double[d];
127      return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
128        for (int j = 0; j < d; j++) rowData[j] = x[i, j];
129        return interpreter.Interpret(sentence, rowData, erc);
130      }));
131    }
132
133
134    public string CanonicalRepresentation(string phrase) {
135      throw new NotImplementedException();
136    }
137
138    public IEnumerable<Feature> GetFeatures(string phrase) {
139      // first generate canonical expression (which must not contain ())
140      // recursively split into expressions
141      // for each expression split into terms
142      // for each term order factors to canonical // ../E = * 1/E
143      var canonical = CanonicalRepresentation(phrase);
144      throw new NotImplementedException();
145    }
146
147
148
149    public double OptimizeConstantsAndEvaluate(string sentence) {
150      AutoDiff.Term func;
151      int pos = 0;
152
153      var compiler = new ExpressionCompiler();
154      Variable[] variables;
155      Variable[] constants;
156      compiler.Compile(sentence, out func, out variables, out constants);
157
158      // constants are manipulated
159
160      if (!constants.Any()) return SimpleEvaluate(sentence);
161
162      AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(constants, variables); // variate constants leave variables fixed to data
163
164      double[] c = constants.Select(_ => 1.0).ToArray(); // start with ones
165
166      alglib.lsfitstate state;
167      alglib.lsfitreport rep;
168      int info;
169
170      int n = x.GetLength(0);
171      int m = x.GetLength(1);
172      int k = c.Length;
173
174      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
175      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
176
177      const int maxIterations = 10;
178      try {
179        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
180        alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
181        //alglib.lsfitsetgradientcheck(state, 0.001);
182        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
183        alglib.lsfitresults(state, out info, out c, out rep);
184      } catch (ArithmeticException) {
185        return 0.0;
186      } catch (alglib.alglibexception) {
187        return 0.0;
188      }
189
190      //info == -7  => constant optimization failed due to wrong gradient
191      if (info == -7) throw new ArgumentException();
192      {
193        var rowData = new double[d];
194        return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
195          for (int j = 0; j < d; j++) rowData[j] = x[i, j];
196          return compiledFunc.Evaluate(c, rowData);
197        }));
198      }
199    }
200
201
202    private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
203      return (double[] c, double[] x, ref double func, object o) => {
204        func = compiledFunc.Evaluate(c, x);
205      };
206    }
207
208    private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
209      return (double[] c, double[] x, ref double func, double[] grad, object o) => {
210        var tupel = compiledFunc.Differentiate(c, x);
211        func = tupel.Item2;
212        Array.Copy(tupel.Item1, grad, grad.Length);
213      };
214    }
215
216    public IGrammar TreeBasedGPGrammar { get; private set; }
217    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
218      var sb = new StringBuilder();
219
220      TreeToSentence(tree.Root.GetSubtree(0).GetSubtree(0), sb);
221
222      return sb.ToString();
223    }
224
225    private void TreeToSentence(ISymbolicExpressionTreeNode treeNode, StringBuilder sb) {
226      if (treeNode.SubtreeCount == 0) {
227        // terminal
228        sb.Append(treeNode.Symbol.Name);
229      } else {
230        string op = string.Empty;
231        switch (treeNode.Symbol.Name) {
232          case "S": op = "+"; break;
233          case "N": op = "-"; break;
234          case "P": op = "*"; break;
235          case "D": op = "%"; break;
236          default: {
237              Debug.Assert(treeNode.SubtreeCount == 1);
238              break;
239            }
240        }
241        // nonterminal
242        if (treeNode.SubtreeCount > 1) sb.Append("(");
243        TreeToSentence(treeNode.Subtrees.First(), sb);
244        foreach (var subTree in treeNode.Subtrees.Skip(1)) {
245          sb.Append(op);
246          TreeToSentence(subTree, sb);
247        }
248        if (treeNode.SubtreeCount > 1) sb.Append(")");
249      }
250    }
251  }
252}
Note: See TracBrowser for help on using the repository browser.