Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Algorithms.DataAnalysis/3.4/TimeSeries/AutoregressiveModeling.cs @ 8430

Last change on this file since 8430 was 8430, checked in by mkommend, 12 years ago

#1081: Intermediate commit of trunk updates - interpreter changes must be redone.

File size: 6.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.DataAnalysis.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis;
34
35namespace HeuristicLab.Algorithms.DataAnalysis.TimeSeries {
36  [Item("Autoregressive Modeling", "Timeseries modeling algorithm that creates AR-N models.")]
37  [Creatable("Data Analysis")]
38  [StorableClass]
39  public class AutoregressiveModeling : FixedDataAnalysisAlgorithm<ITimeSeriesPrognosisProblem> {
40    private const string TimeOffesetParameterName = "Maximum Time Offset";
41
42    public IFixedValueParameter<IntValue> TimeOffsetParameter {
43      get { return (IFixedValueParameter<IntValue>)Parameters[TimeOffesetParameterName]; }
44    }
45
46
47    public int TimeOffset {
48      get { return TimeOffsetParameter.Value.Value; }
49      set { TimeOffsetParameter.Value.Value = value; }
50    }
51
52    [StorableConstructor]
53    protected AutoregressiveModeling(bool deserializing) : base(deserializing) { }
54    protected AutoregressiveModeling(AutoregressiveModeling original, Cloner cloner) : base(original, cloner) { }
55    public override IDeepCloneable Clone(Cloner cloner) {
56      return new AutoregressiveModeling(this, cloner);
57    }
58
59    public AutoregressiveModeling()
60      : base() {
61      Parameters.Add(new FixedValueParameter<IntValue>(TimeOffesetParameterName, "The maximum time offset for the model ranging from 1 to infinity.", new IntValue(1)));
62      Problem = new TimeSeriesPrognosisProblem();
63    }
64
65    protected override void Run() {
66      double rmsError, cvRmsError;
67      var solution = CreateAutoRegressiveSolution(Problem.ProblemData, TimeOffset, out rmsError, out cvRmsError);
68      Results.Add(new Result("Autoregressive solution", "The autoregressive time series prognosis solution.", solution));
69      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the autoregressive time series prognosis solution on the training set.", new DoubleValue(rmsError)));
70      Results.Add(new Result("Estimated root mean square error (cross-validation)", "The estimated root of the mean of squared errors of the autoregressive time series prognosis solution via cross validation.", new DoubleValue(cvRmsError)));
71    }
72
73    /// <summary>
74    /// Calculates an AR(p) model. For further information see http://en.wikipedia.org/wiki/Autoregressive_model
75    /// </summary>
76    /// <param name="problemData">The problem data which should be used for training</param>
77    /// <param name="timeOffset">The parameter p of the AR(p) specifying the maximum time offset [1,infinity] </param>
78    /// <returns>The times series autoregressive solution </returns>
79    public ITimeSeriesPrognosisSolution CreateAutoRegressiveSolution(ITimeSeriesPrognosisProblemData problemData, int timeOffset) {
80      double rmsError, cvRmsError;
81      return CreateAutoRegressiveSolution(problemData, timeOffset, out rmsError, out cvRmsError);
82    }
83
84    internal ITimeSeriesPrognosisSolution CreateAutoRegressiveSolution(ITimeSeriesPrognosisProblemData problemData, int timeOffset, out double rmsError, out double cvRmsError) {
85      Dataset dataset = problemData.Dataset;
86      string targetVariable = problemData.TargetVariable;
87
88      double[,] inputMatrix = new double[problemData.TrainingPartition.Size, timeOffset + 1];
89      var targetValues = problemData.Dataset.GetReadOnlyDoubleValues(targetVariable);
90      for (int i = 0, row = problemData.TrainingPartition.Start; i < problemData.TrainingPartition.Size; i++, row++) {
91        for (int col = 0; col < timeOffset + 1; col++) {
92          inputMatrix[i, col] = targetValues[row - col];
93        }
94      }
95
96      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
97        throw new NotSupportedException("Linear regression does not support NaN or infinity values in the input dataset.");
98
99
100      alglib.linearmodel lm = new alglib.linearmodel();
101      alglib.lrreport ar = new alglib.lrreport();
102      int nRows = inputMatrix.GetLength(0);
103      int nFeatures = inputMatrix.GetLength(1) - 1;
104      double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
105
106      int retVal = 1;
107      alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
108      if (retVal != 1) throw new ArgumentException("Error in calculation of linear regression solution");
109      rmsError = ar.rmserror;
110      cvRmsError = ar.cvrmserror;
111
112      alglib.lrunpack(lm, out coefficients, out nFeatures);
113
114
115      ISymbolicExpressionTree tree = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
116      ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();
117      tree.Root.AddSubtree(startNode);
118      ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();
119      startNode.AddSubtree(addition);
120
121      for (int i = 0; i < timeOffset; i++) {
122        LaggedVariableTreeNode node = (LaggedVariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.LaggedVariable().CreateTreeNode();
123        node.VariableName = targetVariable;
124        node.Weight = coefficients[i];
125        node.Lag = (i + 1) * -1;
126        addition.AddSubtree(node);
127      }
128
129      ConstantTreeNode cNode = (ConstantTreeNode)new Constant().CreateTreeNode();
130      cNode.Value = coefficients[coefficients.Length - 1];
131      addition.AddSubtree(cNode);
132
133      var interpreter = new SymbolicTimeSeriesPrognosisExpressionTreeInterpreter(problemData.TargetVariable);
134      var model = new SymbolicTimeSeriesPrognosisModel(tree, interpreter);
135      var solution = model.CreateTimeSeriesPrognosisSolution((ITimeSeriesPrognosisProblemData)problemData.Clone());
136      return solution;
137    }
138  }
139}
Note: See TracBrowser for help on using the repository browser.