Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2283 created a new branch to separate development from aballeit

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    private double lambda;
75
76
77    // lambda should be tuned using CV
78    public SymbolicRegressionProblem(Random random, string partOfName, double lambda = 1.0, bool useConstantOpt = true) {
79      var instanceProviders = new RegressionInstanceProvider[]
80      {new RegressionRealWorldInstanceProvider(),
81        new HeuristicLab.Problems.Instances.DataAnalysis.VariousInstanceProvider(),
82        new KeijzerInstanceProvider(),
83        new VladislavlevaInstanceProvider(),
84        new NguyenInstanceProvider(),
85        new KornsInstanceProvider(),
86    };
87      var instanceProvider = instanceProviders.FirstOrDefault(prov => prov.GetDataDescriptors().Any(dd => dd.Name.Contains(partOfName)));
88      IRegressionProblemData problemData = null;
89      if (instanceProvider != null) {
90        var dds = instanceProvider.GetDataDescriptors();
91        problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
92
93      } else if (File.Exists(partOfName)) {
94        // check if it is a file
95        var prov = new RegressionCSVInstanceProvider();
96        problemData = prov.ImportData(partOfName);
97        problemData.TrainingPartition.Start = 0;
98        problemData.TrainingPartition.End = problemData.Dataset.Rows;
99        // no test partition
100        problemData.TestPartition.Start = problemData.Dataset.Rows;
101        problemData.TestPartition.End = problemData.Dataset.Rows;
102      } else {
103        throw new ArgumentException("instance not found");
104      }
105
106      this.useConstantOpt = useConstantOpt;
107
108      this.Name = problemData.Name + string.Format("lambda={0:N2}", lambda);
109
110      this.N = problemData.TrainingIndices.Count();
111      this.d = problemData.AllowedInputVariables.Count();
112      if (d > 26) throw new NotSupportedException(); // we only allow single-character terminal symbols so far
113      this.x = new double[N, d];
114      this.y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
115
116      var varEst = new OnlineMeanAndVarianceCalculator();
117
118      var means = new double[d];
119      var stdDevs = new double[d];
120
121      int i = 0;
122      foreach (var inputVariable in problemData.AllowedInputVariables) {
123        varEst.Reset();
124        problemData.Dataset.GetDoubleValues(inputVariable).ToList().ForEach(varEst.Add);
125        if (varEst.VarianceErrorState != OnlineCalculatorError.None) throw new ArgumentException();
126        means[i] = varEst.Mean;
127        stdDevs[i] = Math.Sqrt(varEst.Variance);
128        i++;
129      }
130
131      i = 0;
132      foreach (var r in problemData.TrainingIndices) {
133        int j = 0;
134        foreach (var inputVariable in problemData.AllowedInputVariables) {
135          x[i, j] = (problemData.Dataset.GetDoubleValue(inputVariable, r) - means[j]) / stdDevs[j];
136          j++;
137        }
138        i++;
139      }
140
141      this.random = random;
142      this.lambda = lambda;
143
144      // initialize ERC values
145      erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
146
147      char firstVar = 'a';
148      char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
149      if (!useConstantOpt) {
150        this.grammar = new Grammar(grammarString.Replace("<variables>", firstVar + " .. " + lastVar));
151        this.TreeBasedGPGrammar = new Grammar(treeGrammarString.Replace("<variables>", firstVar + " .. " + lastVar));
152      } else {
153        this.grammar = new Grammar(grammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
154        this.TreeBasedGPGrammar = new Grammar(treeGrammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
155      }
156    }
157
158
159    public double BestKnownQuality(int maxLen) {
160      // for now only an upper bound is returned, ideally we have an R² of 1.0
161      return 1.0;
162    }
163
164    public IGrammar Grammar {
165      get { return grammar; }
166    }
167
168    public double Evaluate(string sentence) {
169      var extender = new ExpressionExtender();
170      sentence = extender.CanonicalRepresentation(sentence);
171      if (useConstantOpt)
172        return OptimizeConstantsAndEvaluate(sentence);
173      else {
174        Debug.Assert(SimpleEvaluate(sentence) == SimpleEvaluate(extender.CanonicalRepresentation(sentence)));
175        return SimpleEvaluate(sentence);
176      }
177    }
178
179    public double SimpleEvaluate(string sentence) {
180      var interpreter = new ExpressionInterpreter();
181      var rowData = new double[d];
182      return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
183        for (int j = 0; j < d; j++) rowData[j] = x[i, j];
184        return interpreter.Interpret(sentence, rowData, erc);
185      }));
186    }
187
188
189    public string CanonicalRepresentation(string phrase) {
190      var extender = new ExpressionExtender();
191      return extender.CanonicalRepresentation(phrase);
192    }
193
194    public IEnumerable<Feature> GetFeatures(string phrase) {
195      throw new NotImplementedException();
196      //phrase = CanonicalRepresentation(phrase);
197      //return phrase.Split('+').Distinct().Select(t => new Feature(t, 1.0));
198      // return new Feature[] { new Feature(phrase, 1.0) };
199    }
200
201
202
203    public double OptimizeConstantsAndEvaluate(string sentence) {
204      AutoDiff.Term func;
205      int n = x.GetLength(0);
206      int m = x.GetLength(1);
207
208      var compiler = new ExpressionCompiler();
209      Variable[] variables = Enumerable.Range(0, m).Select(_ => new Variable()).ToArray();
210      Variable[] constants;
211      compiler.Compile(sentence, out func, variables, out constants);
212
213      // constants are manipulated
214
215      if (!constants.Any()) return SimpleEvaluate(sentence);
216
217      // L2 regularization
218      // not possible with lsfit, would need to change to minlm below
219      // func = TermBuilder.Sum(func, lambda * TermBuilder.Sum(constants.Select(con => con * con)));
220
221      AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(constants, variables); // variate constants, leave variables fixed to data
222
223      // 10 restarts with random starting points
224      double[] bestStart = null;
225      double bestError = double.PositiveInfinity;
226      int info;
227      alglib.lsfitstate state;
228      alglib.lsfitreport rep;
229      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
230      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
231      for (int t = 0; t < 10; t++) {
232        double[] cStart = constants.Select(_ => Rand.RandNormal(random) * 10).ToArray();
233        double[] cEnd;
234        // start with normally distributed (N(0, 10)) weights
235
236
237        int k = cStart.Length;
238
239
240        const int maxIterations = 10;
241        try {
242          alglib.lsfitcreatefg(x, y, cStart, n, m, k, false, out state);
243          alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
244          //alglib.lsfitsetgradientcheck(state, 0.001);
245          alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
246          alglib.lsfitresults(state, out info, out cEnd, out rep);
247          if (info != -7 && rep.rmserror < bestError) {
248            bestStart = cStart;
249            bestError = rep.rmserror;
250          }
251        } catch (ArithmeticException) {
252          return 0.0;
253        } catch (alglib.alglibexception) {
254          return 0.0;
255        }
256      }
257
258      // 100 iteration steps from the best starting point
259      {
260        double[] c = bestStart;
261
262        int k = c.Length;
263
264        const int maxIterations = 100;
265        try {
266          alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
267          alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
268          //alglib.lsfitsetgradientcheck(state, 0.001);
269          alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
270          alglib.lsfitresults(state, out info, out c, out rep);
271        } catch (ArithmeticException) {
272          return 0.0;
273        } catch (alglib.alglibexception) {
274          return 0.0;
275        }
276        //info == -7  => constant optimization failed due to wrong gradient
277        if (info == -7) throw new ArgumentException();
278        {
279          var rowData = new double[d];
280          return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
281            for (int j = 0; j < d; j++) rowData[j] = x[i, j];
282            return compiledFunc.Evaluate(c, rowData);
283          }));
284        }
285      }
286    }
287
288
289    private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
290      return (double[] c, double[] x, ref double func, object o) => {
291        func = compiledFunc.Evaluate(c, x);
292      };
293    }
294
295    private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
296      return (double[] c, double[] x, ref double func, double[] grad, object o) => {
297        var tupel = compiledFunc.Differentiate(c, x);
298        func = tupel.Item2;
299        Array.Copy(tupel.Item1, grad, grad.Length);
300      };
301    }
302
303    public IGrammar TreeBasedGPGrammar { get; private set; }
304    public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
305      var sb = new StringBuilder();
306
307      TreeToSentence(tree.Root.GetSubtree(0).GetSubtree(0), sb);
308
309      return sb.ToString();
310    }
311
312
313    private void TreeToSentence(ISymbolicExpressionTreeNode treeNode, StringBuilder sb) {
314      if (treeNode.SubtreeCount == 0) {
315        // terminal
316        sb.Append(treeNode.Symbol.Name);
317      } else {
318        string op = string.Empty;
319        switch (treeNode.Symbol.Name) {
320          case "S": op = "+"; break;
321          case "N": op = "-"; break;
322          case "P": op = "*"; break;
323          case "D": op = "%"; break;
324          default: {
325              Debug.Assert(treeNode.SubtreeCount == 1);
326              break;
327            }
328        }
329        // nonterminal
330        if (treeNode.SubtreeCount > 1) sb.Append("(");
331        TreeToSentence(treeNode.Subtrees.First(), sb);
332        foreach (var subTree in treeNode.Subtrees.Skip(1)) {
333          sb.Append(op);
334          TreeToSentence(subTree, sb);
335        }
336        if (treeNode.SubtreeCount > 1) sb.Append(")");
337      }
338    }
339  }
340}
Note: See TracBrowser for help on using the repository browser.