Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1797 added an interface IConstrainedValueParameter, added a test case to check the name, visibility and type of the parameter-property for constrainedValueParameters, corrected all properties in IParameterizedItems

File size: 8.3 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;
32
33namespace HeuristicLab.Algorithms.DataAnalysis {
34  /// <summary>
35  /// Support vector machine regression data analysis algorithm.
36  /// </summary>
37  [Item("Support Vector Regression", "Support vector machine regression data analysis algorithm (wrapper for libSVM).")]
38  [Creatable("Data Analysis")]
39  [StorableClass]
40  public sealed class SupportVectorRegression : FixedDataAnalysisAlgorithm<IRegressionProblem> {
41    private const string SvmTypeParameterName = "SvmType";
42    private const string KernelTypeParameterName = "KernelType";
43    private const string CostParameterName = "Cost";
44    private const string NuParameterName = "Nu";
45    private const string GammaParameterName = "Gamma";
46    private const string EpsilonParameterName = "Epsilon";
47
48    #region parameter properties
49    public IConstrainedValueParameter<StringValue> SvmTypeParameter {
50      get { return (IConstrainedValueParameter<StringValue>)Parameters[SvmTypeParameterName]; }
51    }
52    public IConstrainedValueParameter<StringValue> KernelTypeParameter {
53      get { return (IConstrainedValueParameter<StringValue>)Parameters[KernelTypeParameterName]; }
54    }
55    public IValueParameter<DoubleValue> NuParameter {
56      get { return (IValueParameter<DoubleValue>)Parameters[NuParameterName]; }
57    }
58    public IValueParameter<DoubleValue> CostParameter {
59      get { return (IValueParameter<DoubleValue>)Parameters[CostParameterName]; }
60    }
61    public IValueParameter<DoubleValue> GammaParameter {
62      get { return (IValueParameter<DoubleValue>)Parameters[GammaParameterName]; }
63    }
64    public IValueParameter<DoubleValue> EpsilonParameter {
65      get { return (IValueParameter<DoubleValue>)Parameters[EpsilonParameterName]; }
66    }
67    #endregion
68    #region properties
69    public StringValue SvmType {
70      get { return SvmTypeParameter.Value; }
71      set { SvmTypeParameter.Value = value; }
72    }
73    public StringValue KernelType {
74      get { return KernelTypeParameter.Value; }
75      set { KernelTypeParameter.Value = value; }
76    }
77    public DoubleValue Nu {
78      get { return NuParameter.Value; }
79    }
80    public DoubleValue Cost {
81      get { return CostParameter.Value; }
82    }
83    public DoubleValue Gamma {
84      get { return GammaParameter.Value; }
85    }
86    public DoubleValue Epsilon {
87      get { return EpsilonParameter.Value; }
88    }
89    #endregion
90    [StorableConstructor]
91    private SupportVectorRegression(bool deserializing) : base(deserializing) { }
92    private SupportVectorRegression(SupportVectorRegression original, Cloner cloner)
93      : base(original, cloner) {
94    }
95    public SupportVectorRegression()
96      : base() {
97      Problem = new RegressionProblem();
98
99      List<StringValue> svrTypes = (from type in new List<string> { "NU_SVR", "EPSILON_SVR" }
100                                    select new StringValue(type).AsReadOnly())
101                                   .ToList();
102      ItemSet<StringValue> svrTypeSet = new ItemSet<StringValue>(svrTypes);
103      List<StringValue> kernelTypes = (from type in new List<string> { "LINEAR", "POLY", "SIGMOID", "RBF" }
104                                       select new StringValue(type).AsReadOnly())
105                                   .ToList();
106      ItemSet<StringValue> kernelTypeSet = new ItemSet<StringValue>(kernelTypes);
107      Parameters.Add(new ConstrainedValueParameter<StringValue>(SvmTypeParameterName, "The type of SVM to use.", svrTypeSet, svrTypes[0]));
108      Parameters.Add(new ConstrainedValueParameter<StringValue>(KernelTypeParameterName, "The kernel type to use for the SVM.", kernelTypeSet, kernelTypes[3]));
109      Parameters.Add(new ValueParameter<DoubleValue>(NuParameterName, "The value of the nu parameter of the nu-SVR.", new DoubleValue(0.5)));
110      Parameters.Add(new ValueParameter<DoubleValue>(CostParameterName, "The value of the C (cost) parameter of epsilon-SVR and nu-SVR.", new DoubleValue(1.0)));
111      Parameters.Add(new ValueParameter<DoubleValue>(GammaParameterName, "The value of the gamma parameter in the kernel function.", new DoubleValue(1.0)));
112      Parameters.Add(new ValueParameter<DoubleValue>(EpsilonParameterName, "The value of the epsilon parameter for epsilon-SVR.", new DoubleValue(0.1)));
113    }
114    [StorableHook(HookType.AfterDeserialization)]
115    private void AfterDeserialization() { }
116
117    public override IDeepCloneable Clone(Cloner cloner) {
118      return new SupportVectorRegression(this, cloner);
119    }
120
121    #region support vector regression
122    protected override void Run() {
123      IRegressionProblemData problemData = Problem.ProblemData;
124      IEnumerable<string> selectedInputVariables = problemData.AllowedInputVariables;
125      double trainR2, testR2;
126      int nSv;
127      var solution = CreateSupportVectorRegressionSolution(problemData, selectedInputVariables, SvmType.Value,
128        KernelType.Value, Cost.Value, Nu.Value, Gamma.Value, Epsilon.Value,
129        out trainR2, out testR2, out nSv);
130
131      Results.Add(new Result("Support vector regression solution", "The support vector regression solution.", solution));
132      Results.Add(new Result("Training R²", "The Pearson's R² of the SVR solution on the training partition.", new DoubleValue(trainR2)));
133      Results.Add(new Result("Test R²", "The Pearson's R² of the SVR solution on the test partition.", new DoubleValue(testR2)));
134      Results.Add(new Result("Number of support vectors", "The number of support vectors of the SVR solution.", new IntValue(nSv)));
135    }
136
137    public static SupportVectorRegressionSolution CreateSupportVectorRegressionSolution(IRegressionProblemData problemData, IEnumerable<string> allowedInputVariables,
138      string svmType, string kernelType, double cost, double nu, double gamma, double epsilon,
139      out double trainingR2, out double testR2, out int nSv) {
140      Dataset dataset = problemData.Dataset;
141      string targetVariable = problemData.TargetVariable;
142      IEnumerable<int> rows = problemData.TrainingIndizes;
143
144      //extract SVM parameters from scope and set them
145      SVM.Parameter parameter = new SVM.Parameter();
146      parameter.SvmType = (SVM.SvmType)Enum.Parse(typeof(SVM.SvmType), svmType, true);
147      parameter.KernelType = (SVM.KernelType)Enum.Parse(typeof(SVM.KernelType), kernelType, true);
148      parameter.C = cost;
149      parameter.Nu = nu;
150      parameter.Gamma = gamma;
151      parameter.P = epsilon;
152      parameter.CacheSize = 500;
153      parameter.Probability = false;
154
155
156      SVM.Problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, targetVariable, allowedInputVariables, rows);
157      SVM.RangeTransform rangeTransform = SVM.RangeTransform.Compute(problem);
158      SVM.Problem scaledProblem = SVM.Scaling.Scale(rangeTransform, problem);
159      var svmModel = SVM.Training.Train(scaledProblem, parameter);
160      nSv = svmModel.SupportVectorCount;
161      var model = new SupportVectorMachineModel(svmModel, rangeTransform, targetVariable, allowedInputVariables);
162      var solution = new SupportVectorRegressionSolution(model, (IRegressionProblemData)problemData.Clone());
163      trainingR2 = solution.TrainingRSquared;
164      testR2 = solution.TestRSquared;
165      return solution;
166    }
167    #endregion
168  }
169}
Note: See TracBrowser for help on using the repository browser.