Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis Refactoring/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine/SupportVectorMachineModel.cs @ 5690

Last change on this file since 5690 was 5690, checked in by gkronber, 13 years ago

#1418 removed SupportVectorIndizes field from libSVM models.

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