Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine/SupportVectorMachineModel.cs @ 5861

Last change on this file since 5861 was 5861, checked in by mkommend, 13 years ago

#1418: Corrected cloning bug in SupportVectorMachineModel.

File size: 7.2 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 HeuristicLab.Problems.DataAnalysis;
31using SVM;
32
33namespace HeuristicLab.Algorithms.DataAnalysis {
34  /// <summary>
35  /// Represents a support vector machine model.
36  /// </summary>
37  [StorableClass]
38  [Item("SupportVectorMachineModel", "Represents a support vector machine model.")]
39  public sealed class SupportVectorMachineModel : NamedItem, ISupportVectorMachineModel {
40
41    private SVM.Model model;
42    /// <summary>
43    /// Gets or sets the SVM model.
44    /// </summary>
45    public SVM.Model Model {
46      get { return model; }
47      set {
48        if (value != model) {
49          if (value == null) throw new ArgumentNullException();
50          model = value;
51          OnChanged(EventArgs.Empty);
52        }
53      }
54    }
55
56    /// <summary>
57    /// Gets or sets the range transformation for the model.
58    /// </summary>
59    private SVM.RangeTransform rangeTransform;
60    public SVM.RangeTransform RangeTransform {
61      get { return rangeTransform; }
62      set {
63        if (value != rangeTransform) {
64          if (value == null) throw new ArgumentNullException();
65          rangeTransform = value;
66          OnChanged(EventArgs.Empty);
67        }
68      }
69    }
70
71    public Dataset SupportVectors {
72      get {
73        var data = new double[Model.SupportVectorCount, allowedInputVariables.Count()];
74        for (int i = 0; i < Model.SupportVectorCount; i++) {
75          var sv = Model.SupportVectors[i];
76          for (int j = 0; j < sv.Length; j++) {
77            data[i, j] = sv[j].Value;
78          }
79        }
80        return new Dataset(allowedInputVariables, data);
81      }
82    }
83
84    [Storable]
85    private string targetVariable;
86    [Storable]
87    private string[] allowedInputVariables;
88    [Storable]
89    private double[] classValues; // only for SVM classification models
90
91    [StorableConstructor]
92    private SupportVectorMachineModel(bool deserializing) : base(deserializing) { }
93    private SupportVectorMachineModel(SupportVectorMachineModel original, Cloner cloner)
94      : base(original, cloner) {
95      // only using a shallow copy here! (gkronber)
96      this.model = original.model;
97      this.rangeTransform = original.rangeTransform;
98      this.targetVariable = original.targetVariable;
99      this.allowedInputVariables = (string[])original.allowedInputVariables.Clone();
100      if (original.classValues != null)
101        this.classValues = (double[])original.classValues.Clone();
102    }
103    public SupportVectorMachineModel(SVM.Model model, SVM.RangeTransform rangeTransform, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<double> classValues)
104      : this(model, rangeTransform, targetVariable, allowedInputVariables) {
105      this.classValues = classValues.ToArray();
106    }
107    public SupportVectorMachineModel(SVM.Model model, SVM.RangeTransform rangeTransform, string targetVariable, IEnumerable<string> allowedInputVariables)
108      : base() {
109      this.name = ItemName;
110      this.description = ItemDescription;
111      this.model = model;
112      this.rangeTransform = rangeTransform;
113      this.targetVariable = targetVariable;
114      this.allowedInputVariables = allowedInputVariables.ToArray();
115    }
116
117    public override IDeepCloneable Clone(Cloner cloner) {
118      return new SupportVectorMachineModel(this, cloner);
119    }
120
121    #region IRegressionModel Members
122    public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
123      return GetEstimatedValuesHelper(dataset, rows);
124    }
125    #endregion
126    #region IClassificationModel Members
127    public IEnumerable<double> GetEstimatedClassValues(Dataset dataset, IEnumerable<int> rows) {
128      if (classValues == null) throw new NotSupportedException();
129      // return the original class value instead of the predicted value of the model
130      // svm classification only works for integer classes
131      foreach (var estimated in GetEstimatedValuesHelper(dataset, rows)) {
132        // find closest class
133        double bestDist = double.MaxValue;
134        double bestClass = -1;
135        for (int i = 0; i < classValues.Length; i++) {
136          double d = Math.Abs(estimated - classValues[i]);
137          if (d < bestDist) {
138            bestDist = d;
139            bestClass = classValues[i];
140            if (d.IsAlmost(0.0)) break; // exact match no need to look further
141          }
142        }
143        yield return bestClass;
144      }
145    }
146    #endregion
147    private IEnumerable<double> GetEstimatedValuesHelper(Dataset dataset, IEnumerable<int> rows) {
148      SVM.Problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, targetVariable, allowedInputVariables, rows);
149      SVM.Problem scaledProblem = Scaling.Scale(RangeTransform, problem);
150
151      foreach (var row in Enumerable.Range(0, scaledProblem.Count)) {
152        yield return SVM.Prediction.Predict(Model, scaledProblem.X[row]);
153      }
154    }
155    #region events
156    public event EventHandler Changed;
157    private void OnChanged(EventArgs e) {
158      var handlers = Changed;
159      if (handlers != null)
160        handlers(this, e);
161    }
162    #endregion
163
164    #region persistence
165    [Storable]
166    private string ModelAsString {
167      get {
168        using (MemoryStream stream = new MemoryStream()) {
169          SVM.Model.Write(stream, Model);
170          stream.Seek(0, System.IO.SeekOrigin.Begin);
171          StreamReader reader = new StreamReader(stream);
172          return reader.ReadToEnd();
173        }
174      }
175      set {
176        using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
177          model = SVM.Model.Read(stream);
178        }
179      }
180    }
181    [Storable]
182    private string RangeTransformAsString {
183      get {
184        using (MemoryStream stream = new MemoryStream()) {
185          SVM.RangeTransform.Write(stream, RangeTransform);
186          stream.Seek(0, System.IO.SeekOrigin.Begin);
187          StreamReader reader = new StreamReader(stream);
188          return reader.ReadToEnd();
189        }
190      }
191      set {
192        using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
193          RangeTransform = SVM.RangeTransform.Read(stream);
194        }
195      }
196    }
197    #endregion
198  }
199}
Note: See TracBrowser for help on using the repository browser.