[15765] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
[15712] | 3 | using System.Linq;
|
---|
[15765] | 4 | using System.Text;
|
---|
[15712] | 5 | using System.Threading;
|
---|
| 6 | using HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration.GrammarEnumeration;
|
---|
| 7 | using HeuristicLab.Common;
|
---|
| 8 | using HeuristicLab.Core;
|
---|
| 9 | using HeuristicLab.Data;
|
---|
[15722] | 10 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
[15712] | 11 | using HeuristicLab.Optimization;
|
---|
[15722] | 12 | using HeuristicLab.Parameters;
|
---|
[15712] | 13 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 14 | using HeuristicLab.Problems.DataAnalysis;
|
---|
[15722] | 15 | using HeuristicLab.Problems.DataAnalysis.Symbolic;
|
---|
| 16 | using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
|
---|
[15712] | 17 |
|
---|
| 18 | namespace HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration {
|
---|
| 19 | [Item("Grammar Enumeration Symbolic Regression", "Iterates all possible model structures for a fixed grammar.")]
|
---|
| 20 | [StorableClass]
|
---|
| 21 | [Creatable(CreatableAttribute.Categories.DataAnalysisRegression, Priority = 250)]
|
---|
| 22 | public class GrammarEnumerationAlgorithm : FixedDataAnalysisAlgorithm<IRegressionProblem> {
|
---|
[15746] | 23 | #region properties and result names
|
---|
| 24 | private readonly string BestTrainingQualityName = "Best R² (Training)";
|
---|
| 25 | private readonly string BestTrainingSolutionName = "Best solution (Training)";
|
---|
| 26 | private readonly string GeneratedSentencesName = "Generated Sentences";
|
---|
| 27 | private readonly string DistinctSentencesName = "Distinct Sentences";
|
---|
| 28 | private readonly string PhraseExpansionsName = "Phrase Expansions";
|
---|
| 29 | private readonly string AverageTreeLengthName = "Avg. Sentence Length among Distinct";
|
---|
| 30 | private readonly string GeneratedEqualSentencesName = "Generated equal sentences";
|
---|
[15712] | 31 |
|
---|
[15746] | 32 |
|
---|
| 33 | private readonly string SearchDataStructureParameterName = "Search Data Structure";
|
---|
[15722] | 34 | private readonly string MaxTreeSizeParameterName = "Max. Tree Nodes";
|
---|
| 35 | private readonly string GuiUpdateIntervalParameterName = "GUI Update Interval";
|
---|
[15765] | 36 |
|
---|
[15746] | 37 | public override bool SupportsPause { get { return false; } }
|
---|
[15712] | 38 |
|
---|
[15723] | 39 | protected IValueParameter<IntValue> MaxTreeSizeParameter {
|
---|
[15722] | 40 | get { return (IValueParameter<IntValue>)Parameters[MaxTreeSizeParameterName]; }
|
---|
[15712] | 41 | }
|
---|
[15722] | 42 | public int MaxTreeSize {
|
---|
| 43 | get { return MaxTreeSizeParameter.Value.Value; }
|
---|
[15723] | 44 | set { MaxTreeSizeParameter.Value.Value = value; }
|
---|
[15722] | 45 | }
|
---|
[15712] | 46 |
|
---|
[15723] | 47 | protected IValueParameter<IntValue> GuiUpdateIntervalParameter {
|
---|
| 48 | get { return (IValueParameter<IntValue>)Parameters[GuiUpdateIntervalParameterName]; }
|
---|
[15722] | 49 | }
|
---|
| 50 | public int GuiUpdateInterval {
|
---|
| 51 | get { return GuiUpdateIntervalParameter.Value.Value; }
|
---|
[15723] | 52 | set { GuiUpdateIntervalParameter.Value.Value = value; }
|
---|
[15722] | 53 | }
|
---|
[15712] | 54 |
|
---|
[15746] | 55 | protected IValueParameter<EnumValue<StorageType>> SearchDataStructureParameter {
|
---|
| 56 | get { return (IValueParameter<EnumValue<StorageType>>)Parameters[SearchDataStructureParameterName]; }
|
---|
[15723] | 57 | }
|
---|
[15746] | 58 | public StorageType SearchDataStructure {
|
---|
| 59 | get { return SearchDataStructureParameter.Value.Value; }
|
---|
| 60 | set { SearchDataStructureParameter.Value.Value = value; }
|
---|
[15723] | 61 | }
|
---|
| 62 |
|
---|
[15724] | 63 | public SymbolString BestTrainingSentence;
|
---|
| 64 |
|
---|
[15722] | 65 | #endregion
|
---|
[15712] | 66 |
|
---|
[15746] | 67 | public Dictionary<int, SymbolString> DistinctSentences; // Semantically distinct sentences in a run.
|
---|
| 68 | public Dictionary<int, List<SymbolString>> AllSentences; // All sentences ever generated in a run.
|
---|
| 69 | public Dictionary<int, SymbolString> ArchivedPhrases; // Nodes in the search tree
|
---|
| 70 | SearchDataStore OpenPhrases; // Stack/Queue/etc. for fetching the next node in the search tree.
|
---|
| 71 |
|
---|
| 72 | public int EqualGeneratedSentences; // It is not guaranteed that shorter solutions are found first.
|
---|
| 73 | // When longer solutions are overwritten with shorter ones,
|
---|
| 74 | // this counter is increased.
|
---|
| 75 | public int Expansions; // Number, how many times a nonterminal symbol is replaced with a production rule.
|
---|
[15724] | 76 | public Grammar Grammar;
|
---|
[15712] | 77 |
|
---|
[15765] | 78 | public StringBuilder dotFileBuilder;
|
---|
| 79 |
|
---|
[15722] | 80 | #region ctors
|
---|
| 81 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 82 | return new GrammarEnumerationAlgorithm(this, cloner);
|
---|
| 83 | }
|
---|
[15712] | 84 |
|
---|
[15722] | 85 | public GrammarEnumerationAlgorithm() {
|
---|
[15776] | 86 | var provider = new HeuristicLab.Problems.Instances.DataAnalysis.NguyenInstanceProvider(seed: 1234);
|
---|
| 87 | var regProblem = provider.LoadData(provider.GetDataDescriptors().Single(x => x.Name.Contains("F9 ")));
|
---|
[15723] | 88 |
|
---|
| 89 | Problem = new RegressionProblem() {
|
---|
| 90 | ProblemData = regProblem
|
---|
| 91 | };
|
---|
| 92 |
|
---|
| 93 | Parameters.Add(new ValueParameter<IntValue>(MaxTreeSizeParameterName, "The number of clusters.", new IntValue(6)));
|
---|
[15722] | 94 | Parameters.Add(new ValueParameter<IntValue>(GuiUpdateIntervalParameterName, "Number of generated sentences, until GUI is refreshed.", new IntValue(4000)));
|
---|
[15746] | 95 |
|
---|
[15784] | 96 | Parameters.Add(new ValueParameter<EnumValue<StorageType>>(SearchDataStructureParameterName, new EnumValue<StorageType>(StorageType.Stack)));
|
---|
[15722] | 97 | }
|
---|
[15712] | 98 |
|
---|
[15746] | 99 | public GrammarEnumerationAlgorithm(GrammarEnumerationAlgorithm original, Cloner cloner) : base(original, cloner) { }
|
---|
[15722] | 100 | #endregion
|
---|
[15712] | 101 |
|
---|
[15722] | 102 | protected override void Run(CancellationToken cancellationToken) {
|
---|
[15746] | 103 | #region init
|
---|
| 104 | InitResults();
|
---|
[15723] | 105 |
|
---|
[15765] | 106 | dotFileBuilder = new StringBuilder();
|
---|
| 107 |
|
---|
[15746] | 108 | AllSentences = new Dictionary<int, List<SymbolString>>();
|
---|
| 109 | ArchivedPhrases = new Dictionary<int, SymbolString>(); // Nodes in the search tree
|
---|
| 110 | DistinctSentences = new Dictionary<int, SymbolString>();
|
---|
| 111 | Expansions = 0;
|
---|
| 112 | EqualGeneratedSentences = 0;
|
---|
| 113 |
|
---|
[15724] | 114 | Grammar = new Grammar(Problem.ProblemData.AllowedInputVariables.ToArray());
|
---|
[15712] | 115 |
|
---|
[15746] | 116 | OpenPhrases = new SearchDataStore(SearchDataStructure); // Select search strategy
|
---|
[15734] | 117 | var phrase0 = new SymbolString(new[] { Grammar.StartSymbol });
|
---|
[15746] | 118 | #endregion
|
---|
[15712] | 119 |
|
---|
[15746] | 120 | OpenPhrases.Store(Grammar.CalcHashCode(phrase0), phrase0);
|
---|
| 121 |
|
---|
| 122 | while (OpenPhrases.Count > 0) {
|
---|
[15722] | 123 | if (cancellationToken.IsCancellationRequested) break;
|
---|
| 124 |
|
---|
[15746] | 125 | StoredSymbolString fetchedPhrase = OpenPhrases.GetNext();
|
---|
| 126 | SymbolString currPhrase = fetchedPhrase.SymbolString;
|
---|
[15712] | 127 |
|
---|
[15765] | 128 | if (dotFileBuilder.Length == 0) {
|
---|
| 129 | dotFileBuilder.AppendLine("digraph searchgraph {");
|
---|
| 130 | dotFileBuilder.AppendLine(fetchedPhrase.Hash + " [label=\"" + Grammar.PostfixToInfixParser(fetchedPhrase.SymbolString) + "\", shape=doublecircle];");
|
---|
| 131 | } else {
|
---|
| 132 | dotFileBuilder.AppendLine(fetchedPhrase.Hash + " [label=\"" + Grammar.PostfixToInfixParser(fetchedPhrase.SymbolString) + "\"];");
|
---|
| 133 | }
|
---|
| 134 |
|
---|
[15746] | 135 | ArchivedPhrases.Add(fetchedPhrase.Hash, currPhrase);
|
---|
[15712] | 136 |
|
---|
[15746] | 137 | // expand next nonterminal symbols
|
---|
| 138 | int nonterminalSymbolIndex = currPhrase.FindIndex(s => s is NonterminalSymbol);
|
---|
| 139 | NonterminalSymbol expandedSymbol = currPhrase[nonterminalSymbolIndex] as NonterminalSymbol;
|
---|
[15726] | 140 |
|
---|
[15746] | 141 | foreach (Production productionAlternative in expandedSymbol.Alternatives) {
|
---|
| 142 | SymbolString newPhrase = new SymbolString(currPhrase);
|
---|
| 143 | newPhrase.RemoveAt(nonterminalSymbolIndex);
|
---|
| 144 | newPhrase.InsertRange(nonterminalSymbolIndex, productionAlternative);
|
---|
[15734] | 145 |
|
---|
[15746] | 146 | Expansions++;
|
---|
| 147 | if (newPhrase.Count <= MaxTreeSize) {
|
---|
| 148 | var phraseHash = Grammar.CalcHashCode(newPhrase);
|
---|
[15734] | 149 |
|
---|
[15765] | 150 | dotFileBuilder.AppendLine(fetchedPhrase.Hash + " -> " + phraseHash + " [label=\"" + expandedSymbol.StringRepresentation + "→" + productionAlternative + "\"];");
|
---|
| 151 |
|
---|
[15746] | 152 | if (newPhrase.IsSentence()) { // Sentence was generated.
|
---|
| 153 | SaveToAllSentences(phraseHash, newPhrase);
|
---|
[15734] | 154 |
|
---|
[15746] | 155 | if (!DistinctSentences.ContainsKey(phraseHash) || DistinctSentences[phraseHash].Count > newPhrase.Count) {
|
---|
| 156 | if (DistinctSentences.ContainsKey(phraseHash)) EqualGeneratedSentences++; // for analysis only
|
---|
[15712] | 157 |
|
---|
[15746] | 158 | DistinctSentences[phraseHash] = newPhrase;
|
---|
| 159 | EvaluateSentence(newPhrase);
|
---|
[15765] | 160 |
|
---|
| 161 | dotFileBuilder.AppendLine(phraseHash + " [label=\"" + Grammar.PostfixToInfixParser(newPhrase) + "\", style=\"filled\"];");
|
---|
[15746] | 162 | }
|
---|
| 163 | UpdateView(AllSentences, DistinctSentences, Expansions);
|
---|
[15712] | 164 |
|
---|
[15746] | 165 | } else if (!OpenPhrases.Contains(phraseHash) && !ArchivedPhrases.ContainsKey(phraseHash)) {
|
---|
| 166 | OpenPhrases.Store(phraseHash, newPhrase);
|
---|
[15712] | 167 | }
|
---|
| 168 | }
|
---|
| 169 | }
|
---|
| 170 | }
|
---|
| 171 |
|
---|
[15765] | 172 | dotFileBuilder.AppendLine(Grammar.CalcHashCode(BestTrainingSentence) + " [label=\"" + Grammar.PostfixToInfixParser(BestTrainingSentence) + "\", shape=Mcircle, style=\"filled,bold\"];");
|
---|
| 173 | dotFileBuilder.AppendLine("}");
|
---|
| 174 |
|
---|
| 175 | System.IO.File.WriteAllText(Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory)+ @"\searchgraph.dot", dotFileBuilder.ToString());
|
---|
| 176 |
|
---|
[15746] | 177 | UpdateView(AllSentences, DistinctSentences, Expansions, force: true);
|
---|
| 178 | UpdateFinalResults();
|
---|
| 179 | }
|
---|
[15723] | 180 |
|
---|
[15746] | 181 | // Store sentence to "MultiDictionary"
|
---|
| 182 | private void SaveToAllSentences(int hash, SymbolString sentence) {
|
---|
| 183 | if (AllSentences.ContainsKey(hash))
|
---|
| 184 | AllSentences[hash].Add(sentence);
|
---|
| 185 | else
|
---|
| 186 | AllSentences[hash] = new List<SymbolString> { sentence };
|
---|
[15722] | 187 | }
|
---|
[15712] | 188 |
|
---|
[15746] | 189 | #region Evaluation of generated models.
|
---|
[15712] | 190 |
|
---|
[15746] | 191 | // Evaluate sentence within an algorithm run.
|
---|
[15722] | 192 | private void EvaluateSentence(SymbolString symbolString) {
|
---|
[15724] | 193 | SymbolicExpressionTree tree = Grammar.ParseSymbolicExpressionTree(symbolString);
|
---|
[15712] | 194 | SymbolicRegressionModel model = new SymbolicRegressionModel(
|
---|
| 195 | Problem.ProblemData.TargetVariable,
|
---|
| 196 | tree,
|
---|
| 197 | new SymbolicDataAnalysisExpressionTreeLinearInterpreter());
|
---|
[15746] | 198 |
|
---|
[15734] | 199 | var probData = Problem.ProblemData;
|
---|
| 200 | var target = probData.TargetVariableTrainingValues;
|
---|
| 201 | var estVals = model.GetEstimatedValues(probData.Dataset, probData.TrainingIndices);
|
---|
| 202 | OnlineCalculatorError error;
|
---|
| 203 | var r2 = OnlinePearsonsRSquaredCalculator.Calculate(target, estVals, out error);
|
---|
| 204 | if (error != OnlineCalculatorError.None) r2 = 0.0;
|
---|
[15712] | 205 |
|
---|
[15746] | 206 | var bestR2 = ((DoubleValue)Results[BestTrainingQualityName].Value).Value;
|
---|
| 207 | if (r2 > bestR2) {
|
---|
| 208 | ((DoubleValue)Results[BestTrainingQualityName].Value).Value = r2;
|
---|
| 209 | BestTrainingSentence = symbolString;
|
---|
| 210 | }
|
---|
| 211 | }
|
---|
[15712] | 212 |
|
---|
[15746] | 213 | #endregion
|
---|
| 214 |
|
---|
| 215 | #region Visualization in HL
|
---|
| 216 | // Initialize entries in result set.
|
---|
| 217 | private void InitResults() {
|
---|
| 218 | BestTrainingSentence = null;
|
---|
| 219 |
|
---|
| 220 | Results.Add(new Result(BestTrainingQualityName, new DoubleValue(-1.0)));
|
---|
| 221 |
|
---|
| 222 | Results.Add(new Result(GeneratedSentencesName, new IntValue(0)));
|
---|
| 223 | Results.Add(new Result(DistinctSentencesName, new IntValue(0)));
|
---|
| 224 | Results.Add(new Result(PhraseExpansionsName, new IntValue(0)));
|
---|
| 225 | Results.Add(new Result(GeneratedEqualSentencesName, new IntValue(0)));
|
---|
| 226 | Results.Add(new Result(AverageTreeLengthName, new DoubleValue(1.0)));
|
---|
[15712] | 227 | }
|
---|
[15746] | 228 |
|
---|
| 229 | // Update the view for intermediate results in an algorithm run.
|
---|
| 230 | private int updates;
|
---|
| 231 | private void UpdateView(Dictionary<int, List<SymbolString>> allGenerated,
|
---|
| 232 | Dictionary<int, SymbolString> distinctGenerated, int expansions, bool force = false) {
|
---|
| 233 | updates++;
|
---|
| 234 |
|
---|
| 235 | if (force || updates % GuiUpdateInterval == 0) {
|
---|
| 236 | var allGeneratedEnum = allGenerated.Values.SelectMany(x => x).ToArray();
|
---|
| 237 | ((IntValue)Results[GeneratedSentencesName].Value).Value = allGeneratedEnum.Length;
|
---|
| 238 | ((IntValue)Results[DistinctSentencesName].Value).Value = distinctGenerated.Count;
|
---|
| 239 | ((IntValue)Results[PhraseExpansionsName].Value).Value = expansions;
|
---|
| 240 | ((IntValue)Results[GeneratedEqualSentencesName].Value).Value = EqualGeneratedSentences;
|
---|
| 241 | ((DoubleValue)Results[AverageTreeLengthName].Value).Value = allGeneratedEnum.Select(sentence => sentence.Count).Average();
|
---|
| 242 | }
|
---|
| 243 | }
|
---|
| 244 |
|
---|
| 245 | // Generate all Results after an algorithm run.
|
---|
| 246 | private void UpdateFinalResults() {
|
---|
| 247 | SymbolicExpressionTree tree = Grammar.ParseSymbolicExpressionTree(BestTrainingSentence);
|
---|
| 248 | SymbolicRegressionModel model = new SymbolicRegressionModel(
|
---|
| 249 | Problem.ProblemData.TargetVariable,
|
---|
| 250 | tree,
|
---|
| 251 | new SymbolicDataAnalysisExpressionTreeLinearInterpreter());
|
---|
| 252 |
|
---|
| 253 | IRegressionSolution bestTrainingSolution = new RegressionSolution(model, Problem.ProblemData);
|
---|
| 254 | Results.AddOrUpdateResult(BestTrainingSolutionName, bestTrainingSolution);
|
---|
| 255 |
|
---|
| 256 | // Print generated sentences.
|
---|
| 257 | string[,] sentencesMatrix = new string[AllSentences.Values.SelectMany(x => x).Count(), 3];
|
---|
| 258 |
|
---|
| 259 | int i = 0;
|
---|
| 260 | foreach (var sentenceSet in AllSentences) {
|
---|
| 261 | foreach (var sentence in sentenceSet.Value) {
|
---|
| 262 | sentencesMatrix[i, 0] = sentence.ToString();
|
---|
| 263 | sentencesMatrix[i, 1] = Grammar.PostfixToInfixParser(sentence).ToString();
|
---|
| 264 | sentencesMatrix[i, 2] = sentenceSet.Key.ToString();
|
---|
| 265 | i++;
|
---|
| 266 | }
|
---|
| 267 | }
|
---|
| 268 | Results.Add(new Result("All generated sentences", new StringMatrix(sentencesMatrix)));
|
---|
| 269 |
|
---|
| 270 | string[,] distinctSentencesMatrix = new string[DistinctSentences.Count, 3];
|
---|
| 271 | i = 0;
|
---|
| 272 | foreach (KeyValuePair<int, SymbolString> distinctSentence in DistinctSentences) {
|
---|
| 273 | distinctSentencesMatrix[i, 0] = distinctSentence.Key.ToString();
|
---|
| 274 | distinctSentencesMatrix[i, 1] = Grammar.PostfixToInfixParser(distinctSentence.Value).ToString();
|
---|
| 275 | distinctSentencesMatrix[i, 2] = distinctSentence.Key.ToString();
|
---|
| 276 | i++;
|
---|
| 277 | }
|
---|
| 278 | Results.Add(new Result("Distinct generated sentences", new StringMatrix(distinctSentencesMatrix)));
|
---|
| 279 | }
|
---|
| 280 | #endregion
|
---|
[15765] | 281 |
|
---|
[15712] | 282 | }
|
---|
| 283 | } |
---|