Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis/3.4/SingleObjective/SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator.cs @ 7154

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

#1081: worked on multi-variate time series prognosis

File size: 9.9 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.Drawing.Printing;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic.TimeSeriesPrognosis {
33  [Item("Mean squared error Evaluator", "Calculates the mean squared error of a symbolic time-series prognosis solution.")]
34  [StorableClass]
35  public class SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator : SymbolicTimeSeriesPrognosisSingleObjectiveEvaluator {
36    [StorableConstructor]
37    protected SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator(bool deserializing) : base(deserializing) { }
38    protected SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator(SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator original, Cloner cloner)
39      : base(original, cloner) {
40    }
41    public override IDeepCloneable Clone(Cloner cloner) {
42      return new SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator(this, cloner);
43    }
44
45    public SymbolicTimeSeriesPrognosisSingleObjectiveMeanSquaredErrorEvaluator() : base() { }
46
47    public override bool Maximization { get { return false; } }
48
49    public override IOperation Apply() {
50      var solution = SymbolicExpressionTreeParameter.ActualValue;
51      IEnumerable<int> rows = GenerateRowsToEvaluate();
52
53      double quality = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue,
54        solution,
55        EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper,
56        ProblemDataParameter.ActualValue,
57        rows, HorizonParameter.ActualValue.Value);
58      QualityParameter.ActualValue = new DoubleValue(quality);
59
60      return base.Apply();
61    }
62
63    public static double Calculate(ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, ITimeSeriesPrognosisProblemData problemData, IEnumerable<int> rows, int horizon) {
64      double[] alpha;
65      double[] beta;
66      DetermineScalingFactors(solution, problemData, interpreter, rows, out alpha, out beta);
67      var scaledSolution = Scale(solution, alpha, beta);
68      string[] targetVariables = problemData.TargetVariables.ToArray();
69      var meanSquaredErrorCalculators = Enumerable.Range(0, problemData.TargetVariables.Count())
70        .Select(i => new OnlineMeanSquaredErrorCalculator()).ToArray();
71
72      var allContinuationsEnumerator = interpreter.GetSymbolicExpressionTreeValues(scaledSolution, problemData.Dataset,
73                                                                                  targetVariables,
74                                                                                  rows, horizon).GetEnumerator();
75      allContinuationsEnumerator.MoveNext();
76      // foreach row
77      foreach (var row in rows) {
78        // foreach horizon
79        for (int h = 0; h < horizon; h++) {
80          // foreach component
81          for (int i = 0; i < meanSquaredErrorCalculators.Length; i++) {
82            double e = Math.Min(upperEstimationLimit, Math.Max(lowerEstimationLimit, allContinuationsEnumerator.Current));
83            meanSquaredErrorCalculators[i].Add(problemData.Dataset.GetDoubleValue(targetVariables[i], row + h), e);
84            if (meanSquaredErrorCalculators[i].ErrorState == OnlineCalculatorError.InvalidValueAdded)
85              return double.MaxValue;
86            allContinuationsEnumerator.MoveNext();
87          }
88        }
89      }
90      var meanCalculator = new OnlineMeanAndVarianceCalculator();
91      foreach (var calc in meanSquaredErrorCalculators) {
92        if (calc.ErrorState != OnlineCalculatorError.None) return double.MaxValue;
93        meanCalculator.Add(calc.MeanSquaredError);
94      }
95      //int i = 0;
96      //foreach (var targetVariable in problemData.TargetVariables) {
97      //  var predictedContinuations = allPredictedContinuations.Select(v => v.ElementAt(i));
98      //  for (int h = 0; h < horizon; h++) {
99      //    OnlineCalculatorError errorState;
100      //    meanCalculator.Add(OnlineMeanSquaredErrorCalculator.Calculate(predictedContinuations
101      //                                                                    .Select(x => x.ElementAt(h))
102      //                                                                    .LimitToRange(lowerEstimationLimit,
103      //                                                                                  upperEstimationLimit),
104      //                                                                  actualContinuations.Select(x => x.ElementAt(h)),
105      //                                                                  out errorState));
106      //    if (errorState != OnlineCalculatorError.None) return double.NaN;
107      //  }
108      //}
109      return meanCalculator.MeanErrorState == OnlineCalculatorError.None ? meanCalculator.Mean : double.MaxValue;
110    }
111
112    private static ISymbolicExpressionTree Scale(ISymbolicExpressionTree solution, double[] alpha, double[] beta) {
113      var clone = (ISymbolicExpressionTree)solution.Clone();
114      int n = alpha.Length;
115      for (int i = 0; i < n; i++) {
116        var parent = clone.Root.GetSubtree(0);
117        var rpb = clone.Root.GetSubtree(0).GetSubtree(i);
118        var scaledRpb = MakeSum(
119          MakeProduct(rpb,
120            MakeConstant(beta[i], clone.Root.Grammar), clone.Root.Grammar),
121            MakeConstant(alpha[i], clone.Root.Grammar), clone.Root.Grammar);
122        parent.RemoveSubtree(i);
123        parent.InsertSubtree(i, scaledRpb);
124      }
125      return clone;
126    }
127
128    private static ISymbolicExpressionTreeNode MakeSum(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeGrammar grammar) {
129      var sum = grammar.Symbols.Where(s => s is Addition).First().CreateTreeNode();
130      sum.AddSubtree(a);
131      sum.AddSubtree(b);
132      return sum;
133    }
134
135    private static ISymbolicExpressionTreeNode MakeProduct(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeGrammar grammar) {
136      var prod = grammar.Symbols.Where(s => s is Multiplication).First().CreateTreeNode();
137      prod.AddSubtree(a);
138      prod.AddSubtree(b);
139      return prod;
140    }
141
142    private static ISymbolicExpressionTreeNode MakeConstant(double c, ISymbolicExpressionTreeGrammar grammar) {
143      var node = (ConstantTreeNode)grammar.Symbols.Where(s => s is Constant).First().CreateTreeNode();
144      node.Value = c;
145      return node;
146    }
147
148    private static void DetermineScalingFactors(ISymbolicExpressionTree solution, ITimeSeriesPrognosisProblemData problemData, ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, IEnumerable<int> rows, out double[] alpha, out double[] beta) {
149      string[] targetVariables = problemData.TargetVariables.ToArray();
150      int nComponents = targetVariables.Length;
151      alpha = new double[nComponents];
152      beta = new double[nComponents];
153      var oneStepPredictionsEnumerator = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, targetVariables, rows).GetEnumerator();
154      var scalingParameterCalculators =
155        Enumerable.Repeat(0, nComponents).Select(x => new OnlineLinearScalingParameterCalculator()).ToArray();
156      var targetValues = problemData.Dataset.GetVectorEnumerable(targetVariables, rows);
157      var targetValueEnumerator = targetValues.GetEnumerator();
158
159      var more = oneStepPredictionsEnumerator.MoveNext() & targetValueEnumerator.MoveNext();
160      while (more) {
161        for (int i = 0; i < nComponents; i++) {
162          scalingParameterCalculators[i].Add(oneStepPredictionsEnumerator.Current, targetValueEnumerator.Current);
163          more = oneStepPredictionsEnumerator.MoveNext() & targetValueEnumerator.MoveNext();
164        }
165      }
166
167      for (int i = 0; i < nComponents; i++) {
168        if (scalingParameterCalculators[i].ErrorState == OnlineCalculatorError.None) {
169          alpha[i] = scalingParameterCalculators[i].Alpha;
170          beta[i] = scalingParameterCalculators[i].Beta;
171        } else {
172          alpha[i] = 0.0;
173          beta[i] = 1.0;
174        }
175      }
176    }
177
178    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, ITimeSeriesPrognosisProblemData problemData, IEnumerable<int> rows) {
179      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
180      EstimationLimitsParameter.ExecutionContext = context;
181      HorizonParameter.ExecutionContext = context;
182
183      double mse = Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, HorizonParameter.ActualValue.Value);
184
185      HorizonParameter.ExecutionContext = null;
186      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
187      EstimationLimitsParameter.ExecutionContext = null;
188
189      return mse;
190    }
191  }
192}
Note: See TracBrowser for help on using the repository browser.