McSvmADMTrainer.h
Go to the documentation of this file.
1 //===========================================================================
2 /*!
3  *
4  *
5  * \brief Trainer for the ADM Multi-class Support Vector Machine
6  *
7  *
8  *
9  *
10  * \author T. Glasmachers
11  * \date -
12  *
13  *
14  * \par Copyright 1995-2015 Shark Development Team
15  *
16  * <BR><HR>
17  * This file is part of Shark.
18  * <http://image.diku.dk/shark/>
19  *
20  * Shark is free software: you can redistribute it and/or modify
21  * it under the terms of the GNU Lesser General Public License as published
22  * by the Free Software Foundation, either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * Shark is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU Lesser General Public License for more details.
29  *
30  * You should have received a copy of the GNU Lesser General Public License
31  * along with Shark. If not, see <http://www.gnu.org/licenses/>.
32  *
33  */
34 //===========================================================================
35 
36 
37 #ifndef SHARK_ALGORITHMS_MCSVMADMTRAINER_H
38 #define SHARK_ALGORITHMS_MCSVMADMTRAINER_H
39 
40 
44 
48 
49 
50 namespace shark {
51 
52 
53 ///
54 /// \brief Training of ADM-SVMs for multi-category classification.
55 ///
56 /// The ADM-SVM is a special support vector machine variant for
57 /// classification of more than two classes. Given are data
58 /// tuples \f$ (x_i, y_i) \f$ with x-component denoting input
59 /// and y-component denoting the label 1, ..., d (see the tutorial on
60 /// label conventions; the implementation uses values 0 to d-1),
61 /// a kernel function k(x, x') and a regularization
62 /// constant C > 0. Let H denote the kernel induced
63 /// reproducing kernel Hilbert space of k, and let \f$ \phi \f$
64 /// denote the corresponding feature map.
65 /// Then the SVM classifier is the function
66 /// \f[
67 /// h(x) = \arg \max (f_c(x))
68 /// \f]
69 /// \f[
70 /// f_c(x) = \langle w_c, \phi(x) \rangle + b_c
71 /// \f]
72 /// \f[
73 /// f = (f_1, \dots, f_d)
74 /// \f]
75 /// with class-wise coefficients w_c and b_c given by the
76 /// (primal) optimization problem
77 /// \f[
78 /// \min \frac{1}{2} \sum_c \|w_c\|^2 + C \sum_i L(y_i, f(x_i))
79 /// \f]
80 /// \f[
81 /// \text{s.t. } \sum_c f_c = 0
82 /// \f]
83 /// The special property of the so-called ADM machine is its
84 /// loss function, which arises from the application of the
85 /// discriminative maximum operator to absolute margin violations.
86 /// Let \f$ h(m) = \max\{0, 1-m\} \f$ denote the hinge loss
87 /// as a function of the margin m, then the ADM loss is given
88 /// by
89 /// \f[
90 /// L(y, f(x)) = \max_{c \not= y} h(-f_c(x))
91 /// \f]
92 ///
93 /// For more details refer to the technical report:<br/>
94 /// <p>Fast Training of Multi-Class Support Vector Machines. &Uuml; Dogan, T. Glasmachers, and C. Igel, Technical Report 2011/3, Department of Computer Science, University of Copenhagen, 2011.</p>
95 ///
96 template <class InputType, class CacheType = float>
97 class McSvmADMTrainer : public AbstractSvmTrainer<InputType, unsigned int>
98 {
99 public:
100 
101  typedef CacheType QpFloatType;
102 
106 
107  //! Constructor
108  //! \param kernel kernel function to use for training and prediction
109  //! \param C regularization parameter - always the 'true' value of C, even when unconstrained is set
110  //! \param unconstrained when a C-value is given via setParameter, should it be piped through the exp-function before using it in the solver?
111  McSvmADMTrainer(KernelType* kernel, double C, bool unconstrained = false)
112  : base_type(kernel, C, unconstrained)
113  { }
114 
115  /// \brief From INameable: return the class name.
116  std::string name() const
117  { return "McSvmADMTrainer"; }
118 
120  {
121  std::size_t ic = dataset.numberOfElements();
122  std::size_t classes = numberOfClasses(dataset);
123 
124  // prepare the problem description
125  RealMatrix linear(ic, classes-1,1.0);
126  QpSparseArray<QpFloatType> nu(classes * (classes-1), classes, classes*(classes-1));
127  for (unsigned int r=0, y=0; y<classes; y++)
128  {
129  for (unsigned int p=0, pp=0; p<classes-1; p++, pp++, r++)
130  {
131  if (pp == y) pp++;
132  nu.add(r, pp, -1.0);
133  }
134  }
135 
136  QpSparseArray<QpFloatType> M(classes * (classes-1) * classes, classes-1, classes * (classes-1) * (classes-1));
137  QpFloatType mood = (QpFloatType)(-1.0 / (double)classes);
138  QpFloatType val = (QpFloatType)1.0 + mood;
139  for (unsigned int r=0, yv=0; yv<classes; yv++)
140  {
141  for (unsigned int pv=0, ppv=0; pv<classes-1; pv++, ppv++)
142  {
143  if (ppv == yv) ppv++;
144  for (unsigned int yw=0; yw<classes; yw++, r++)
145  {
146  M.setDefaultValue(r, mood);
147  if (ppv != yw)
148  {
149  unsigned int pw = ppv - (ppv > yw ? 1 : 0);
150  M.add(r, pw, val);
151  }
152  }
153  }
154  }
155 
156  typedef KernelMatrix<InputType, QpFloatType> KernelMatrixType;
157  typedef CachedMatrix< KernelMatrixType > CachedMatrixType;
158  typedef PrecomputedMatrix< KernelMatrixType > PrecomputedMatrixType;
159 
160  KernelMatrixType km(*base_type::m_kernel, dataset.inputs());
161 
162  RealMatrix alpha(ic,classes-1,0.0);
163  RealVector bias(classes,0.0);
164  // solve the problem
166  {
167  PrecomputedMatrixType matrix(&km);
168  QpMcSimplexDecomp< PrecomputedMatrixType> problem(matrix, M, dataset.labels(), linear, this->C());
170  problem.setShrinking(base_type::m_shrinking);
171  //problem.setShrinking(false);
172  if(this->m_trainOffset){
173  BiasSolverSimplex<PrecomputedMatrixType> biasSolver(&problem);
174  biasSolver.solve(bias,base_type::m_stoppingcondition,nu);
175  }
176  else{
178  solver.solve( base_type::m_stoppingcondition, &prop);
179  }
180  alpha = problem.solution();
181  }
182  else
183  {
184  CachedMatrixType matrix(&km, base_type::m_cacheSize);
185  QpMcSimplexDecomp< CachedMatrixType> problem(matrix, M, dataset.labels(), linear, this->C());
187  problem.setShrinking(base_type::m_shrinking);
188  //problem.setShrinking(false);
189  if(this->m_trainOffset){
190  BiasSolverSimplex<CachedMatrixType> biasSolver(&problem);
191  biasSolver.solve(bias,base_type::m_stoppingcondition,nu);
192  }
193  else{
195  solver.solve( base_type::m_stoppingcondition, &prop);
196  }
197  alpha = problem.solution();
198  }
199 
200  svm.decisionFunction().setStructure(this->m_kernel,dataset.inputs(),this->m_trainOffset,classes);
201 
202  // write the solution into the model
203  for (std::size_t i=0; i<ic; i++)
204  {
205  unsigned int y = dataset.element(i).label;
206  for (unsigned int c=0; c<classes; c++)
207  {
208  double sum = 0.0;
209  unsigned int r = (classes-1) * y;
210  for (unsigned int p=0; p != classes-1; p++, r++)
211  sum += nu(r, c) * alpha(i, p);
212  svm.decisionFunction().alpha(i,c) = sum;
213  }
214  }
215  if (this->m_trainOffset)
216  svm.decisionFunction().offset() = bias;
217 
218  base_type::m_accessCount = km.getAccessCount();
219  if (this->sparsify())
220  svm.decisionFunction().sparsify();
221  }
222 };
223 
224 
225 template <class InputType>
227 {
228 public:
230 
231  LinearMcSvmADMTrainer(double C, bool unconstrained = false)
232  : AbstractLinearSvmTrainer<InputType>(C, unconstrained){ }
233 
234  /// \brief From INameable: return the class name.
235  std::string name() const
236  { return "LinearMcSvmADMTrainer"; }
237 
239  {
240  std::size_t dim = inputDimension(dataset);
241  std::size_t classes = numberOfClasses(dataset);
242 
243  QpMcLinearADM<InputType> solver(dataset, dim, classes);
244  RealMatrix w = solver.solve(this->C(), this->stoppingCondition(), &this->solutionProperties(), this->verbosity() > 0);
245  model.decisionFunction().setStructure(w);
246  }
247 };
248 
249 
250 }
251 #endif