Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine/SupportVectorClassification.cs @ 10878

Last change on this file since 10878 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 9.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using LibSVM;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  /// <summary>
36  /// Support vector machine classification data analysis algorithm.
37  /// </summary>
38  [Item("Support Vector Classification", "Support vector machine classification data analysis algorithm (wrapper for libSVM).")]
39  [Creatable("Data Analysis")]
40  [StorableClass]
41  public sealed class SupportVectorClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
42    private const string SvmTypeParameterName = "SvmType";
43    private const string KernelTypeParameterName = "KernelType";
44    private const string CostParameterName = "Cost";
45    private const string NuParameterName = "Nu";
46    private const string GammaParameterName = "Gamma";
47    private const string DegreeParameterName = "Degree";
48
49    #region parameter properties
50    public IConstrainedValueParameter<StringValue> SvmTypeParameter {
51      get { return (IConstrainedValueParameter<StringValue>)Parameters[SvmTypeParameterName]; }
52    }
53    public IConstrainedValueParameter<StringValue> KernelTypeParameter {
54      get { return (IConstrainedValueParameter<StringValue>)Parameters[KernelTypeParameterName]; }
55    }
56    public IValueParameter<DoubleValue> NuParameter {
57      get { return (IValueParameter<DoubleValue>)Parameters[NuParameterName]; }
58    }
59    public IValueParameter<DoubleValue> CostParameter {
60      get { return (IValueParameter<DoubleValue>)Parameters[CostParameterName]; }
61    }
62    public IValueParameter<DoubleValue> GammaParameter {
63      get { return (IValueParameter<DoubleValue>)Parameters[GammaParameterName]; }
64    }
65    public IValueParameter<IntValue> DegreeParameter {
66      get { return (IValueParameter<IntValue>)Parameters[DegreeParameterName]; }
67    }
68    #endregion
69    #region properties
70    public StringValue SvmType {
71      get { return SvmTypeParameter.Value; }
72      set { SvmTypeParameter.Value = value; }
73    }
74    public StringValue KernelType {
75      get { return KernelTypeParameter.Value; }
76      set { KernelTypeParameter.Value = value; }
77    }
78    public DoubleValue Nu {
79      get { return NuParameter.Value; }
80    }
81    public DoubleValue Cost {
82      get { return CostParameter.Value; }
83    }
84    public DoubleValue Gamma {
85      get { return GammaParameter.Value; }
86    }
87    public IntValue Degree {
88      get { return DegreeParameter.Value; }
89    }
90    #endregion
91    [StorableConstructor]
92    private SupportVectorClassification(bool deserializing) : base(deserializing) { }
93    private SupportVectorClassification(SupportVectorClassification original, Cloner cloner)
94      : base(original, cloner) {
95    }
96    public SupportVectorClassification()
97      : base() {
98      Problem = new ClassificationProblem();
99
100      List<StringValue> svrTypes = (from type in new List<string> { "NU_SVC", "C_SVC" }
101                                    select new StringValue(type).AsReadOnly())
102                                   .ToList();
103      ItemSet<StringValue> svrTypeSet = new ItemSet<StringValue>(svrTypes);
104      List<StringValue> kernelTypes = (from type in new List<string> { "LINEAR", "POLY", "SIGMOID", "RBF" }
105                                       select new StringValue(type).AsReadOnly())
106                                   .ToList();
107      ItemSet<StringValue> kernelTypeSet = new ItemSet<StringValue>(kernelTypes);
108      Parameters.Add(new ConstrainedValueParameter<StringValue>(SvmTypeParameterName, "The type of SVM to use.", svrTypeSet, svrTypes[0]));
109      Parameters.Add(new ConstrainedValueParameter<StringValue>(KernelTypeParameterName, "The kernel type to use for the SVM.", kernelTypeSet, kernelTypes[3]));
110      Parameters.Add(new ValueParameter<DoubleValue>(NuParameterName, "The value of the nu parameter nu-SVC.", new DoubleValue(0.5)));
111      Parameters.Add(new ValueParameter<DoubleValue>(CostParameterName, "The value of the C (cost) parameter of C-SVC.", new DoubleValue(1.0)));
112      Parameters.Add(new ValueParameter<DoubleValue>(GammaParameterName, "The value of the gamma parameter in the kernel function.", new DoubleValue(1.0)));
113      Parameters.Add(new ValueParameter<IntValue>(DegreeParameterName, "The degree parameter for the polynomial kernel function.", new IntValue(3)));
114    }
115    [StorableHook(HookType.AfterDeserialization)]
116    private void AfterDeserialization() {
117      #region backwards compatibility (change with 3.4)
118      if (!Parameters.ContainsKey(DegreeParameterName))
119        Parameters.Add(new ValueParameter<IntValue>(DegreeParameterName, "The degree parameter for the polynomial kernel function.", new IntValue(3)));
120      #endregion
121    }
122
123    public override IDeepCloneable Clone(Cloner cloner) {
124      return new SupportVectorClassification(this, cloner);
125    }
126
127    #region support vector classification
128    protected override void Run() {
129      IClassificationProblemData problemData = Problem.ProblemData;
130      IEnumerable<string> selectedInputVariables = problemData.AllowedInputVariables;
131      double trainingAccuracy, testAccuracy;
132      int nSv;
133      var solution = CreateSupportVectorClassificationSolution(problemData, selectedInputVariables,
134        SvmType.Value, KernelType.Value, Cost.Value, Nu.Value, Gamma.Value, Degree.Value,
135        out trainingAccuracy, out testAccuracy, out nSv);
136
137      Results.Add(new Result("Support vector classification solution", "The support vector classification solution.", solution));
138      Results.Add(new Result("Training accuracy", "The accuracy of the SVR solution on the training partition.", new DoubleValue(trainingAccuracy)));
139      Results.Add(new Result("Test accuracy", "The accuracy of the SVR solution on the test partition.", new DoubleValue(testAccuracy)));
140      Results.Add(new Result("Number of support vectors", "The number of support vectors of the SVR solution.", new IntValue(nSv)));
141    }
142
143    public static SupportVectorClassificationSolution CreateSupportVectorClassificationSolution(IClassificationProblemData problemData, IEnumerable<string> allowedInputVariables,
144      string svmType, string kernelType, double cost, double nu, double gamma, int degree,
145      out double trainingAccuracy, out double testAccuracy, out int nSv) {
146      Dataset dataset = problemData.Dataset;
147      string targetVariable = problemData.TargetVariable;
148      IEnumerable<int> rows = problemData.TrainingIndices;
149
150      //extract SVM parameters from scope and set them
151      svm_parameter parameter = new svm_parameter();
152      parameter.svm_type = GetSvmType(svmType);
153      parameter.kernel_type = GetKernelType(kernelType);
154      parameter.C = cost;
155      parameter.nu = nu;
156      parameter.gamma = gamma;
157      parameter.cache_size = 500;
158      parameter.probability = 0;
159      parameter.eps = 0.001;
160      parameter.degree = degree;
161      parameter.shrinking = 1;
162      parameter.coef0 = 0;
163
164
165      var weightLabels = new List<int>();
166      var weights = new List<double>();
167      foreach (double c in problemData.ClassValues) {
168        double wSum = 0.0;
169        foreach (double otherClass in problemData.ClassValues) {
170          if (!c.IsAlmost(otherClass)) {
171            wSum += problemData.GetClassificationPenalty(c, otherClass);
172          }
173        }
174        weightLabels.Add((int)c);
175        weights.Add(wSum);
176      }
177      parameter.weight_label = weightLabels.ToArray();
178      parameter.weight = weights.ToArray();
179
180
181      svm_problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, targetVariable, allowedInputVariables, rows);
182      RangeTransform rangeTransform = RangeTransform.Compute(problem);
183      svm_problem scaledProblem = rangeTransform.Scale(problem);
184      var svmModel = svm.svm_train(scaledProblem, parameter);
185      var model = new SupportVectorMachineModel(svmModel, rangeTransform, targetVariable, allowedInputVariables, problemData.ClassValues);
186      var solution = new SupportVectorClassificationSolution(model, (IClassificationProblemData)problemData.Clone());
187
188      nSv = svmModel.SV.Length;
189      trainingAccuracy = solution.TrainingAccuracy;
190      testAccuracy = solution.TestAccuracy;
191
192      return solution;
193    }
194
195    private static int GetSvmType(string svmType) {
196      if (svmType == "NU_SVC") return svm_parameter.NU_SVC;
197      if (svmType == "C_SVC") return svm_parameter.C_SVC;
198      throw new ArgumentException("Unknown SVM type");
199    }
200
201    private static int GetKernelType(string kernelType) {
202      if (kernelType == "LINEAR") return svm_parameter.LINEAR;
203      if (kernelType == "POLY") return svm_parameter.POLY;
204      if (kernelType == "SIGMOID") return svm_parameter.SIGMOID;
205      if (kernelType == "RBF") return svm_parameter.RBF;
206      throw new ArgumentException("Unknown kernel type");
207    }
208    #endregion
209  }
210}
Note: See TracBrowser for help on using the repository browser.