Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed a bug in import of SVM predictors. #772 (Text export of SVM models)

File size: 8.6 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    // for persistence
53    public Predictor() : base() { }
54
55    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames) :
56      this(model, targetVariable, variableNames, 0, 0) {
57    }
58
59    public Predictor(SVMModel model, string targetVariable, IEnumerable<string> variableNames, int minTimeOffset, int maxTimeOffset)
60      : this() {
61      this.svmModel = model;
62      this.targetVariable = targetVariable;
63      this.minTimeOffset = minTimeOffset;
64      this.maxTimeOffset = maxTimeOffset;
65      this.variableNames = new List<string>(variableNames);
66    }
67
68    public override double[] Predict(Dataset input, int start, int end) {
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
74      Problem p = SVMHelper.CreateSVMProblem(input, input.GetVariableIndex(targetVariable), variableNames,
75        start, end, minTimeOffset, maxTimeOffset);
76      Problem scaledProblem = transform.Scale(p);
77
78      int targetVariableIndex = input.GetVariableIndex(targetVariable);
79      int rows = end - start;
80      double[] result = new double[rows];
81      int problemRow = 0;
82      for (int resultRow = 0; resultRow < rows; resultRow++) {
83        if (double.IsNaN(input.GetValue(resultRow, targetVariableIndex)))
84          result[resultRow] = UpperPredictionLimit;
85        else if (resultRow + maxTimeOffset < 0) {
86          result[resultRow] = UpperPredictionLimit;
87          problemRow++;
88        } else {
89          result[resultRow] = Math.Max(Math.Min(SVM.Prediction.Predict(model, scaledProblem.X[problemRow++]), UpperPredictionLimit), LowerPredictionLimit);
90        }
91      }
92      return result;
93    }
94
95    public override IEnumerable<string> GetInputVariables() {
96      return variableNames;
97    }
98
99    public override IView CreateView() {
100      return new PredictorView(this);
101    }
102
103    public override object Clone(IDictionary<Guid, object> clonedObjects) {
104      Predictor clone = (Predictor)base.Clone(clonedObjects);
105      clone.svmModel = (SVMModel)Auxiliary.Clone(svmModel, clonedObjects);
106      clone.targetVariable = targetVariable;
107      clone.variableNames = new List<string>(variableNames);
108      clone.minTimeOffset = minTimeOffset;
109      clone.maxTimeOffset = maxTimeOffset;
110      return clone;
111    }
112
113    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
114      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
115      XmlAttribute targetVarAttr = document.CreateAttribute("TargetVariable");
116      targetVarAttr.Value = targetVariable;
117      node.Attributes.Append(targetVarAttr);
118      XmlAttribute minTimeOffsetAttr = document.CreateAttribute("MinTimeOffset");
119      XmlAttribute maxTimeOffsetAttr = document.CreateAttribute("MaxTimeOffset");
120      minTimeOffsetAttr.Value = XmlConvert.ToString(minTimeOffset);
121      maxTimeOffsetAttr.Value = XmlConvert.ToString(maxTimeOffset);
122      node.Attributes.Append(minTimeOffsetAttr);
123      node.Attributes.Append(maxTimeOffsetAttr);
124      node.AppendChild(PersistenceManager.Persist(svmModel, document, persistedObjects));
125      XmlNode variablesNode = document.CreateElement("Variables");
126      foreach (var variableName in variableNames) {
127        XmlNode variableNameNode = document.CreateElement("Variable");
128        XmlAttribute nameAttr = document.CreateAttribute("Name");
129        nameAttr.Value = variableName;
130        variableNameNode.Attributes.Append(nameAttr);
131        variablesNode.AppendChild(variableNameNode);
132      }
133      node.AppendChild(variablesNode);
134      return node;
135    }
136
137    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
138      base.Populate(node, restoredObjects);
139      targetVariable = node.Attributes["TargetVariable"].Value;
140      svmModel = (SVMModel)PersistenceManager.Restore(node.ChildNodes[0], restoredObjects);
141
142      if (node.Attributes["MinTimeOffset"] != null) minTimeOffset = XmlConvert.ToInt32(node.Attributes["MinTimeOffset"].Value);
143      if (node.Attributes["MaxTimeOffset"] != null) maxTimeOffset = XmlConvert.ToInt32(node.Attributes["MaxTimeOffset"].Value);
144      variableNames = new List<string>();
145      XmlNode variablesNode = node.ChildNodes[1];
146      foreach (XmlNode variableNameNode in variablesNode.ChildNodes) {
147        variableNames.Add(variableNameNode.Attributes["Name"].Value);
148      }
149    }
150
151    public static void Export(Predictor p, Stream s) {
152      StreamWriter writer = new StreamWriter(s);
153      writer.Write("Targetvariable: "); writer.WriteLine(p.targetVariable);
154      writer.Write("LowerPredictionLimit: "); writer.WriteLine(p.LowerPredictionLimit.ToString("r", CultureInfo.InvariantCulture.NumberFormat));
155      writer.Write("UpperPredictionLimit: "); writer.WriteLine(p.UpperPredictionLimit.ToString("r", CultureInfo.InvariantCulture.NumberFormat));
156      writer.Write("MaxTimeOffset: "); writer.WriteLine(p.MaxTimeOffset.ToString());
157      writer.Write("MinTimeOffset: "); writer.WriteLine(p.MinTimeOffset.ToString());
158      writer.Write("InputVariables :");
159      writer.Write(p.GetInputVariables().First());
160      foreach (string variable in p.GetInputVariables().Skip(1)) {
161        writer.Write("; "); writer.Write(variable);
162      }
163      writer.WriteLine();
164      writer.Flush();
165      using (MemoryStream memStream = new MemoryStream()) {
166        SVMModel.Export(p.Model, memStream);
167        memStream.WriteTo(s);
168      }
169    }
170
171    public static Predictor Import(TextReader reader) {
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      string targetVariable = targetVariableLine[1].Trim();
180      double lowerPredictionLimit = double.Parse(lowerPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
181      double upperPredictionLimit = double.Parse(upperPredictionLimitLine[1], CultureInfo.InvariantCulture.NumberFormat);
182      int maxTimeOffset = int.Parse(maxTimeOffsetLine[1]);
183      int minTimeOffset = int.Parse(minTimeOffsetLine[1]);
184      List<string> variableNames = new List<string>();
185      foreach (string inputVariable in inputVariableLine.Skip(1)) {
186        variableNames.Add(inputVariable.Trim());
187      }
188      SVMModel model = SVMModel.Import(reader);
189      Predictor p = new Predictor(model, targetVariable, variableNames, minTimeOffset, maxTimeOffset);
190      p.UpperPredictionLimit = upperPredictionLimit;
191      p.LowerPredictionLimit = lowerPredictionLimit;
192      return p;
193    }
194  }
195}
Note: See TracBrowser for help on using the repository browser.