Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Problems.DataAnalysis/3.3/SupportVectorMachine/SupportVectorMachineModel.cs @ 14927

Last change on this file since 14927 was 5692, checked in by gkronber, 14 years ago

#1426 merged r5690 from data analysis refactoring branch (see #1418) into trunk to fix persistence problems of SVMs.

File size: 6.5 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.IO;
25using System.Linq;
26using System.Text;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using SVM;
31
32namespace HeuristicLab.Problems.DataAnalysis.SupportVectorMachine {
33  /// <summary>
34  /// Represents a support vector machine model.
35  /// </summary>
36  [StorableClass]
37  [Item("SupportVectorMachineModel", "Represents a support vector machine model.")]
38  public sealed class SupportVectorMachineModel : NamedItem, IDataAnalysisModel {
39    private SVM.Model model;
40    /// <summary>
41    /// Gets or sets the SVM model.
42    /// </summary>
43    public SVM.Model Model {
44      get { return model; }
45      set {
46        if (value != model) {
47          if (value == null) throw new ArgumentNullException();
48          model = value;
49          OnChanged(EventArgs.Empty);
50        }
51      }
52    }
53
54    /// <summary>
55    /// Gets or sets the range transformation for the model.
56    /// </summary>
57    private SVM.RangeTransform rangeTransform;
58    public SVM.RangeTransform RangeTransform {
59      get { return rangeTransform; }
60      set {
61        if (value != rangeTransform) {
62          if (value == null) throw new ArgumentNullException();
63          rangeTransform = value;
64          OnChanged(EventArgs.Empty);
65        }
66      }
67    }
68
69    public IEnumerable<double[]> SupportVectors {
70      get {
71        return from sv in Model.SupportVectors
72               select (from svx in sv
73                       select svx.Value).ToArray();
74      }
75    }
76
77    [StorableConstructor]
78    private SupportVectorMachineModel(bool deserializing) : base(deserializing) { }
79    private SupportVectorMachineModel(SupportVectorMachineModel original, Cloner cloner)
80      : base(original, cloner) {
81      // only using a shallow copy here! (gkronber)
82      this.model = original.model;
83      this.rangeTransform = original.rangeTransform;
84    }
85    public SupportVectorMachineModel() : base() { }
86
87    public IEnumerable<double> GetEstimatedValues(DataAnalysisProblemData problemData, int start, int end) {
88      SVM.Problem problem = SupportVectorMachineUtil.CreateSvmProblem(problemData, Enumerable.Range(start, end - start));
89      SVM.Problem scaledProblem = Scaling.Scale(RangeTransform, problem);
90
91      return (from row in Enumerable.Range(0, scaledProblem.Count)
92              select SVM.Prediction.Predict(Model, scaledProblem.X[row]))
93              .ToList();
94    }
95
96    #region events
97    public event EventHandler Changed;
98    private void OnChanged(EventArgs e) {
99      var handlers = Changed;
100      if (handlers != null)
101        handlers(this, e);
102    }
103    #endregion
104
105    #region persistence
106    [Storable]
107    private string ModelAsString {
108      get {
109        using (MemoryStream stream = new MemoryStream()) {
110          SVM.Model.Write(stream, Model);
111          stream.Seek(0, System.IO.SeekOrigin.Begin);
112          StreamReader reader = new StreamReader(stream);
113          return reader.ReadToEnd();
114        }
115      }
116      set {
117        using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
118          model = SVM.Model.Read(stream);
119        }
120      }
121    }
122    [Storable]
123    private string RangeTransformAsString {
124      get {
125        using (MemoryStream stream = new MemoryStream()) {
126          SVM.RangeTransform.Write(stream, RangeTransform);
127          stream.Seek(0, System.IO.SeekOrigin.Begin);
128          StreamReader reader = new StreamReader(stream);
129          return reader.ReadToEnd();
130        }
131      }
132      set {
133        using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
134          RangeTransform = SVM.RangeTransform.Read(stream);
135        }
136      }
137    }
138    #endregion
139
140    public override IDeepCloneable Clone(Cloner cloner) {
141      return new SupportVectorMachineModel(this, cloner);
142    }
143
144    /// <summary>
145    ///  Exports the <paramref name="model"/> in string representation to stream <paramref name="s"/>
146    /// </summary>
147    /// <param name="model">The support vector regression model to export</param>
148    /// <param name="s">The stream to export the model to</param>
149    public static void Export(SupportVectorMachineModel model, Stream s) {
150      StreamWriter writer = new StreamWriter(s);
151      writer.WriteLine("RangeTransform:");
152      writer.Flush();
153      using (MemoryStream memStream = new MemoryStream()) {
154        SVM.RangeTransform.Write(memStream, model.RangeTransform);
155        memStream.Seek(0, SeekOrigin.Begin);
156        memStream.WriteTo(s);
157      }
158      writer.WriteLine("Model:");
159      writer.Flush();
160      using (MemoryStream memStream = new MemoryStream()) {
161        SVM.Model.Write(memStream, model.Model);
162        memStream.Seek(0, SeekOrigin.Begin);
163        memStream.WriteTo(s);
164      }
165      s.Flush();
166    }
167
168    /// <summary>
169    /// Imports a support vector machine model given as string representation.
170    /// </summary>
171    /// <param name="reader">The reader to retrieve the string representation from</param>
172    /// <returns>The imported support vector machine model.</returns>
173    public static SupportVectorMachineModel Import(TextReader reader) {
174      SupportVectorMachineModel model = new SupportVectorMachineModel();
175      while (reader.ReadLine().Trim() != "RangeTransform:") ; // read until line "RangeTransform";
176      model.RangeTransform = SVM.RangeTransform.Read(reader);
177      // read until "Model:"
178      while (reader.ReadLine().Trim() != "Model:") ;
179      model.Model = SVM.Model.Read(reader);
180      return model;
181    }
182  }
183}
Note: See TracBrowser for help on using the repository browser.