Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Problems.GrammaticalOptimization.SymbReg/SymbolicRegressionProblem.cs @ 12893

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

#2283: experiments on grammatical optimization algorithms (maxreward instead of avg reward, ...)

File size: 12.6 KB
Line 
1using System;
2using System.CodeDom.Compiler;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.Globalization;
6using System.IO;
7using System.Linq;
8using System.Security;
9using System.Security.AccessControl;
10using System.Security.Authentication.ExtendedProtection.Configuration;
11using System.Text;
12using AutoDiff;
13using HeuristicLab.Algorithms.Bandits;
14using HeuristicLab.Common;
15using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
16using HeuristicLab.Problems.DataAnalysis;
17using HeuristicLab.Problems.Instances;
18using HeuristicLab.Problems.Instances.DataAnalysis;
19
20namespace HeuristicLab.Problems.GrammaticalOptimization.SymbReg {
21  // provides bridge to HL regression problem instances
22  public class SymbolicRegressionProblem : ISymbolicExpressionTreeProblem {
23
24    // C represents Koza-style ERC (the symbol is the index of the ERC), the values are initialized below
25    private const string grammarString = @"
26        G(E):
27        E -> V | C | V+E | V-E | V*E | V%E | (E) | C+E | C-E | C*E | C%E
28        C -> 0..9
29        V -> <variables>
30        ";
31
32    // when using constant opt optimal constants are generated in the evaluation step so we don't need them in the grammar
33    private const string grammarConstOptString = @"
34        G(E):
35        E -> V | V+E | V*E | V%E | (E)
36        V -> <variables>
37        ";
38
39    // S .. Sum (+), N .. Neg. sum (-), P .. Product (*), D .. Division (%)
40    private const string treeGrammarString = @"
41        G(E):
42        E -> V | C | S | N | P | D
43        S -> EE | EEE
44        N -> EE | EEE
45        P -> EE | EEE
46        D -> EE
47        C -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
48        V -> <variables>
49        ";
50    private const string treeGrammarConstOptString = @"
51        G(E):
52        E -> V | S | P | D
53        S -> EE | EEE
54        P -> EE | EEE
55        D -> EE
56        V -> <variables>
57        ";
58
59    // when we use constants optimization we can completely ignore all constants by a simple strategy:
60    // introduce a constant factor for each complete term
61    // introduce a constant offset for each complete expression (including expressions in brackets)
62    // e.g. 1*(2*a + b - 3 + 4) is the same as c0*a + c1*b + c2
63
64    private readonly IGrammar grammar;
65
66    private readonly int N;
67    private readonly double[,] x;
68    private readonly double[] y;
69    private readonly int d;
70    private readonly double[] erc;
71    private readonly bool useConstantOpt;
72    public string Name { get; private set; }
73    private Random random;
74
75
76    // lambda should be tuned using CV
77    public SymbolicRegressionProblem(Random random, string partOfName, bool useConstantOpt = true) {
78      var instanceProviders = new RegressionInstanceProvider[]
79      {new RegressionRealWorldInstanceProvider(),
80        new HeuristicLab.Problems.Instances.DataAnalysis.VariousInstanceProvider(),
81        new KeijzerInstanceProvider(),
82        new VladislavlevaInstanceProvider(),
83        new NguyenInstanceProvider(),
84        new KornsInstanceProvider(),
85    };
86      var instanceProvider = instanceProviders.FirstOrDefault(prov => prov.GetDataDescriptors().Any(dd => dd.Name.Contains(partOfName)));
87      IRegressionProblemData problemData = null;
88      if (instanceProvider != null) {
89        var dds = instanceProvider.GetDataDescriptors();
90        problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
91
92      } else if (File.Exists(partOfName)) {
93        // check if it is a file
94        var prov = new RegressionCSVInstanceProvider();
95        problemData = prov.ImportData(partOfName);
96        problemData.TrainingPartition.Start = 0;
97        problemData.TrainingPartition.End = problemData.Dataset.Rows;
98        // no test partition
99        problemData.TestPartition.Start = problemData.Dataset.Rows;
100        problemData.TestPartition.End = problemData.Dataset.Rows;
101      } else {
102        throw new ArgumentException("instance not found");
103      }
104
105      this.useConstantOpt = useConstantOpt;
106
107      this.Name = problemData.Name;
108
109      this.N = problemData.TrainingIndices.Count();
110      this.d = problemData.AllowedInputVariables.Count();
111      if (d > 26) throw new NotSupportedException(); // we only allow single-character terminal symbols so far
112      this.x = new double[N, d];
113      this.y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
114
115      var varEst = new OnlineMeanAndVarianceCalculator();
116
117      var means = new double[d];
118      var stdDevs = new double[d];
119
120      int i = 0;
121      foreach (var inputVariable in problemData.AllowedInputVariables) {
122        varEst.Reset();
123        problemData.Dataset.GetDoubleValues(inputVariable).ToList().ForEach(varEst.Add);
124        if (varEst.VarianceErrorState != OnlineCalculatorError.None) throw new ArgumentException();
125        means[i] = varEst.Mean;
126        stdDevs[i] = Math.Sqrt(varEst.Variance);
127        i++;
128      }
129
130      i = 0;
131      foreach (var r in problemData.TrainingIndices) {
132        int j = 0;
133        foreach (var inputVariable in problemData.AllowedInputVariables) {
134          x[i, j] = (problemData.Dataset.GetDoubleValue(inputVariable, r) - means[j]) / stdDevs[j];
135          j++;
136        }
137        i++;
138      }
139
140      this.random = random;
141
142      // initialize ERC values
143      erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
144
145      char firstVar = 'a';
146      char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
147      if (!useConstantOpt) {
148        this.grammar = new Grammar(grammarString.Replace("<variables>", firstVar + " .. " + lastVar));
149        this.TreeBasedGPGrammar = new Grammar(treeGrammarString.Replace("<variables>", firstVar + " .. " + lastVar));
150      } else {
151        this.grammar = new Grammar(grammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
152        this.TreeBasedGPGrammar = new Grammar(treeGrammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
153      }
154    }
155
156
157    public double BestKnownQuality(int maxLen) {
158      // for now only an upper bound is returned, ideally we have an R² of 1.0
159      return 1.0;
160    }
161
162    public IGrammar Grammar {
163      get { return grammar; }
164    }
165
166    public double Evaluate(string sentence) {
167      //var extender = new ExpressionExtender();
168      //sentence = extender.CanonicalRepresentation(sentence);
169      if (useConstantOpt)
170        return OptimizeConstantsAndEvaluate(sentence);
171      else {
172        //Debug.Assert(SimpleEvaluate(sentence) == SimpleEvaluate(extender.CanonicalRepresentation(sentence)));
173        return SimpleEvaluate(sentence);
174      }
175    }
176
177    public double SimpleEvaluate(string sentence) {
178      var interpreter = new ExpressionInterpreter();
179      var rowData = new double[d];
180      return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
181        for (int j = 0; j < d; j++) rowData[j] = x[i, j];
182        return interpreter.Interpret(sentence, rowData, erc);
183      }));
184    }
185
186
187    public string CanonicalRepresentation(string phrase) {
188      var extender = new ExpressionExtender();
189      return extender.CanonicalRepresentation(phrase);
190    }
191
192    public IEnumerable<Feature> GetFeatures(string phrase) {
193      throw new NotImplementedException();
194      //phrase = CanonicalRepresentation(phrase);
195      //return phrase.Split('+').Distinct().Select(t => new Feature(t, 1.0));
196      // return new Feature[] { new Feature(phrase, 1.0) };
197    }
198
199    public bool IsOptimalPhrase(string phrase) {
200      return false;
201    }
202
203
204    public double OptimizeConstantsAndEvaluate(string sentence) {
205      AutoDiff.Term func;
206      int n = x.GetLength(0);
207      int m = x.GetLength(1);
208
209      var compiler = new ExpressionCompiler();
210      Variable[] variables = Enumerable.Range(0, m).Select(_ => new Variable()).ToArray();
211      Variable[] constants;
212      compiler.Compile(sentence, out func, variables, out constants);
213
214      // constants are manipulated
215
216      if (!constants.Any()) return SimpleEvaluate(sentence);
217
218      // L2 regularization
219      // not possible with lsfit, would need to change to minlm below
220      // func = TermBuilder.Sum(func, lambda * TermBuilder.Sum(constants.Select(con => con * con)));
221
222      AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(constants, variables); // variate constants, leave variables fixed to data
223
224      // 10 restarts with random starting points
225      double[] bestStart = null;
226      double bestError = double.PositiveInfinity;
227      int info;
228      alglib.lsfitstate state;
229      alglib.lsfitreport rep;
230      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
231      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
232      for (int t = 0; t < 1; t++) {
233        double[] cStart = constants.Select(_ => Rand.RandNormal(random) * 10).ToArray();
234        double[] cEnd;
235        // start with normally distributed (N(0, 10)) weights
236
237
238        int k = cStart.Length;
239
240
241        const int maxIterations = 10;
242        try {
243          alglib.lsfitcreatefg(x, y, cStart, n, m, k, false, out state);
244          alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
245          //alglib.lsfitsetgradientcheck(state, 0.001);
246          alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
247          alglib.lsfitresults(state, out info, out cEnd, out rep);
248          if (info != -7 && rep.rmserror < bestError) {
249            bestStart = cStart;
250            bestError = rep.rmserror;
251          }
252        } catch (ArithmeticException) {
253          return 0.0;
254        } catch (alglib.alglibexception) {
255          return 0.0;
256        }
257      }
258
259      // 100 iteration steps from the best starting point
260      {
261        double[] c = bestStart;
262
263        int k = c.Length;
264
265        const int maxIterations = 100;
266        try {
267          alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
268          alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
269          //alglib.lsfitsetgradientcheck(state, 0.001);
270          alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
271          alglib.lsfitresults(state, out info, out c, out rep);
272        } catch (ArithmeticException) {
273          return 0.0;
274        } catch (alglib.alglibexception) {
275          return 0.0;
276        }
277        //info == -7  => constant optimization failed due to wrong gradient
278        if (info == -7) throw new ArgumentException();
279        {
280          var rowData = new double[d];
281          return Math.Round(HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
282            for (int j = 0; j < d; j++) rowData[j] = x[i, j];
283            return compiledFunc.Evaluate(c, rowData);
284          })), 3);
285        }
286      }
287    }
288
289
290    private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
291      return (double[] c, double[] x, ref double func, object o) => {
292        func = compiledFunc.Evaluate(c, x);
293      };
294    }
295
296    private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
297      return (double[] c, double[] x, ref double func, double[] grad, object o) => {
298        var tupel = compiledFunc.Differentiate(c, x);
299        func = tupel.Item2;
300        Array.Copy(tupel.Item1, grad, grad.Length);
301      };
302    }
303
304    public IGrammar TreeBasedGPGrammar { get; private set; }
305    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
306      var sb = new StringBuilder();
307
308      TreeToSentence(tree.Root.GetSubtree(0).GetSubtree(0), sb);
309
310      return sb.ToString();
311    }
312
313
314    private void TreeToSentence(ISymbolicExpressionTreeNode treeNode, StringBuilder sb) {
315      if (treeNode.SubtreeCount == 0) {
316        // terminal
317        sb.Append(treeNode.Symbol.Name);
318      } else {
319        string op = string.Empty;
320        switch (treeNode.Symbol.Name) {
321          case "S": op = "+"; break;
322          case "N": op = "-"; break;
323          case "P": op = "*"; break;
324          case "D": op = "%"; break;
325          default: {
326              Debug.Assert(treeNode.SubtreeCount == 1);
327              break;
328            }
329        }
330        // nonterminal
331        if (treeNode.SubtreeCount > 1) sb.Append("(");
332        TreeToSentence(treeNode.Subtrees.First(), sb);
333        foreach (var subTree in treeNode.Subtrees.Skip(1)) {
334          sb.Append(op);
335          TreeToSentence(subTree, sb);
336        }
337        if (treeNode.SubtreeCount > 1) sb.Append(")");
338      }
339    }
340  }
341}
Note: See TracBrowser for help on using the repository browser.