Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12448 was 12099, checked in by gkronber, 10 years ago

#2283: name for all problems (for output), new unit test, and added testsettings file

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