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