Free cookie consent management tool by TermsFeed Policy Generator

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

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

Implemented #834 (IPredictor.Predict() should return an IEnumerable<double> instead of an double[]).

File size: 8.6 KB
RevLine 
[2285]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;
[2413]26using System.Linq;
[2285]27using HeuristicLab.Core;
28using System.Globalization;
29using System.IO;
30using HeuristicLab.Modeling;
31using SVM;
32using HeuristicLab.DataAnalysis;
33
34namespace HeuristicLab.SupportVectorMachines {
[2328]35  public class Predictor : PredictorBase {
[2285]36    private SVMModel svmModel;
[2328]37    public SVMModel Model {
38      get { return svmModel; }
39    }
40
[2421]41    private List<string> variableNames;
[2285]42    private string targetVariable;
[2347]43    private int minTimeOffset;
[2373]44    public int MinTimeOffset {
45      get { return minTimeOffset; }
46    }
[2347]47    private int maxTimeOffset;
[2373]48    public int MaxTimeOffset {
49      get { return maxTimeOffset; }
50    }
[2285]51
[2436]52    // for persistence
53    public Predictor() : base() { }
[2285]54
[2421]55    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames) :
[2347]56      this(model, targetVariable, variableNames, 0, 0) {
57    }
58
[2421]59    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames, int minTimeOffset, int maxTimeOffset)
[2436]60      : this() {
[2285]61      this.svmModel = model;
62      this.targetVariable = targetVariable;
[2347]63      this.minTimeOffset = minTimeOffset;
64      this.maxTimeOffset = maxTimeOffset;
[2436]65      this.variableNames = new List<string>(variableNames);
[2285]66    }
67
[2619]68    public override IEnumerable<double> Predict(Dataset input, int start, int end) {
[2285]69      if (start < 0 || end <= start) throw new ArgumentException("start must be larger than zero and strictly smaller than end");
70      if (end > input.Rows) throw new ArgumentOutOfRangeException("number of rows in input is smaller then end");
71      RangeTransform transform = svmModel.RangeTransform;
72      Model model = svmModel.Model;
73
[2421]74      Problem p = SVMHelper.CreateSVMProblem(input, input.GetVariableIndex(targetVariable), variableNames,
[2347]75        start, end, minTimeOffset, maxTimeOffset);
[2415]76      Problem scaledProblem = transform.Scale(p);
[2285]77
[2412]78      int targetVariableIndex = input.GetVariableIndex(targetVariable);
[2285]79      int rows = end - start;
[2619]80      //double[] result = new double[rows];
[2412]81      int problemRow = 0;
82      for (int resultRow = 0; resultRow < rows; resultRow++) {
83        if (double.IsNaN(input.GetValue(resultRow, targetVariableIndex)))
[2619]84          yield return UpperPredictionLimit;
[2421]85        else if (resultRow + maxTimeOffset < 0) {
86          problemRow++;
[2619]87          yield return UpperPredictionLimit;
[2421]88        } else {
[2619]89          yield return Math.Max(Math.Min(SVM.Prediction.Predict(model, scaledProblem.X[problemRow++]), UpperPredictionLimit), LowerPredictionLimit);
[2421]90        }
[2285]91      }
92    }
93
[2381]94    public override IEnumerable<string> GetInputVariables() {
[2421]95      return variableNames;
[2381]96    }
97
[2285]98    public override IView CreateView() {
[2328]99      return new PredictorView(this);
[2285]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;
[2421]106      clone.variableNames = new List<string>(variableNames);
[2347]107      clone.minTimeOffset = minTimeOffset;
108      clone.maxTimeOffset = maxTimeOffset;
[2285]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);
[2347]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);
[2285]123      node.AppendChild(PersistenceManager.Persist(svmModel, document, persistedObjects));
[2290]124      XmlNode variablesNode = document.CreateElement("Variables");
[2421]125      foreach (var variableName in variableNames) {
126        XmlNode variableNameNode = document.CreateElement("Variable");
[2290]127        XmlAttribute nameAttr = document.CreateAttribute("Name");
[2421]128        nameAttr.Value = variableName;
129        variableNameNode.Attributes.Append(nameAttr);
130        variablesNode.AppendChild(variableNameNode);
[2290]131      }
132      node.AppendChild(variablesNode);
[2285]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);
[2290]140
[2347]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);
[2421]143      variableNames = new List<string>();
[2290]144      XmlNode variablesNode = node.ChildNodes[1];
[2421]145      foreach (XmlNode variableNameNode in variablesNode.ChildNodes) {
146        variableNames.Add(variableNameNode.Attributes["Name"].Value);
[2290]147      }
[2285]148    }
[2415]149
150    public static void Export(Predictor p, Stream s) {
151      StreamWriter writer = new StreamWriter(s);
152      writer.Write("Targetvariable: "); writer.WriteLine(p.targetVariable);
[2418]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));
[2415]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
[2418]170    public static Predictor Import(TextReader reader) {
[2415]171      string[] targetVariableLine = reader.ReadLine().Split(':');
172      string[] lowerPredictionLimitLine = reader.ReadLine().Split(':');
173      string[] upperPredictionLimitLine = reader.ReadLine().Split(':');
174      string[] maxTimeOffsetLine = reader.ReadLine().Split(':');
175      string[] minTimeOffsetLine = reader.ReadLine().Split(':');
176      string[] inputVariableLine = reader.ReadLine().Split(':', ';');
177
[2436]178      string targetVariable = targetVariableLine[1].Trim();
179      double lowerPredictionLimit = double.Parse(lowerPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
180      double upperPredictionLimit = double.Parse(upperPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
181      int maxTimeOffset = int.Parse(maxTimeOffsetLine[1]);
182      int minTimeOffset = int.Parse(minTimeOffsetLine[1]);
183      List<string> variableNames = new List<string>();
[2415]184      foreach (string inputVariable in inputVariableLine.Skip(1)) {
[2436]185        variableNames.Add(inputVariable.Trim());
[2415]186      }
[2436]187      SVMModel model = SVMModel.Import(reader);
188      Predictor p = new Predictor(model, targetVariable, variableNames, minTimeOffset, maxTimeOffset);
189      p.UpperPredictionLimit = upperPredictionLimit;
190      p.LowerPredictionLimit = lowerPredictionLimit;
[2415]191      return p;
192    }
[2285]193  }
194}
Note: See TracBrowser for help on using the repository browser.