1 | using System;
|
---|
2 | using System.CodeDom.Compiler;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.Diagnostics;
|
---|
5 | using System.Linq;
|
---|
6 | using System.Security;
|
---|
7 | using System.Security.AccessControl;
|
---|
8 | using System.Security.Authentication.ExtendedProtection.Configuration;
|
---|
9 | using System.Text;
|
---|
10 | using AutoDiff;
|
---|
11 | using HeuristicLab.Common;
|
---|
12 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
13 | using HeuristicLab.Problems.DataAnalysis;
|
---|
14 | using HeuristicLab.Problems.Instances;
|
---|
15 | using HeuristicLab.Problems.Instances.DataAnalysis;
|
---|
16 |
|
---|
17 | namespace 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 instanceProviders = new RegressionInstanceProvider[]
|
---|
73 | {new RegressionRealWorldInstanceProvider(),
|
---|
74 | new HeuristicLab.Problems.Instances.DataAnalysis.VariousInstanceProvider(),
|
---|
75 | new KeijzerInstanceProvider(),
|
---|
76 | new VladislavlevaInstanceProvider(),
|
---|
77 | new NguyenInstanceProvider(),
|
---|
78 | new KornsInstanceProvider(),
|
---|
79 | };
|
---|
80 | var instanceProvider = instanceProviders.FirstOrDefault(prov => prov.GetDataDescriptors().Any(dd => dd.Name.Contains(partOfName)));
|
---|
81 | if (instanceProvider == null) throw new ArgumentException("instance not found");
|
---|
82 |
|
---|
83 | this.useConstantOpt = useConstantOpt;
|
---|
84 |
|
---|
85 | var dds = instanceProvider.GetDataDescriptors();
|
---|
86 | var problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
|
---|
87 |
|
---|
88 | this.N = problemData.TrainingIndices.Count();
|
---|
89 | this.d = problemData.AllowedInputVariables.Count();
|
---|
90 | if (d > 26) throw new NotSupportedException(); // we only allow single-character terminal symbols so far
|
---|
91 | this.x = new double[N, d];
|
---|
92 | this.y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
|
---|
93 |
|
---|
94 | int i = 0;
|
---|
95 | foreach (var r in problemData.TrainingIndices) {
|
---|
96 | int j = 0;
|
---|
97 | foreach (var inputVariable in problemData.AllowedInputVariables) {
|
---|
98 | x[i, j++] = problemData.Dataset.GetDoubleValue(inputVariable, r);
|
---|
99 | }
|
---|
100 | i++;
|
---|
101 | }
|
---|
102 | // initialize ERC values
|
---|
103 | erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
|
---|
104 |
|
---|
105 | char firstVar = 'a';
|
---|
106 | char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
|
---|
107 | if (!useConstantOpt) {
|
---|
108 | this.grammar = new Grammar(grammarString.Replace("<variables>", firstVar + " .. " + lastVar));
|
---|
109 | this.TreeBasedGPGrammar = new Grammar(treeGrammarString.Replace("<variables>", firstVar + " .. " + lastVar));
|
---|
110 | } else {
|
---|
111 | this.grammar = new Grammar(grammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
|
---|
112 | this.TreeBasedGPGrammar = new Grammar(treeGrammarConstOptString.Replace("<variables>", firstVar + " .. " + lastVar));
|
---|
113 | }
|
---|
114 | }
|
---|
115 |
|
---|
116 |
|
---|
117 | public double BestKnownQuality(int maxLen) {
|
---|
118 | // for now only an upper bound is returned, ideally we have an R² of 1.0
|
---|
119 | return 1.0;
|
---|
120 | }
|
---|
121 |
|
---|
122 | public IGrammar Grammar {
|
---|
123 | get { return grammar; }
|
---|
124 | }
|
---|
125 |
|
---|
126 | public double Evaluate(string sentence) {
|
---|
127 | if (useConstantOpt)
|
---|
128 | return OptimizeConstantsAndEvaluate(sentence);
|
---|
129 | else {
|
---|
130 | return SimpleEvaluate(sentence);
|
---|
131 | }
|
---|
132 | }
|
---|
133 |
|
---|
134 | public double SimpleEvaluate(string sentence) {
|
---|
135 | var interpreter = new ExpressionInterpreter();
|
---|
136 | var rowData = new double[d];
|
---|
137 | return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
|
---|
138 | for (int j = 0; j < d; j++) rowData[j] = x[i, j];
|
---|
139 | return interpreter.Interpret(sentence, rowData, erc);
|
---|
140 | }));
|
---|
141 | }
|
---|
142 |
|
---|
143 |
|
---|
144 | public string CanonicalRepresentation(string phrase) {
|
---|
145 | return phrase;
|
---|
146 | }
|
---|
147 |
|
---|
148 | public IEnumerable<Feature> GetFeatures(string phrase) {
|
---|
149 | // first generate canonical expression (which must not contain ())
|
---|
150 | // recursively split into expressions
|
---|
151 | // for each expression split into terms
|
---|
152 | // for each term order factors to canonical // ../E = * 1/E
|
---|
153 | return new Feature[] { new Feature(phrase, 1.0) };
|
---|
154 | }
|
---|
155 |
|
---|
156 |
|
---|
157 |
|
---|
158 | public double OptimizeConstantsAndEvaluate(string sentence) {
|
---|
159 | AutoDiff.Term func;
|
---|
160 | int pos = 0;
|
---|
161 | int n = x.GetLength(0);
|
---|
162 | int m = x.GetLength(1);
|
---|
163 |
|
---|
164 | var compiler = new ExpressionCompiler();
|
---|
165 | Variable[] variables = Enumerable.Range(0, m).Select(_ => new Variable()).ToArray();
|
---|
166 | Variable[] constants;
|
---|
167 | compiler.Compile(sentence, out func, variables, out constants);
|
---|
168 |
|
---|
169 | // constants are manipulated
|
---|
170 |
|
---|
171 | if (!constants.Any()) return SimpleEvaluate(sentence);
|
---|
172 |
|
---|
173 | AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(constants, variables); // variate constants leave variables fixed to data
|
---|
174 |
|
---|
175 | double[] c = constants.Select(_ => 1.0).ToArray(); // start with ones
|
---|
176 |
|
---|
177 | alglib.lsfitstate state;
|
---|
178 | alglib.lsfitreport rep;
|
---|
179 | int info;
|
---|
180 |
|
---|
181 |
|
---|
182 | int k = c.Length;
|
---|
183 |
|
---|
184 | alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
|
---|
185 | alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
|
---|
186 |
|
---|
187 | const int maxIterations = 10;
|
---|
188 | try {
|
---|
189 | alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
|
---|
190 | alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
|
---|
191 | //alglib.lsfitsetgradientcheck(state, 0.001);
|
---|
192 | alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
|
---|
193 | alglib.lsfitresults(state, out info, out c, out rep);
|
---|
194 | } catch (ArithmeticException) {
|
---|
195 | return 0.0;
|
---|
196 | } catch (alglib.alglibexception) {
|
---|
197 | return 0.0;
|
---|
198 | }
|
---|
199 |
|
---|
200 | //info == -7 => constant optimization failed due to wrong gradient
|
---|
201 | if (info == -7) throw new ArgumentException();
|
---|
202 | {
|
---|
203 | var rowData = new double[d];
|
---|
204 | return HeuristicLab.Common.Extensions.RSq(y, Enumerable.Range(0, N).Select(i => {
|
---|
205 | for (int j = 0; j < d; j++) rowData[j] = x[i, j];
|
---|
206 | return compiledFunc.Evaluate(c, rowData);
|
---|
207 | }));
|
---|
208 | }
|
---|
209 | }
|
---|
210 |
|
---|
211 |
|
---|
212 | private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
213 | return (double[] c, double[] x, ref double func, object o) => {
|
---|
214 | func = compiledFunc.Evaluate(c, x);
|
---|
215 | };
|
---|
216 | }
|
---|
217 |
|
---|
218 | private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
|
---|
219 | return (double[] c, double[] x, ref double func, double[] grad, object o) => {
|
---|
220 | var tupel = compiledFunc.Differentiate(c, x);
|
---|
221 | func = tupel.Item2;
|
---|
222 | Array.Copy(tupel.Item1, grad, grad.Length);
|
---|
223 | };
|
---|
224 | }
|
---|
225 |
|
---|
226 | public IGrammar TreeBasedGPGrammar { get; private set; }
|
---|
227 | public string ConvertTreeToSentence(ISymbolicExpressionTree tree) {
|
---|
228 | var sb = new StringBuilder();
|
---|
229 |
|
---|
230 | TreeToSentence(tree.Root.GetSubtree(0).GetSubtree(0), sb);
|
---|
231 |
|
---|
232 | return sb.ToString();
|
---|
233 | }
|
---|
234 |
|
---|
235 |
|
---|
236 | private void TreeToSentence(ISymbolicExpressionTreeNode treeNode, StringBuilder sb) {
|
---|
237 | if (treeNode.SubtreeCount == 0) {
|
---|
238 | // terminal
|
---|
239 | sb.Append(treeNode.Symbol.Name);
|
---|
240 | } else {
|
---|
241 | string op = string.Empty;
|
---|
242 | switch (treeNode.Symbol.Name) {
|
---|
243 | case "S": op = "+"; break;
|
---|
244 | case "N": op = "-"; break;
|
---|
245 | case "P": op = "*"; break;
|
---|
246 | case "D": op = "%"; break;
|
---|
247 | default: {
|
---|
248 | Debug.Assert(treeNode.SubtreeCount == 1);
|
---|
249 | break;
|
---|
250 | }
|
---|
251 | }
|
---|
252 | // nonterminal
|
---|
253 | if (treeNode.SubtreeCount > 1) sb.Append("(");
|
---|
254 | TreeToSentence(treeNode.Subtrees.First(), sb);
|
---|
255 | foreach (var subTree in treeNode.Subtrees.Skip(1)) {
|
---|
256 | sb.Append(op);
|
---|
257 | TreeToSentence(subTree, sb);
|
---|
258 | }
|
---|
259 | if (treeNode.SubtreeCount > 1) sb.Append(")");
|
---|
260 | }
|
---|
261 | }
|
---|
262 | }
|
---|
263 | }
|
---|