[11732] | 1 | using System;
|
---|
[11895] | 2 | using System.CodeDom.Compiler;
|
---|
[11732] | 3 | using System.Collections.Generic;
|
---|
[11895] | 4 | using System.Diagnostics;
|
---|
[12290] | 5 | using System.Globalization;
|
---|
| 6 | using System.IO;
|
---|
[11732] | 7 | using System.Linq;
|
---|
| 8 | using System.Security;
|
---|
| 9 | using System.Security.AccessControl;
|
---|
[11895] | 10 | using System.Security.Authentication.ExtendedProtection.Configuration;
|
---|
[11732] | 11 | using System.Text;
|
---|
[11895] | 12 | using AutoDiff;
|
---|
[12014] | 13 | using HeuristicLab.Algorithms.Bandits;
|
---|
[11732] | 14 | using HeuristicLab.Common;
|
---|
[11895] | 15 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[11732] | 16 | using HeuristicLab.Problems.DataAnalysis;
|
---|
| 17 | using HeuristicLab.Problems.Instances;
|
---|
| 18 | using HeuristicLab.Problems.Instances.DataAnalysis;
|
---|
| 19 |
|
---|
| 20 | namespace HeuristicLab.Problems.GrammaticalOptimization.SymbReg {
|
---|
| 21 | // provides bridge to HL regression problem instances
|
---|
[11895] | 22 | public class SymbolicRegressionProblem : ISymbolicExpressionTreeProblem {
|
---|
[11832] | 23 |
|
---|
[11902] | 24 | // C represents Koza-style ERC (the symbol is the index of the ERC), the values are initialized below
|
---|
[11732] | 25 | private const string grammarString = @"
|
---|
| 26 | G(E):
|
---|
[11895] | 27 | E -> V | C | V+E | V-E | V*E | V%E | (E) | C+E | C-E | C*E | C%E
|
---|
[11832] | 28 | C -> 0..9
|
---|
[11732] | 29 | V -> <variables>
|
---|
| 30 | ";
|
---|
| 31 |
|
---|
[11902] | 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 |
|
---|
[11895] | 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 | ";
|
---|
[11902] | 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 | ";
|
---|
[11895] | 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 |
|
---|
[11732] | 64 | private readonly IGrammar grammar;
|
---|
| 65 |
|
---|
| 66 | private readonly int N;
|
---|
[11895] | 67 | private readonly double[,] x;
|
---|
[11732] | 68 | private readonly double[] y;
|
---|
| 69 | private readonly int d;
|
---|
[11832] | 70 | private readonly double[] erc;
|
---|
[11902] | 71 | private readonly bool useConstantOpt;
|
---|
[12099] | 72 | public string Name { get; private set; }
|
---|
[12290] | 73 | private Random random;
|
---|
| 74 | private double lambda;
|
---|
[11732] | 75 |
|
---|
[12290] | 76 |
|
---|
| 77 | // lambda should be tuned using CV
|
---|
| 78 | public SymbolicRegressionProblem(Random random, string partOfName, double lambda = 1.0, bool useConstantOpt = true) {
|
---|
[11972] | 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)));
|
---|
[12290] | 88 | IRegressionProblemData problemData = null;
|
---|
| 89 | if (instanceProvider != null) {
|
---|
| 90 | var dds = instanceProvider.GetDataDescriptors();
|
---|
| 91 | problemData = instanceProvider.LoadData(dds.Single(ds => ds.Name.Contains(partOfName)));
|
---|
[11972] | 92 |
|
---|
[12290] | 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 |
|
---|
[11902] | 106 | this.useConstantOpt = useConstantOpt;
|
---|
[11732] | 107 |
|
---|
[12290] | 108 | this.Name = problemData.Name + string.Format("lambda={0:N2}", lambda);
|
---|
[11732] | 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
|
---|
[11895] | 113 | this.x = new double[N, d];
|
---|
[11732] | 114 | this.y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
|
---|
| 115 |
|
---|
[12290] | 116 | var varEst = new OnlineMeanAndVarianceCalculator();
|
---|
| 117 |
|
---|
| 118 | var means = new double[d];
|
---|
| 119 | var stdDevs = new double[d];
|
---|
| 120 |
|
---|
[11732] | 121 | int i = 0;
|
---|
[12290] | 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;
|
---|
[11732] | 132 | foreach (var r in problemData.TrainingIndices) {
|
---|
| 133 | int j = 0;
|
---|
| 134 | foreach (var inputVariable in problemData.AllowedInputVariables) {
|
---|
[12290] | 135 | x[i, j] = (problemData.Dataset.GetDoubleValue(inputVariable, r) - means[j]) / stdDevs[j];
|
---|
| 136 | j++;
|
---|
[11732] | 137 | }
|
---|
| 138 | i++;
|
---|
| 139 | }
|
---|
[12290] | 140 |
|
---|
| 141 | this.random = random;
|
---|
| 142 | this.lambda = lambda;
|
---|
| 143 |
|
---|
[11832] | 144 | // initialize ERC values
|
---|
| 145 | erc = Enumerable.Range(0, 10).Select(_ => Rand.RandNormal(random) * 10).ToArray();
|
---|
[11732] | 146 |
|
---|
| 147 | char firstVar = 'a';
|
---|
| 148 | char lastVar = Convert.ToChar(Convert.ToByte('a') + d - 1);
|
---|
[11902] | 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 | }
|
---|
[11732] | 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) {
|
---|
[12024] | 169 | var extender = new ExpressionExtender();
|
---|
| 170 | sentence = extender.CanonicalRepresentation(sentence);
|
---|
[11902] | 171 | if (useConstantOpt)
|
---|
| 172 | return OptimizeConstantsAndEvaluate(sentence);
|
---|
| 173 | else {
|
---|
[12014] | 174 | Debug.Assert(SimpleEvaluate(sentence) == SimpleEvaluate(extender.CanonicalRepresentation(sentence)));
|
---|
[11902] | 175 | return SimpleEvaluate(sentence);
|
---|
| 176 | }
|
---|
[11895] | 177 | }
|
---|
| 178 |
|
---|
| 179 | public double SimpleEvaluate(string sentence) {
|
---|
[11832] | 180 | var interpreter = new ExpressionInterpreter();
|
---|
[11895] | 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 | }));
|
---|
[11732] | 186 | }
|
---|
| 187 |
|
---|
| 188 |
|
---|
[11832] | 189 | public string CanonicalRepresentation(string phrase) {
|
---|
[12014] | 190 | var extender = new ExpressionExtender();
|
---|
| 191 | return extender.CanonicalRepresentation(phrase);
|
---|
[11732] | 192 | }
|
---|
[11832] | 193 |
|
---|
[11895] | 194 | public IEnumerable<Feature> GetFeatures(string phrase) {
|
---|
[12290] | 195 | throw new NotImplementedException();
|
---|
| 196 | //phrase = CanonicalRepresentation(phrase);
|
---|
| 197 | //return phrase.Split('+').Distinct().Select(t => new Feature(t, 1.0));
|
---|
[12024] | 198 | // return new Feature[] { new Feature(phrase, 1.0) };
|
---|
[11832] | 199 | }
|
---|
| 200 |
|
---|
| 201 |
|
---|
| 202 |
|
---|
[11895] | 203 | public double OptimizeConstantsAndEvaluate(string sentence) {
|
---|
[11832] | 204 | AutoDiff.Term func;
|
---|
[11972] | 205 | int n = x.GetLength(0);
|
---|
| 206 | int m = x.GetLength(1);
|
---|
[11832] | 207 |
|
---|
[11895] | 208 | var compiler = new ExpressionCompiler();
|
---|
[11972] | 209 | Variable[] variables = Enumerable.Range(0, m).Select(_ => new Variable()).ToArray();
|
---|
[11895] | 210 | Variable[] constants;
|
---|
[11972] | 211 | compiler.Compile(sentence, out func, variables, out constants);
|
---|
[11832] | 212 |
|
---|
[11895] | 213 | // constants are manipulated
|
---|
[11832] | 214 |
|
---|
[11895] | 215 | if (!constants.Any()) return SimpleEvaluate(sentence);
|
---|
[11832] | 216 |
|
---|
[12290] | 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)));
|
---|
[11895] | 220 |
|
---|
[12290] | 221 | AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(constants, variables); // variate constants, leave variables fixed to data
|
---|
[11895] | 222 |
|
---|
[12290] | 223 | // 10 restarts with random starting points
|
---|
| 224 | double[] bestStart = null;
|
---|
| 225 | double bestError = double.PositiveInfinity;
|
---|
| 226 | int info;
|
---|
[11832] | 227 | alglib.lsfitstate state;
|
---|
| 228 | alglib.lsfitreport rep;
|
---|
[12290] | 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
|
---|
[11832] | 235 |
|
---|
[11972] | 236 |
|
---|
[12290] | 237 | int k = cStart.Length;
|
---|
[11832] | 238 |
|
---|
| 239 |
|
---|
[12290] | 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 | }
|
---|
[11832] | 256 | }
|
---|
| 257 |
|
---|
[12290] | 258 | // 100 iteration steps from the best starting point
|
---|
[11895] | 259 | {
|
---|
[12290] | 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 | }
|
---|
[11895] | 285 | }
|
---|
[11832] | 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 |
|
---|
[11895] | 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 |
|
---|
[11972] | 312 |
|
---|
[11895] | 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;
|
---|
[11832] | 327 | }
|
---|
| 328 | }
|
---|
[11895] | 329 | // nonterminal
|
---|
[11902] | 330 | if (treeNode.SubtreeCount > 1) sb.Append("(");
|
---|
[11895] | 331 | TreeToSentence(treeNode.Subtrees.First(), sb);
|
---|
| 332 | foreach (var subTree in treeNode.Subtrees.Skip(1)) {
|
---|
| 333 | sb.Append(op);
|
---|
| 334 | TreeToSentence(subTree, sb);
|
---|
[11832] | 335 | }
|
---|
[11902] | 336 | if (treeNode.SubtreeCount > 1) sb.Append(")");
|
---|
[11832] | 337 | }
|
---|
| 338 | }
|
---|
[11732] | 339 | }
|
---|
| 340 | }
|
---|