Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/SupportVectorMachine/SupportVectorRegression.cs @ 8609

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

#1944 changed SVR and SVC algorithms in HeuristicLab to use most recent LibSVM version.

File size: 8.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 regression data analysis algorithm.
37  /// </summary>
38  [Item("Support Vector Regression", "Support vector machine regression data analysis algorithm (wrapper for libSVM).")]
39  [Creatable("Data Analysis")]
40  [StorableClass]
41  public sealed class SupportVectorRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
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 EpsilonParameterName = "Epsilon";
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<DoubleValue> EpsilonParameter {
66      get { return (IValueParameter<DoubleValue>)Parameters[EpsilonParameterName]; }
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 DoubleValue Epsilon {
88      get { return EpsilonParameter.Value; }
89    }
90    #endregion
91    [StorableConstructor]
92    private SupportVectorRegression(bool deserializing) : base(deserializing) { }
93    private SupportVectorRegression(SupportVectorRegression original, Cloner cloner)
94      : base(original, cloner) {
95    }
96    public SupportVectorRegression()
97      : base() {
98      Problem = new RegressionProblem();
99
100      List<StringValue> svrTypes = (from type in new List<string> { "NU_SVR", "EPSILON_SVR" }
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 of the nu-SVR.", new DoubleValue(0.5)));
111      Parameters.Add(new ValueParameter<DoubleValue>(CostParameterName, "The value of the C (cost) parameter of epsilon-SVR and nu-SVR.", 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<DoubleValue>(EpsilonParameterName, "The value of the epsilon parameter for epsilon-SVR.", new DoubleValue(0.1)));
114    }
115    [StorableHook(HookType.AfterDeserialization)]
116    private void AfterDeserialization() { }
117
118    public override IDeepCloneable Clone(Cloner cloner) {
119      return new SupportVectorRegression(this, cloner);
120    }
121
122    #region support vector regression
123    protected override void Run() {
124      IRegressionProblemData problemData = Problem.ProblemData;
125      IEnumerable<string> selectedInputVariables = problemData.AllowedInputVariables;
126      double trainR2, testR2;
127      int nSv;
128      var solution = CreateSupportVectorRegressionSolution(problemData, selectedInputVariables, SvmType.Value,
129        KernelType.Value, Cost.Value, Nu.Value, Gamma.Value, Epsilon.Value,
130        out trainR2, out testR2, out nSv);
131
132      Results.Add(new Result("Support vector regression solution", "The support vector regression solution.", solution));
133      Results.Add(new Result("Training R²", "The Pearson's R² of the SVR solution on the training partition.", new DoubleValue(trainR2)));
134      Results.Add(new Result("Test R²", "The Pearson's R² of the SVR solution on the test partition.", new DoubleValue(testR2)));
135      Results.Add(new Result("Number of support vectors", "The number of support vectors of the SVR solution.", new IntValue(nSv)));
136    }
137
138    public static SupportVectorRegressionSolution CreateSupportVectorRegressionSolution(IRegressionProblemData problemData, IEnumerable<string> allowedInputVariables,
139      string svmType, string kernelType, double cost, double nu, double gamma, double epsilon,
140      out double trainingR2, out double testR2, out int nSv) {
141      Dataset dataset = problemData.Dataset;
142      string targetVariable = problemData.TargetVariable;
143      IEnumerable<int> rows = problemData.TrainingIndices;
144
145      //extract SVM parameters from scope and set them
146      svm_parameter parameter = new svm_parameter();
147      parameter.svm_type = GetSvmType(svmType);
148      parameter.kernel_type = GetKernelType(kernelType);
149      parameter.C = cost;
150      parameter.nu = nu;
151      parameter.gamma = gamma;
152      parameter.p = epsilon;
153      parameter.cache_size = 500;
154      parameter.probability = 0;
155      parameter.eps = 0.001;
156      parameter.degree = 3;
157      parameter.shrinking = 1;
158      parameter.coef0 = 0;
159
160
161
162      svm_problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, targetVariable, allowedInputVariables, rows);
163      RangeTransform rangeTransform = RangeTransform.Compute(problem);
164      svm_problem scaledProblem = rangeTransform.Scale(problem);
165      var svmModel = svm.svm_train(scaledProblem, parameter);
166      nSv = svmModel.SV.Length;
167      var model = new SupportVectorMachineModel(svmModel, rangeTransform, targetVariable, allowedInputVariables);
168      var solution = new SupportVectorRegressionSolution(model, (IRegressionProblemData)problemData.Clone());
169      trainingR2 = solution.TrainingRSquared;
170      testR2 = solution.TestRSquared;
171      return solution;
172    }
173
174    private static int GetSvmType(string svmType) {
175      if (svmType == "NU_SVR") return svm_parameter.NU_SVR;
176      if (svmType == "EPSILON_SVR") return svm_parameter.EPSILON_SVR;
177      throw new ArgumentException("Unknown SVM type");
178    }
179
180    private static int GetKernelType(string kernelType) {
181      if (kernelType == "LINEAR") return svm_parameter.LINEAR;
182      if (kernelType == "POLY") return svm_parameter.POLY;
183      if (kernelType == "SIGMOID") return svm_parameter.SIGMOID;
184      if (kernelType == "RBF") return svm_parameter.RBF;
185      throw new ArgumentException("Unknown kernel type");
186    }
187    #endregion
188  }
189}
Note: See TracBrowser for help on using the repository browser.