Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed bugs in text export/import of SVM models. #772.

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