Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12708 was 12708, checked in by mkommend, 7 years ago

#2025:Merged all changes regarding the new item dialog into stable.
#2387: Merged all changes regarding the type selector into stable.

File size: 10.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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(CreatableAttribute.Categories.DataAnalysisClassification, Priority = 110)]
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, out double trainingAccuracy, out double testAccuracy, out int nSv) {
145      return CreateSupportVectorClassificationSolution(problemData, allowedInputVariables, GetSvmType(svmType), GetKernelType(kernelType), cost, nu, gamma, degree,
146        out trainingAccuracy, out testAccuracy, out nSv);
147    }
148
149    public static SupportVectorClassificationSolution CreateSupportVectorClassificationSolution(IClassificationProblemData problemData, IEnumerable<string> allowedInputVariables,
150      int svmType, int kernelType, double cost, double nu, double gamma, int degree, out double trainingAccuracy, out double testAccuracy, out int nSv) {
151      var dataset = problemData.Dataset;
152      string targetVariable = problemData.TargetVariable;
153      IEnumerable<int> rows = problemData.TrainingIndices;
154
155      //extract SVM parameters from scope and set them
156      svm_parameter parameter = new svm_parameter();
157      parameter.svm_type = svmType;
158      parameter.kernel_type = kernelType;
159      parameter.C = cost;
160      parameter.nu = nu;
161      parameter.gamma = gamma;
162      parameter.cache_size = 500;
163      parameter.probability = 0;
164      parameter.eps = 0.001;
165      parameter.degree = degree;
166      parameter.shrinking = 1;
167      parameter.coef0 = 0;
168
169      var weightLabels = new List<int>();
170      var weights = new List<double>();
171      foreach (double c in problemData.ClassValues) {
172        double wSum = 0.0;
173        foreach (double otherClass in problemData.ClassValues) {
174          if (!c.IsAlmost(otherClass)) {
175            wSum += problemData.GetClassificationPenalty(c, otherClass);
176          }
177        }
178        weightLabels.Add((int)c);
179        weights.Add(wSum);
180      }
181      parameter.weight_label = weightLabels.ToArray();
182      parameter.weight = weights.ToArray();
183
184
185      svm_problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, targetVariable, allowedInputVariables, rows);
186      RangeTransform rangeTransform = RangeTransform.Compute(problem);
187      svm_problem scaledProblem = rangeTransform.Scale(problem);
188      var svmModel = svm.svm_train(scaledProblem, parameter);
189      var model = new SupportVectorMachineModel(svmModel, rangeTransform, targetVariable, allowedInputVariables, problemData.ClassValues);
190      var solution = new SupportVectorClassificationSolution(model, (IClassificationProblemData)problemData.Clone());
191
192      nSv = svmModel.SV.Length;
193      trainingAccuracy = solution.TrainingAccuracy;
194      testAccuracy = solution.TestAccuracy;
195
196      return solution;
197    }
198
199    private static int GetSvmType(string svmType) {
200      if (svmType == "NU_SVC") return svm_parameter.NU_SVC;
201      if (svmType == "C_SVC") return svm_parameter.C_SVC;
202      throw new ArgumentException("Unknown SVM type");
203    }
204
205    private static int GetKernelType(string kernelType) {
206      if (kernelType == "LINEAR") return svm_parameter.LINEAR;
207      if (kernelType == "POLY") return svm_parameter.POLY;
208      if (kernelType == "SIGMOID") return svm_parameter.SIGMOID;
209      if (kernelType == "RBF") return svm_parameter.RBF;
210      throw new ArgumentException("Unknown kernel type");
211    }
212    #endregion
213  }
214}
Note: See TracBrowser for help on using the repository browser.