Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/LinearTimeSeriesPrognosis.cs @ 7481

Last change on this file since 7481 was 7120, checked in by gkronber, 13 years ago

#1081 implemented multi-variate symbolic expression tree interpreter for time series prognosis.

File size: 7.3 KB
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
35using HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis;
36
37namespace HeuristicLab.Algorithms.DataAnalysis {
38  /// <summary>
39  /// Linear time series prognosis data analysis algorithm.
40  /// </summary>
41  [Item("Linear Time Series Prognosis", "Linear time series prognosis data analysis algorithm (wrapper for ALGLIB).")]
42  [Creatable("Data Analysis")]
43  [StorableClass]
44  public sealed class LinearTimeSeriesPrognosis : FixedDataAnalysisAlgorithm<ITimeSeriesPrognosisProblem> {
45    private const string LinearTimeSeriesPrognosisModelResultName = "Linear time-series prognosis solution";
46    private const string MaximalLagParameterName = "MaximalLag";
47
48    public IFixedValueParameter<IntValue> MaximalLagParameter {
49      get { return (IFixedValueParameter<IntValue>)Parameters[MaximalLagParameterName]; }
50    }
51
52    public int MaximalLag {
53      get { return MaximalLagParameter.Value.Value; }
54      set { MaximalLagParameter.Value.Value = value; }
55    }
56
57    [StorableConstructor]
58    private LinearTimeSeriesPrognosis(bool deserializing) : base(deserializing) { }
59    private LinearTimeSeriesPrognosis(LinearTimeSeriesPrognosis original, Cloner cloner)
60      : base(original, cloner) {
61    }
62    public LinearTimeSeriesPrognosis()
63      : base() {
64      Parameters.Add(new FixedValueParameter<IntValue>(MaximalLagParameterName,
65                                                       "The maximal lag to use for auto-regressive terms.",
66                                                       new IntValue(1)));
67      Problem = new TimeSeriesPrognosisProblem();
68    }
69    [StorableHook(HookType.AfterDeserialization)]
70    private void AfterDeserialization() { }
71
72    public override IDeepCloneable Clone(Cloner cloner) {
73      return new LinearTimeSeriesPrognosis(this, cloner);
74    }
75
76    #region linear regression
77    protected override void Run() {
78      double[] rmsErrors, cvRmsErrors;
79      var solution = CreateLinearTimeSeriesPrognosisSolution(Problem.ProblemData, MaximalLag, out rmsErrors, out cvRmsErrors);
80      Results.Add(new Result(LinearTimeSeriesPrognosisModelResultName, "The linear time-series prognosis solution.", solution));
81      Results.Add(new Result("Root mean square errors", "The root of the mean of squared errors of the linear time-series prognosis solution on the training set.", new DoubleArray(rmsErrors)));
82      Results.Add(new Result("Estimated root mean square errors (cross-validation)", "The estimated root of the mean of squared errors of the linear time-series prognosis solution via cross validation.", new DoubleArray(cvRmsErrors)));
83    }
84
85    public static ISymbolicTimeSeriesPrognosisSolution CreateLinearTimeSeriesPrognosisSolution(ITimeSeriesPrognosisProblemData problemData, int maximalLag, out double[] rmsError, out double[] cvRmsError) {
86      Dataset dataset = problemData.Dataset;
87      string[] targetVariables = problemData.TargetVariables.ToArray();
88
89      // prepare symbolic expression tree to hold the models for each target variable
90      ISymbolicExpressionTree tree = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
91      ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();
92      tree.Root.AddSubtree(startNode);
93      int i = 0;
94      rmsError = new double[targetVariables.Length];
95      cvRmsError = new double[targetVariables.Length];
96      foreach (var targetVariable in targetVariables) {
97        IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
98        IEnumerable<int> rows = problemData.TrainingIndizes;
99        IEnumerable<int> lags = Enumerable.Range(1, maximalLag);
100        double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset,
101                                                              allowedInputVariables.Concat(new string[] { targetVariable }),
102                                                              rows, lags);
103        if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
104          throw new NotSupportedException(
105            "Linear time-series prognosis does not support NaN or infinity values in the input dataset.");
106
107        alglib.linearmodel lm = new alglib.linearmodel();
108        alglib.lrreport ar = new alglib.lrreport();
109        int nRows = inputMatrix.GetLength(0);
110        int nFeatures = inputMatrix.GetLength(1) - 1;
111        double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
112
113        int retVal = 1;
114        alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
115        if (retVal != 1) throw new ArgumentException("Error in calculation of linear time series prognosis solution");
116        rmsError[i] = ar.rmserror;
117        cvRmsError[i] = ar.cvrmserror;
118
119        alglib.lrunpack(lm, out coefficients, out nFeatures);
120
121        ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();
122
123        int col = 0;
124        foreach (string column in allowedInputVariables) {
125          foreach (int lag in lags) {
126            LaggedVariableTreeNode vNode =
127              (LaggedVariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.LaggedVariable().CreateTreeNode();
128            vNode.VariableName = column;
129            vNode.Weight = coefficients[col];
130            vNode.Lag = -lag;
131            addition.AddSubtree(vNode);
132            col++;
133          }
134        }
135
136        ConstantTreeNode cNode = (ConstantTreeNode)new Constant().CreateTreeNode();
137        cNode.Value = coefficients[coefficients.Length - 1];
138        addition.AddSubtree(cNode);
139
140        startNode.AddSubtree(addition);
141        i++;
142      }
143
144      SymbolicTimeSeriesPrognosisSolution solution = new SymbolicTimeSeriesPrognosisSolution(new SymbolicTimeSeriesPrognosisModel(tree, new SymbolicDataAnalysisExpressionTreeInterpreter(), problemData.TargetVariables.ToArray()), (ITimeSeriesPrognosisProblemData)problemData.Clone());
145      solution.Model.Name = "Linear Time-Series Prognosis Model";
146      return solution;
147    }
148    #endregion
149  }
150}
Note: See TracBrowser for help on using the repository browser.