McSvmATSTrainer.h
Go to the documentation of this file.
1 //===========================================================================
2 /*!
3  *
4  *
5  * \brief Trainer for the ATS 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_MCSVMATSTRAINER_H
38 #define SHARK_ALGORITHMS_MCSVMATSTRAINER_H
39 
40 
44 
48 
49 
50 namespace shark {
51 
52 
53 ///
54 /// \brief Training of ATS-SVMs for multi-category classification.
55 ///
56 /// The ATS-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 ATS machine is its
84 /// loss function, which arises from the application of the
85 /// total sum 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 ATS loss is given
88 /// by
89 /// \f[
90 /// L(y, f(x)) = \sum_c h((2 \cdot \delta_{c,y} - 1) \cdot f_c(x))
91 /// \f]
92 /// where the Kronecker delta is one if its arguments agree and
93 /// zero otherwise.
94 ///
95 /// For more details refer to the technical report:<br/>
96 /// <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>
97 ///
98 template <class InputType, class CacheType = float>
99 class McSvmATSTrainer : public AbstractSvmTrainer<InputType, unsigned int>
100 {
101 public:
102 
103  typedef CacheType QpFloatType;
107 
108  //! Constructor
109  //! \param kernel kernel function to use for training and prediction
110  //! \param C regularization parameter - always the 'true' value of C, even when unconstrained is set
111  //! \param unconstrained when a C-value is given via setParameter, should it be piped through the exp-function before using it in the solver?
112  McSvmATSTrainer(KernelType* kernel, double C, bool unconstrained = false)
113  : base_type(kernel, C, unconstrained)
114  { }
115 
116  /// \brief From INameable: return the class name.
117  std::string name() const
118  { return "McSvmATSTrainer"; }
119 
121  {
122  std::size_t ic = dataset.numberOfElements();
123  std::size_t classes = numberOfClasses(dataset);
124 
125  // prepare the problem description
126  RealMatrix linear(ic, classes,1.0);
127  QpSparseArray<QpFloatType> nu(classes*classes, classes, classes*classes);
128  for (unsigned int r=0, y=0; y<classes; y++)
129  {
130  for (unsigned int p=0; p<classes; p++, r++)
131  {
132  nu.add(r, p, (QpFloatType)((p == y) ? 1.0 : -1.0));
133  }
134  }
135 
136  QpSparseArray<QpFloatType> M(classes * classes * classes, classes, 2 * classes * classes * classes);
137  QpFloatType c_ne = (QpFloatType)(-1.0 / (double)classes);
138  QpFloatType c_eq = (QpFloatType)1.0 + c_ne;
139  for (unsigned int r=0, yv=0; yv<classes; yv++)
140  {
141  for (unsigned int pv=0; pv<classes; pv++)
142  {
143  QpFloatType sign = QpFloatType((yv == pv) ? -1 : 1);//cast to keep MSVC happy...
144  for (unsigned int yw=0; yw<classes; yw++, r++)
145  {
146  M.setDefaultValue(r, sign * c_ne);
147  if (yw == pv)
148  {
149  M.add(r, pv, -sign * c_eq);
150  }
151  else
152  {
153  M.add(r, pv, sign * c_eq);
154  M.add(r, yw, -sign * c_ne);
155  }
156  }
157  }
158  }
159 
160  typedef KernelMatrix<InputType, QpFloatType> KernelMatrixType;
161  typedef CachedMatrix< KernelMatrixType > CachedMatrixType;
162  typedef PrecomputedMatrix< KernelMatrixType > PrecomputedMatrixType;
163 
164  KernelMatrixType km(*base_type::m_kernel, dataset.inputs());
165 
166  RealMatrix alpha(ic,classes,0.0);
167  RealVector bias(classes,0.0);
168  // solve the problem
170  {
171  PrecomputedMatrixType matrix(&km);
172  QpMcBoxDecomp< PrecomputedMatrixType> problem(matrix, M, dataset.labels(), linear, this->C());
174  problem.setShrinking(base_type::m_shrinking);
175  if(this->m_trainOffset){
176  BiasSolver<PrecomputedMatrixType> biasSolver(&problem);
177  biasSolver.solve(bias,base_type::m_stoppingcondition,nu);
178  }
179  else{
181  solver.solve( base_type::m_stoppingcondition, &prop);
182  }
183  alpha = problem.solution();
184  }
185  else
186  {
187  CachedMatrixType matrix(&km, base_type::m_cacheSize);
188  QpMcBoxDecomp< CachedMatrixType> problem(matrix, M, dataset.labels(), linear, this->C());
190  problem.setShrinking(base_type::m_shrinking);
191  if(this->m_trainOffset){
192  BiasSolver<CachedMatrixType> biasSolver(&problem);
193  biasSolver.solve(bias,base_type::m_stoppingcondition,nu);
194  }
195  else{
197  solver.solve( base_type::m_stoppingcondition, &prop);
198  }
199  alpha = problem.solution();
200  }
201 
202  svm.decisionFunction().setStructure(this->m_kernel,dataset.inputs(),this->m_trainOffset,classes);
203 
204  // write the solution into the model
205  for (std::size_t i=0; i<ic; i++)
206  {
207  unsigned int y = dataset.element(i).label;
208  for (unsigned int c=0; c<classes; c++)
209  {
210  double sum = 0.0;
211  unsigned int r = classes * y;
212  for (unsigned int p=0; p<classes; p++, r++)
213  sum += nu(r, c) * alpha(i, p);
214  svm.decisionFunction().alpha(i,c) = sum;
215  }
216  }
217  if (this->m_trainOffset)
218  svm.decisionFunction().offset() = bias;
219 
220  base_type::m_accessCount = km.getAccessCount();
221  if (this->sparsify())
222  svm.decisionFunction().sparsify();
223  }
224 };
225 
226 
227 template <class InputType>
229 {
230 public:
232 
233  LinearMcSvmATSTrainer(double C, bool unconstrained = false)
234  : AbstractLinearSvmTrainer<InputType>(C, unconstrained){ }
235 
236  /// \brief From INameable: return the class name.
237  std::string name() const
238  { return "LinearMcSvmATSTrainer"; }
239 
241  {
242  std::size_t dim = inputDimension(dataset);
243  std::size_t classes = numberOfClasses(dataset);
244 
245  QpMcLinearATS<InputType> solver(dataset, dim, classes);
246  RealMatrix w = solver.solve(this->C(), this->stoppingCondition(), &this->solutionProperties(), this->verbosity() > 0);
247  model.decisionFunction().setStructure(w);
248  }
249 };
250 
251 
252 }
253 #endif