Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/SymbolicTimeSeriesPrognosisModel.cs @ 7843

Last change on this file since 7843 was 7183, checked in by gkronber, 13 years ago

#1081 implemented remaining metrics for time series prognosis solutions, added estimation limits fixed training and validation best solution analyzers, implemented overfitting analyzer.

File size: 9.1 KB
RevLine 
[6802]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
[7154]22using System;
[6802]23using System.Collections.Generic;
[7120]24using System.Drawing;
[7100]25using System.Linq;
[6802]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis {
32  /// <summary>
33  /// Represents a symbolic time-series prognosis model
34  /// </summary>
35  [StorableClass]
36  [Item(Name = "Symbolic Time-Series Prognosis Model", Description = "Represents a symbolic time series prognosis model.")]
[7120]37  public class SymbolicTimeSeriesPrognosisModel : NamedItem, ISymbolicTimeSeriesPrognosisModel {
38    public override Image ItemImage {
39      get { return HeuristicLab.Common.Resources.VSImageLibrary.Function; }
[7100]40    }
[7183]41    [Storable(DefaultValue = double.MinValue)]
42    private double lowerEstimationLimit;
43    [Storable(DefaultValue = double.MaxValue)]
44    private double upperEstimationLimit;
[6802]45
[7120]46    #region properties
47
48    [Storable]
49    private ISymbolicExpressionTree symbolicExpressionTree;
50    public ISymbolicExpressionTree SymbolicExpressionTree {
51      get { return symbolicExpressionTree; }
52    }
53
54    [Storable]
55    private ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter;
56    public ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter Interpreter {
57      get { return interpreter; }
58    }
59
[7129]60    ISymbolicDataAnalysisExpressionTreeInterpreter ISymbolicDataAnalysisModel.Interpreter {
61      get { return (ISymbolicDataAnalysisExpressionTreeInterpreter)interpreter; }
62    }
63
[7120]64    #endregion
65
66    [Storable]
67    private string[] targetVariables;
68
69
[6802]70    [StorableConstructor]
71    protected SymbolicTimeSeriesPrognosisModel(bool deserializing) : base(deserializing) { }
72    protected SymbolicTimeSeriesPrognosisModel(SymbolicTimeSeriesPrognosisModel original, Cloner cloner)
73      : base(original, cloner) {
[7120]74      this.symbolicExpressionTree = cloner.Clone(original.symbolicExpressionTree);
75      this.interpreter = cloner.Clone(original.interpreter);
[7154]76      this.targetVariables = new string[original.targetVariables.Length];
77      Array.Copy(original.targetVariables, this.targetVariables, this.targetVariables.Length);
[7183]78      this.lowerEstimationLimit = original.lowerEstimationLimit;
79      this.upperEstimationLimit = original.upperEstimationLimit;
[6802]80    }
[7183]81    public SymbolicTimeSeriesPrognosisModel(ISymbolicExpressionTree tree, ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, IEnumerable<string> targetVariables, double lowerLimit = double.MinValue, double upperLimit = double.MaxValue)
[7120]82      : base() {
83      this.name = ItemName;
84      this.description = ItemDescription;
85      this.symbolicExpressionTree = tree;
86      this.interpreter = interpreter; this.targetVariables = targetVariables.ToArray();
[7183]87      this.lowerEstimationLimit = lowerLimit;
88      this.upperEstimationLimit = upperLimit;
[6802]89    }
90
91    public override IDeepCloneable Clone(Cloner cloner) {
92      return new SymbolicTimeSeriesPrognosisModel(this, cloner);
93    }
94
[7100]95    public IEnumerable<IEnumerable<IEnumerable<double>>> GetPrognosedValues(Dataset dataset, IEnumerable<int> rows, int horizon) {
[7154]96      var enumerator =
97        Interpreter.GetSymbolicExpressionTreeValues(SymbolicExpressionTree, dataset, targetVariables, rows, horizon).
98          GetEnumerator();
99      foreach (var r in rows) {
100        var l = new List<double[]>();
101        for (int h = 0; h < horizon; h++) {
102          double[] components = new double[targetVariables.Length];
103          for (int c = 0; c < components.Length; c++) {
104            enumerator.MoveNext();
[7183]105            components[c] = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, enumerator.Current));
[7154]106          }
107          l.Add(components);
108        }
109        yield return l;
110      }
[6802]111    }
112
113    public ISymbolicTimeSeriesPrognosisSolution CreateTimeSeriesPrognosisSolution(ITimeSeriesPrognosisProblemData problemData) {
114      return new SymbolicTimeSeriesPrognosisSolution(this, problemData);
115    }
116    ITimeSeriesPrognosisSolution ITimeSeriesPrognosisModel.CreateTimeSeriesPrognosisSolution(ITimeSeriesPrognosisProblemData problemData) {
117      return CreateTimeSeriesPrognosisSolution(problemData);
118    }
119
120    public static void Scale(SymbolicTimeSeriesPrognosisModel model, ITimeSeriesPrognosisProblemData problemData) {
121      var dataset = problemData.Dataset;
[7154]122      var targetVariables = problemData.TargetVariables.ToArray();
[6802]123      var rows = problemData.TrainingIndizes;
[7154]124      var estimatedValuesEnumerator = model.Interpreter.GetSymbolicExpressionTreeValues(model.SymbolicExpressionTree, dataset,
125                                                                              targetVariables,
126                                                                              rows).GetEnumerator();
127      var scalingParameterCalculators =
128        problemData.TargetVariables.Select(v => new OnlineLinearScalingParameterCalculator()).ToArray();
129      var targetValuesEnumerator = problemData.Dataset.GetVectorEnumerable(targetVariables, rows).GetEnumerator();
[6802]130
[7154]131      var more = targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext();
132      // foreach row
133      while (more) {
134        // foreach component
135        for (int i = 0; i < targetVariables.Length; i++) {
136          scalingParameterCalculators[i].Add(estimatedValuesEnumerator.Current, targetValuesEnumerator.Current);
137          more = estimatedValuesEnumerator.MoveNext() & targetValuesEnumerator.MoveNext();
138        }
139      }
140
141      for (int i = 0; i < targetVariables.Count(); i++) {
142        if (scalingParameterCalculators[i].ErrorState != OnlineCalculatorError.None) continue;
143        double alpha = scalingParameterCalculators[i].Alpha;
144        double beta = scalingParameterCalculators[i].Beta;
[7100]145        ConstantTreeNode alphaTreeNode = null;
146        ConstantTreeNode betaTreeNode = null;
147        // check if model has been scaled previously by analyzing the structure of the tree
148        var startNode = model.SymbolicExpressionTree.Root.GetSubtree(0);
149        if (startNode.GetSubtree(i).Symbol is Addition) {
150          var addNode = startNode.GetSubtree(i);
151          if (addNode.SubtreeCount == 2 && addNode.GetSubtree(0).Symbol is Multiplication &&
152              addNode.GetSubtree(1).Symbol is Constant) {
153            alphaTreeNode = addNode.GetSubtree(1) as ConstantTreeNode;
154            var mulNode = addNode.GetSubtree(0);
155            if (mulNode.SubtreeCount == 2 && mulNode.GetSubtree(1).Symbol is Constant) {
156              betaTreeNode = mulNode.GetSubtree(1) as ConstantTreeNode;
157            }
[6802]158          }
159        }
[7100]160        // if tree structure matches the structure necessary for linear scaling then reuse the existing tree nodes
161        if (alphaTreeNode != null && betaTreeNode != null) {
162          betaTreeNode.Value *= beta;
163          alphaTreeNode.Value *= beta;
164          alphaTreeNode.Value += alpha;
165        } else {
166          var mainBranch = startNode.GetSubtree(i);
167          startNode.RemoveSubtree(i);
168          var scaledMainBranch = MakeSum(MakeProduct(mainBranch, beta), alpha);
169          startNode.InsertSubtree(i, scaledMainBranch);
170        }
171      } // foreach
[6802]172    }
173
174    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode treeNode, double alpha) {
175      if (alpha.IsAlmost(0.0)) {
176        return treeNode;
177      } else {
178        var addition = new Addition();
179        var node = addition.CreateTreeNode();
180        var alphaConst = MakeConstant(alpha);
181        node.AddSubtree(treeNode);
182        node.AddSubtree(alphaConst);
183        return node;
184      }
185    }
186
187    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode treeNode, double beta) {
188      if (beta.IsAlmost(1.0)) {
189        return treeNode;
190      } else {
191        var multipliciation = new Multiplication();
192        var node = multipliciation.CreateTreeNode();
193        var betaConst = MakeConstant(beta);
194        node.AddSubtree(treeNode);
195        node.AddSubtree(betaConst);
196        return node;
197      }
198    }
199
200    private static ISymbolicExpressionTreeNode MakeConstant(double c) {
201      var node = (ConstantTreeNode)(new Constant()).CreateTreeNode();
202      node.Value = c;
203      return node;
204    }
205  }
206}
Note: See TracBrowser for help on using the repository browser.