Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5694 was 5694, checked in by gkronber, 12 years ago

#1418 ported views for support vector machine solutions and models.

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 SVM;
31using HeuristicLab.Problems.DataAnalysis;
32using System.Drawing;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  /// <summary>
36  /// Represents a support vector machine model.
37  /// </summary>
38  [StorableClass]
39  [Item("SupportVectorMachineModel", "Represents a support vector machine model.")]
40  public sealed class SupportVectorMachineModel : NamedItem, ISupportVectorMachineModel, IRegressionModel, IClassificationModel {
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    }
71
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, j] = sv[j].Value;
79          }
80        }
81        return new Dataset(allowedInputVariables, data);
82      }
83    }
84
85    [Storable]
86    private string targetVariable;
87    [Storable]
88    private string[] allowedInputVariables;
89    [Storable]
90    private double[] classValues; // only for SVM classification models
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;
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.