Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.SupportVectorMachines/3.2/Predictor.cs @ 2421

Last change on this file since 2421 was 2421, checked in by gkronber, 15 years ago

Fixed bugs related to time series prognosis with SVMs. And fixed an exception when trying to save time-series models to the database. #776 (Error when trying to save time-series prognosis predictors to the database)

File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using System.Xml;
26using System.Linq;
27using HeuristicLab.Core;
28using System.Globalization;
29using System.IO;
30using HeuristicLab.Modeling;
31using SVM;
32using HeuristicLab.DataAnalysis;
33
34namespace HeuristicLab.SupportVectorMachines {
35  public class Predictor : PredictorBase {
36    private SVMModel svmModel;
37    public SVMModel Model {
38      get { return svmModel; }
39    }
40
41    private List<string> variableNames;
42    private string targetVariable;
43    private int minTimeOffset;
44    public int MinTimeOffset {
45      get { return minTimeOffset; }
46    }
47    private int maxTimeOffset;
48    public int MaxTimeOffset {
49      get { return maxTimeOffset; }
50    }
51
52    public Predictor() : base() { } // for persistence
53
54    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames) :
55      this(model, targetVariable, variableNames, 0, 0) {
56    }
57
58    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames, int minTimeOffset, int maxTimeOffset)
59      : base() {
60      this.svmModel = model;
61      this.targetVariable = targetVariable;
62      this.variableNames = new List<string>(variableNames);
63      this.minTimeOffset = minTimeOffset;
64      this.maxTimeOffset = maxTimeOffset;
65    }
66
67    public override double[] Predict(Dataset input, int start, int end) {
68      if (start < 0 || end <= start) throw new ArgumentException("start must be larger than zero and strictly smaller than end");
69      if (end > input.Rows) throw new ArgumentOutOfRangeException("number of rows in input is smaller then end");
70      RangeTransform transform = svmModel.RangeTransform;
71      Model model = svmModel.Model;
72
73      Problem p = SVMHelper.CreateSVMProblem(input, input.GetVariableIndex(targetVariable), variableNames,
74        start, end, minTimeOffset, maxTimeOffset);
75      Problem scaledProblem = transform.Scale(p);
76
77      int targetVariableIndex = input.GetVariableIndex(targetVariable);
78      int rows = end - start;
79      double[] result = new double[rows];
80      int problemRow = 0;
81      for (int resultRow = 0; resultRow < rows; resultRow++) {
82        if (double.IsNaN(input.GetValue(resultRow, targetVariableIndex)))
83          result[resultRow] = UpperPredictionLimit;
84        else if (resultRow + maxTimeOffset < 0) {
85          result[resultRow] = UpperPredictionLimit;
86          problemRow++;
87        } else {
88          result[resultRow] = Math.Max(Math.Min(SVM.Prediction.Predict(model, scaledProblem.X[problemRow++]), UpperPredictionLimit), LowerPredictionLimit);
89        }
90      }
91      return result;
92    }
93
94    public override IEnumerable<string> GetInputVariables() {
95      return variableNames;
96    }
97
98    public override IView CreateView() {
99      return new PredictorView(this);
100    }
101
102    public override object Clone(IDictionary<Guid, object> clonedObjects) {
103      Predictor clone = (Predictor)base.Clone(clonedObjects);
104      clone.svmModel = (SVMModel)Auxiliary.Clone(svmModel, clonedObjects);
105      clone.targetVariable = targetVariable;
106      clone.variableNames = new List<string>(variableNames);
107      clone.minTimeOffset = minTimeOffset;
108      clone.maxTimeOffset = maxTimeOffset;
109      return clone;
110    }
111
112    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
113      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
114      XmlAttribute targetVarAttr = document.CreateAttribute("TargetVariable");
115      targetVarAttr.Value = targetVariable;
116      node.Attributes.Append(targetVarAttr);
117      XmlAttribute minTimeOffsetAttr = document.CreateAttribute("MinTimeOffset");
118      XmlAttribute maxTimeOffsetAttr = document.CreateAttribute("MaxTimeOffset");
119      minTimeOffsetAttr.Value = XmlConvert.ToString(minTimeOffset);
120      maxTimeOffsetAttr.Value = XmlConvert.ToString(maxTimeOffset);
121      node.Attributes.Append(minTimeOffsetAttr);
122      node.Attributes.Append(maxTimeOffsetAttr);
123      node.AppendChild(PersistenceManager.Persist(svmModel, document, persistedObjects));
124      XmlNode variablesNode = document.CreateElement("Variables");
125      foreach (var variableName in variableNames) {
126        XmlNode variableNameNode = document.CreateElement("Variable");
127        XmlAttribute nameAttr = document.CreateAttribute("Name");
128        nameAttr.Value = variableName;
129        variableNameNode.Attributes.Append(nameAttr);
130        variablesNode.AppendChild(variableNameNode);
131      }
132      node.AppendChild(variablesNode);
133      return node;
134    }
135
136    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
137      base.Populate(node, restoredObjects);
138      targetVariable = node.Attributes["TargetVariable"].Value;
139      svmModel = (SVMModel)PersistenceManager.Restore(node.ChildNodes[0], restoredObjects);
140
141      if (node.Attributes["MinTimeOffset"] != null) minTimeOffset = XmlConvert.ToInt32(node.Attributes["MinTimeOffset"].Value);
142      if (node.Attributes["MaxTimeOffset"] != null) maxTimeOffset = XmlConvert.ToInt32(node.Attributes["MaxTimeOffset"].Value);
143      variableNames = new List<string>();
144      XmlNode variablesNode = node.ChildNodes[1];
145      foreach (XmlNode variableNameNode in variablesNode.ChildNodes) {
146        variableNames.Add(variableNameNode.Attributes["Name"].Value);
147      }
148    }
149
150    public static void Export(Predictor p, Stream s) {
151      StreamWriter writer = new StreamWriter(s);
152      writer.Write("Targetvariable: "); writer.WriteLine(p.targetVariable);
153      writer.Write("LowerPredictionLimit: "); writer.WriteLine(p.LowerPredictionLimit.ToString("r", CultureInfo.InvariantCulture.NumberFormat));
154      writer.Write("UpperPredictionLimit: "); writer.WriteLine(p.UpperPredictionLimit.ToString("r", CultureInfo.InvariantCulture.NumberFormat));
155      writer.Write("MaxTimeOffset: "); writer.WriteLine(p.MaxTimeOffset.ToString());
156      writer.Write("MinTimeOffset: "); writer.WriteLine(p.MinTimeOffset.ToString());
157      writer.Write("InputVariables :");
158      writer.Write(p.GetInputVariables().First());
159      foreach (string variable in p.GetInputVariables().Skip(1)) {
160        writer.Write("; "); writer.Write(variable);
161      }
162      writer.WriteLine();
163      writer.Flush();
164      using (MemoryStream memStream = new MemoryStream()) {
165        SVMModel.Export(p.Model, memStream);
166        memStream.WriteTo(s);
167      }
168    }
169
170    public static Predictor Import(TextReader reader) {
171      Predictor p = new Predictor();
172      string[] targetVariableLine = reader.ReadLine().Split(':');
173      string[] lowerPredictionLimitLine = reader.ReadLine().Split(':');
174      string[] upperPredictionLimitLine = reader.ReadLine().Split(':');
175      string[] maxTimeOffsetLine = reader.ReadLine().Split(':');
176      string[] minTimeOffsetLine = reader.ReadLine().Split(':');
177      string[] inputVariableLine = reader.ReadLine().Split(':', ';');
178
179      p.targetVariable = targetVariableLine[1].Trim();
180      p.LowerPredictionLimit = double.Parse(lowerPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
181      p.UpperPredictionLimit = double.Parse(upperPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
182      p.maxTimeOffset = int.Parse(maxTimeOffsetLine[1]);
183      p.minTimeOffset = int.Parse(minTimeOffsetLine[1]);
184      foreach (string inputVariable in inputVariableLine.Skip(1)) {
185        p.variableNames.Add(inputVariable.Trim());
186      }
187      p.svmModel = SVMModel.Import(reader);
188      return p;
189    }
190  }
191}
Note: See TracBrowser for help on using the repository browser.