Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7099 was 7099, checked in by gkronber, 12 years ago

#1081: merged old changesets r6802, r6807:6808, r6811, r6974, r7058 from the trunk into the TimeSeries branch to bring it to version r7096.

File size: 6.8 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 rmsError, cvRmsError;
79      var solution = CreateLinearTimeSeriesPrognosisSolution(Problem.ProblemData, MaximalLag, out rmsError, out cvRmsError);
80      Results.Add(new Result(LinearTimeSeriesPrognosisModelResultName, "The linear time-series prognosis solution.", solution));
81      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the linear time-series prognosis solution on the training set.", new DoubleValue(rmsError)));
82      Results.Add(new Result("Estimated root mean square error (cross-validation)", "The estimated root of the mean of squared errors of the linear time-series prognosis solution via cross validation.", new DoubleValue(cvRmsError)));
83    }
84
85    public static ISymbolicTimeSeriesPrognosisSolution CreateLinearTimeSeriesPrognosisSolution(ITimeSeriesPrognosisProblemData problemData, int maximalLag, out double rmsError, out double cvRmsError) {
86      Dataset dataset = problemData.Dataset;
87      string targetVariable = problemData.TargetVariable;
88      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
89      IEnumerable<int> rows = problemData.TrainingIndizes;
90      IEnumerable<int> lags = Enumerable.Range(1, maximalLag);
91      double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows, lags);
92      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
93        throw new NotSupportedException("Linear time-series prognosis does not support NaN or infinity values in the input dataset.");
94
95      alglib.linearmodel lm = new alglib.linearmodel();
96      alglib.lrreport ar = new alglib.lrreport();
97      int nRows = inputMatrix.GetLength(0);
98      int nFeatures = inputMatrix.GetLength(1) - 1;
99      double[] coefficients = new double[nFeatures + 1]; // last coefficient is for the constant
100
101      int retVal = 1;
102      alglib.lrbuild(inputMatrix, nRows, nFeatures, out retVal, out lm, out ar);
103      if (retVal != 1) throw new ArgumentException("Error in calculation of linear time series prognosis solution");
104      rmsError = ar.rmserror;
105      cvRmsError = ar.cvrmserror;
106
107      alglib.lrunpack(lm, out coefficients, out nFeatures);
108
109      ISymbolicExpressionTree tree = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
110      ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();
111      tree.Root.AddSubtree(startNode);
112      ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();
113      startNode.AddSubtree(addition);
114
115      int col = 0;
116      foreach (string column in allowedInputVariables) {
117        foreach (int lag in lags) {
118          LaggedVariableTreeNode vNode =
119            (LaggedVariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.LaggedVariable().CreateTreeNode();
120          vNode.VariableName = column;
121          vNode.Weight = coefficients[col];
122          vNode.Lag = -lag;
123          addition.AddSubtree(vNode);
124          col++;
125        }
126      }
127
128      ConstantTreeNode cNode = (ConstantTreeNode)new Constant().CreateTreeNode();
129      cNode.Value = coefficients[coefficients.Length - 1];
130      addition.AddSubtree(cNode);
131
132      SymbolicTimeSeriesPrognosisSolution solution = new SymbolicTimeSeriesPrognosisSolution(new SymbolicTimeSeriesPrognosisModel(tree, new SymbolicDataAnalysisExpressionTreeInterpreter()), (ITimeSeriesPrognosisProblemData)problemData.Clone());
133      solution.Model.Name = "Linear Time-Series Prognosis Model";
134      return solution;
135    }
136    #endregion
137  }
138}
Note: See TracBrowser for help on using the repository browser.