[11732] | 1 | using System;
|
---|
[11895] | 2 | using System.CodeDom.Compiler;
|
---|
[11732] | 3 | using System.Collections.Generic;
|
---|
[11895] | 4 | using System.Diagnostics;
|
---|
[11732] | 5 | using System.Linq;
|
---|
| 6 | using System.Security;
|
---|
| 7 | using System.Security.AccessControl;
|
---|
[11895] | 8 | using System.Security.Authentication.ExtendedProtection.Configuration;
|
---|
[11732] | 9 | using System.Text;
|
---|
[11895] | 10 | using AutoDiff;
|
---|
[12014] | 11 | using HeuristicLab.Algorithms.Bandits;
|
---|
[11732] | 12 | using HeuristicLab.Common;
|
---|
[11895] | 13 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[11732] | 14 | using HeuristicLab.Problems.DataAnalysis;
|
---|
| 15 | using HeuristicLab.Problems.Instances;
|
---|
| 16 | using HeuristicLab.Problems.Instances.DataAnalysis;
|
---|
| 17 |
|
---|
| 18 | namespace HeuristicLab.Problems.GrammaticalOptimization.SymbReg {
|
---|
| 19 | // provides bridge to HL regression problem instances
|
---|
[11895] | 20 | public class SymbolicRegressionProblem : ISymbolicExpressionTreeProblem {
|
---|
[11832] | 21 |
|
---|
[11902] | 22 | // C represents Koza-style ERC (the symbol is the index of the ERC), the values are initialized below
|
---|
[11732] | 23 | private const string grammarString = @"
|
---|
| 24 | G(E):
|
---|
[11895] | 25 | E -> V | C | V+E | V-E | V*E | V%E | (E) | C+E | C-E | C*E | C%E
|
---|
[11832] | 26 | C -> 0..9
|
---|
[11732] | 27 | V -> <variables>
|
---|
| 28 | ";
|
---|
| 29 |
|
---|
[11902] | 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 |
|
---|
[11895] | 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 | ";
|
---|
[11902] | 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 | ";
|
---|
[11895] | 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 |
|
---|
[11732] | 62 | private readonly IGrammar grammar;
|
---|
| 63 |
|
---|
| 64 | private readonly int N;
|
---|
[11895] | 65 | private readonly double[,] x;
|
---|
[11732] | 66 | private readonly double[] y;
|
---|
| 67 | private readonly int d;
|
---|
[11832] | 68 | private readonly double[] erc;
|
---|
[11902] | 69 | private readonly bool useConstantOpt;
|
---|
[12099] | 70 | public string Name { get; private set; }
|
---|
[11732] | 71 |
|
---|
[11902] | 72 | public SymbolicRegressionProblem(Random random, string partOfName, bool useConstantOpt = true) {
|
---|
[11972] | 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 |
|
---|
[11902] | 84 | this.useConstantOpt = useConstantOpt;
|
---|
[11732] | 85 |
|
---|
[11972] | 86 | var dds = instanceProvider.GetDataDescriptors();
|
---|
[11732] | 87 | var problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
|
---|
[12099] | 88 | this.Name = problemData.Name;
|
---|
[11732] | 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
|
---|
[11895] | 93 | this.x = new double[N, d];
|
---|
[11732] | 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) {
|
---|
[11895] | 100 | x[i, j++] = problemData.Dataset.GetDoubleValue(inputVariable, r);
|
---|
[11732] | 101 | }
|
---|
| 102 | i++;
|
---|
| 103 | }
|
---|
[11832] | 104 | // initialize ERC values
|
---|
| 105 | erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
|
---|
[11732] | 106 |
|
---|
| 107 | char firstVar = 'a';
|
---|
| 108 | char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
|
---|
[11902] | 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 | }
|
---|
[11732] | 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) {
|
---|
[12024] | 129 | var extender = new ExpressionExtender();
|
---|
| 130 | sentence = extender.CanonicalRepresentation(sentence);
|
---|
[11902] | 131 | if (useConstantOpt)
|
---|
| 132 | return OptimizeConstantsAndEvaluate(sentence);
|
---|
| 133 | else {
|
---|
[12014] | 134 |
|
---|
| 135 | Debug.Assert(SimpleEvaluate(sentence) == SimpleEvaluate(extender.CanonicalRepresentation(sentence)));
|
---|
[11902] | 136 | return SimpleEvaluate(sentence);
|
---|
| 137 | }
|
---|
[11895] | 138 | }
|
---|
| 139 |
|
---|
| 140 | public double SimpleEvaluate(string sentence) {
|
---|
[11832] | 141 | var interpreter = new ExpressionInterpreter();
|
---|
[11895] | 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 | }));
|
---|
[11732] | 147 | }
|
---|
| 148 |
|
---|
| 149 |
|
---|
[11832] | 150 | public string CanonicalRepresentation(string phrase) {
|
---|
[12014] | 151 | var extender = new ExpressionExtender();
|
---|
| 152 | return extender.CanonicalRepresentation(phrase);
|
---|
[11732] | 153 | }
|
---|
[11832] | 154 |
|
---|
[11895] | 155 | public IEnumerable<Feature> GetFeatures(string phrase) {
|
---|
[12024] | 156 | // throw new NotImplementedException();
|
---|
[12014] | 157 | phrase = CanonicalRepresentation(phrase);
|
---|
[12024] | 158 | return phrase.Split('+').Distinct().Select(t => new Feature(t, 1.0));
|
---|
| 159 | // return new Feature[] { new Feature(phrase, 1.0) };
|
---|
[11832] | 160 | }
|
---|
| 161 |
|
---|
| 162 |
|
---|
| 163 |
|
---|
[11895] | 164 | public double OptimizeConstantsAndEvaluate(string sentence) {
|
---|
[11832] | 165 | AutoDiff.Term func;
|
---|
[11972] | 166 | int n = x.GetLength(0);
|
---|
| 167 | int m = x.GetLength(1);
|
---|
[11832] | 168 |
|
---|
[11895] | 169 | var compiler = new ExpressionCompiler();
|
---|
[11972] | 170 | Variable[] variables = Enumerable.Range(0, m).Select(_ => new Variable()).ToArray();
|
---|
[11895] | 171 | Variable[] constants;
|
---|
[11972] | 172 | compiler.Compile(sentence, out func, variables, out constants);
|
---|
[11832] | 173 |
|
---|
[11895] | 174 | // constants are manipulated
|
---|
[11832] | 175 |
|
---|
[11895] | 176 | if (!constants.Any()) return SimpleEvaluate(sentence);
|
---|
[11832] | 177 |
|
---|
[11895] | 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 |
|
---|
[11832] | 182 | alglib.lsfitstate state;
|
---|
| 183 | alglib.lsfitreport rep;
|
---|
| 184 | int info;
|
---|
| 185 |
|
---|
[11972] | 186 |
|
---|
[11832] | 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 |
|
---|
[11895] | 192 | const int maxIterations = 10;
|
---|
[11832] | 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) {
|
---|
[11895] | 200 | return 0.0;
|
---|
[11832] | 201 | } catch (alglib.alglibexception) {
|
---|
[11895] | 202 | return 0.0;
|
---|
[11832] | 203 | }
|
---|
| 204 |
|
---|
| 205 | //info == -7 => constant optimization failed due to wrong gradient
|
---|
[11895] | 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 | }
|
---|
[11832] | 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 |
|
---|
[11895] | 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 |
|
---|
[11972] | 240 |
|
---|
[11895] | 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;
|
---|
[11832] | 255 | }
|
---|
| 256 | }
|
---|
[11895] | 257 | // nonterminal
|
---|
[11902] | 258 | if (treeNode.SubtreeCount > 1) sb.Append("(");
|
---|
[11895] | 259 | TreeToSentence(treeNode.Subtrees.First(), sb);
|
---|
| 260 | foreach (var subTree in treeNode.Subtrees.Skip(1)) {
|
---|
| 261 | sb.Append(op);
|
---|
| 262 | TreeToSentence(subTree, sb);
|
---|
[11832] | 263 | }
|
---|
[11902] | 264 | if (treeNode.SubtreeCount > 1) sb.Append(")");
|
---|
[11832] | 265 | }
|
---|
| 266 | }
|
---|
[12815] | 267 |
|
---|
| 268 |
|
---|
| 269 | public void GenerateProblemSolutions(int maxLen)
|
---|
| 270 | {
|
---|
| 271 | throw new NotImplementedException();
|
---|
| 272 | }
|
---|
| 273 |
|
---|
| 274 | public bool IsParentOfProblemSolution(string sentence, int maxLen)
|
---|
| 275 | {
|
---|
| 276 | throw new NotImplementedException();
|
---|
| 277 | }
|
---|
[11732] | 278 | }
|
---|
| 279 | }
|
---|