Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10446 was 5275, checked in by gkronber, 14 years ago

Merged changes from trunk to data analysis exploration branch and added fractional distance metric evaluator. #1142

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