You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2172 lines
67 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file svm.c
  2. ** @brief Support Vector Machines (SVM) - Implementation
  3. ** @author Milan Sulc
  4. ** @author Daniele Perrone
  5. ** @author Andrea Vedaldi
  6. **/
  7. /*
  8. Copyright (C) 2013 Milan Sulc.
  9. Copyright (C) 2012 Daniele Perrone.
  10. Copyright (C) 2011-13 Andrea Vedaldi.
  11. All rights reserved.
  12. This file is part of the VLFeat library and is made available under
  13. the terms of the BSD license (see the COPYING file).
  14. */
  15. /** @file svm.h
  16. ** @see @ref svm.
  17. **/
  18. /**
  19. <!-- ------------------------------------------------------------- -->
  20. @page svm Support Vector Machines (SVM)
  21. @author Milan Sulc
  22. @author Daniele Perrone
  23. @author Andrea Vedaldi
  24. @tableofcontents
  25. <!-- ------------------------------------------------------------- -->
  26. *Support Vector Machines* (SVMs) are one of the most popular types of
  27. discriminate classifiers. VLFeat implements two solvers, SGD and SDCA,
  28. capable of learning linear SVMs on a large scale. These linear solvers
  29. can be combined with explicit feature maps to learn non-linear models
  30. as well. The solver supports a few variants of the standard
  31. SVM formulation, including using loss functions other than the hinge
  32. loss.
  33. @ref svm-starting demonstrates how to use VLFeat to learn an SVM.
  34. Information on SVMs and the corresponding optimization algorithms as
  35. implemented by VLFeat are given in:
  36. - @subpage svm-fundamentals - Linear SVMs and their learning.
  37. - @subpage svm-advanced - Loss functions, dual objective, and other details.
  38. - @subpage svm-sgd - The SGD algorithm.
  39. - @subpage svm-sdca - The SDCA algorithm.
  40. <!-- ------------------------------------------------------------- -->
  41. @section svm-starting Getting started
  42. <!-- ------------------------------------------------------------- -->
  43. This section demonstrates how to learn an SVM by using VLFeat. SVM
  44. learning is implemented by the ::VlSvm object type. Let's
  45. start by a complete example:
  46. @code
  47. #include <stdio.h>
  48. #include <vl/svm.h>
  49. int main()
  50. {
  51. vl_size const numData = 4 ;
  52. vl_size const dimension = 2 ;
  53. double x [dimension * numData] = {
  54. 0.0, -0.5,
  55. 0.6, -0.3,
  56. 0.0, 0.5
  57. 0.6, 0.0} ;
  58. double y [numData] = {1, 1, -1, 1} ;
  59. double lambda = 0.01;
  60. double * const model ;
  61. double bias ;
  62. VlSvm * svm = vl_svm_new(VlSvmSolverSgd,
  63. x, dimension, numData,
  64. y,
  65. lambda) ;
  66. vl_svm_train(svm) ;
  67. model = vl_svm_get_model(svm) ;
  68. bias = vl_svm_get_bias(svm) ;
  69. printf("model w = [ %f , %f ] , bias b = %f \n",
  70. model[0],
  71. model[1],
  72. bias);
  73. vl_svm_delete(svm) ;
  74. return 0;
  75. }
  76. @endcode
  77. This code learns a binary linear SVM using the SGD algorithm on
  78. four two-dimensional points using 0.01 as regularization parameter.
  79. ::VlSvmSolverSdca can be specified in place of ::VlSvmSolverSdca
  80. in orer to use the SDCA algorithm instead.
  81. Convergence and other diagnostic information can be obtained after
  82. training by using the ::vl_svm_get_statistics function. Algorithms
  83. regularly check for convergence (usally after each pass over the data).
  84. The ::vl_svm_set_diagnostic_function can be used to specify a callback
  85. to be invoked when diagnostic is run. This can be used, for example,
  86. to dump information on the screen as the algorithm progresses.
  87. Convergence is reached after a maximum number of iterations
  88. (::vl_svm_set_max_num_iterations) or after a given criterion falls
  89. below a threshold (::vl_svm_set_epsilon). The meaning of these
  90. may depend on the specific algorithm (see @ref svm for further details).
  91. ::VlSvm is a quite powerful object. Algorithms only need to perform
  92. inner product and accumulation operation on the data (see @ref svm-advanced).
  93. This is used to abstract from the data type and support almost anything
  94. by speciying just two functions (::vl_svm_set_data_functions).
  95. A simple interface to this advanced functionality is provided by the
  96. ::VlSvmDataset object. This supports natively @c float and @c double
  97. data types, as well as applying on the fly the homogeneous kernel map
  98. (@ref homkermap). This is exemplified in @ref svmdataset-starting.
  99. */
  100. /**
  101. <!-- ------------------------------------------------------------- -->
  102. @page svm-fundamentals SVM fundamentals
  103. @tableofcontents
  104. <!-- ------------------------------------------------------------- -->
  105. This page introduces the SVM formulation used in VLFeat. See @ref svm
  106. for more information on VLFeat SVM support.
  107. Let $ \bx \in \real^d $ be a vector representing, for example, an
  108. image, an audio track, or a fragment of text. Our goal is to design a
  109. *classifier*, i.e. a function that associates to each vector $\bx$ a
  110. positive or negative label based on a desired criterion, for example
  111. the fact that the image contains or not a cat, that the audio track
  112. contains or not English speech, or that the text is or not a
  113. scientific paper.
  114. The vector $\bx$ is classified by looking at the sign of a *linear
  115. scoring function* $\langle \bx, \bw \rangle$. The goal of learning is
  116. to estimate the parameter $\bw \in \real^d$ in such a way that the
  117. score is positive if the vector $\bx$ belongs to the positive class
  118. and negative otherwise. In fact, in the standard SVM formulation the
  119. the goal is to have a score of *at least 1* in the first case, and of
  120. *at most -1* in the second one, imposing a *margin*.
  121. The parameter $\bw$ is estimated or *learned* by fitting the scoring
  122. function to a training set of $n$ example pairs $(\bx_i,y_i),
  123. i=1,\dots,n$. Here $y_i \in \{-1,1\}$ are the *ground truth labels* of
  124. the corresponding example vectors. The fit quality is measured by a
  125. *loss function* which, in standard SVMs, is the *hinge loss*:
  126. \[
  127. \ell_i(\langle \bw,\bx\rangle) = \max\{0, 1 - y_i \langle \bw,\bx\rangle\}.
  128. \]
  129. Note that the hinge loss is zero only if the score $\langle
  130. \bw,\bx\rangle$ is at least 1 or at most -1, depending on the label
  131. $y_i$.
  132. Fitting the training data is usually insufficient. In order for the
  133. scoring function *generalize to future data* as well, it is usually
  134. preferable to trade off the fitting accuracy with the *regularity* of
  135. the learned scoring function $\langle \bx, \bw \rangle$. Regularity in
  136. the standard formulation is measured by the norm of the parameter
  137. vector $\|\bw\|^2$ (see @ref svm-advanced). Averaging the loss on all
  138. training samples and adding to it the regularizer weighed by a
  139. parameter $\lambda$ yields the *regularized loss objective*
  140. @f{equation}{
  141. \boxed{\displaystyle
  142. E(\bw) = \frac{\lambda}{2} \left\| \bw \right\|^2
  143. + \frac{1}{n} \sum_{i=1}^n \max\{0, 1 - y_i \langle \bw,\bx\rangle\}.
  144. \label{e:svm-primal-hinge}
  145. }
  146. @f}
  147. Note that this objective function is *convex*, so that there exists a
  148. single global optimum.
  149. The scoring function $\langle \bx, \bw \rangle$ considered so far has
  150. been linear and unbiased. @ref svm-bias discusses how a bias term can
  151. be added to the SVM and @ref svm-feature-maps shows how non-linear
  152. SVMs can be reduced to the linear case by computing suitable feature
  153. maps.
  154. @ref svm-learning shows how VLFeat can be used to learn an SVM by
  155. minimizing $E(\bw)$.
  156. <!-- ------------------------------------------------------------- -->
  157. @section svm-learning Learning
  158. <!-- ------------------------------------------------------------- -->
  159. Learning an SVM amounts to finding the minimizer $\bw^*$ of the cost
  160. function $E(\bw)$. While there are dozens of methods that can be used
  161. to do so, VLFeat implements two large scale methods, designed to work
  162. with linear SVMs (see @ref svm-feature-maps to go beyond linear):
  163. - @ref svm-sgd
  164. - @ref svm-sdca
  165. Using these solvers is exemplified in @ref svm-starting.
  166. <!-- ------------------------------------------------------------- -->
  167. @section svm-bias Adding a bias
  168. <!-- ------------------------------------------------------------- -->
  169. It is common to add to the SVM scoring function a *bias term* $b$, and
  170. to consider the score $\langle \bx,\bw \rangle + b$. In practice the
  171. bias term can be crucial to fit the training data optimally, as there
  172. is no reason why the inner products $\langle \bx,\bw \rangle$ should
  173. be naturally centered at zero.
  174. Some SVM learning algorithms can estimate both $\bw$ and $b$
  175. directly. However, other algorithms such as SGD and SDCA cannot. In
  176. this case, a simple workaround is to add a constant component $B > 0$
  177. (we call this constant the *bias multiplier*) to the data,
  178. i.e. consider the extended data vectors:
  179. \[
  180. \bar \bx = \begin{bmatrix} \bx \\ B \end{bmatrix},
  181. \quad
  182. \bar \bw = \begin{bmatrix} \bw \\ w_b \end{bmatrix}.
  183. \]
  184. In this manner the scoring function incorporates implicitly a bias $b = B w_b$:
  185. \[
  186. \langle \bar\bx, \bar\bw \rangle =
  187. \langle \bx, \bw \rangle + B w_b.
  188. \]
  189. The disadvantage of this reduction is that the term $w_b^2$ becomes
  190. part of the SVM regularizer, which shrinks the bias $b$ towards
  191. zero. This effect can be alleviated by making $B$ sufficiently large,
  192. because in this case $\|\bw\|^2 \gg w_b^2$ and the shrinking effect is
  193. negligible.
  194. Unfortunately, making $B$ too large makes the problem numerically
  195. unbalanced, so a reasonable trade-off between shrinkage and stability
  196. is generally sought. Typically, a good trade-off is obtained by
  197. normalizing the data to have unitary Euclidean norm and then choosing
  198. $B \in [1, 10]$.
  199. Specific implementations of SGD and SDCA may provide explicit support
  200. to learn the bias in this manner, but it is important to understand
  201. the implications on speed and accuracy of the learning if this is
  202. done.
  203. <!-- ------------------------------------------------------------- -->
  204. @section svm-feature-maps Non-linear SVMs and feature maps
  205. <!-- ------------------------------------------------------------- -->
  206. So far only linear scoring function $\langle \bx,\bw \rangle$ have
  207. been considered. Implicitly, however, this assumes that the objects to
  208. be classified (e.g. images) have been encoded as vectors $\bx$ in a
  209. way that makes linear classification possible. This encoding step can
  210. be made explicit by introducing the *feature map* $\Phi(\bx) \in
  211. \real^d$. Including the feature map yields a scoring function
  212. *non-linear* in $\bx$:
  213. \[
  214. \bx\in\mathcal{X} \quad\longrightarrow\quad \langle \Phi(\bx), \bw \rangle.
  215. \]
  216. The nature of the input space $\mathcal{X}$ can be arbitrary and might
  217. not have a vector space structure at all.
  218. The representation or encoding captures a notion of *similarity*
  219. between objects: if two vectors $\Phi(\bx_1)$ and $\Phi(\bx_2)$ are
  220. similar, then their scores will also be similar. Note that choosing a
  221. feature map amounts to incorporating this information in the model
  222. *prior* to learning.
  223. The relation of feature maps to similarity functions is formalized by
  224. the notion of a *kernel*, a positive definite function $K(\bx,\bx')$
  225. measuring the similarity of a pair of objects. A feature map defines a
  226. kernel by
  227. \[
  228. K(\bx,\bx') = \langle \Phi(\bx),\Phi(\bx') \rangle.
  229. \]
  230. Viceversa, any kernel function can be represented by a feature map in
  231. this manner, establishing an equivalence.
  232. So far, all solvers in VLFeat assume that the feature map $\Psi(\bx)$
  233. can be explicitly computed. Although classically kernels were
  234. introduced to generalize solvers to non-linear SVMs for which a
  235. feature map *cannot* be computed (e.g. for a Gaussian kernel the
  236. feature map is infinite dimensional), in practice using explicit
  237. feature representations allow to use much faster solvers, so it makes
  238. sense to *reverse* this process.
  239. */
  240. /**
  241. <!-- ------------------------------------------------------------- -->
  242. @page svm-advanced Advanced SVM topics
  243. @tableofcontents
  244. <!-- ------------------------------------------------------------- -->
  245. This page discusses advanced SVM topics. For an introduction to SVMs,
  246. please refer to @ref svm and @ref svm-fundamentals.
  247. <!-- ------------------------------------------------------------- -->
  248. @section svm-loss-functions Loss functions
  249. <!-- ------------------------------------------------------------- -->
  250. The SVM formulation given in @ref svm-fundamentals uses the
  251. hinge loss, which is only one of a variety of loss functions that
  252. are often used for SVMs. More in general, one
  253. can consider the objective
  254. @f{equation}{
  255. E(\bw) = \frac{\lambda}{2} \left\| \bw \right\|^2 + \frac{1}{n} \sum_{i=1}^n \ell_i(\langle \bw,\bx\rangle).
  256. \label{e:svm-primal}
  257. @f}
  258. where the loss $\ell_i(z)$ is a convex function of the scalar variable
  259. $z$. Losses differ by: (i) their purpose (some are suitable for
  260. classification, other for regression), (ii) their smoothness (which
  261. usually affects how quickly the SVM objective function can be
  262. minimized), and (iii) their statistical interpretation (for example
  263. the logistic loss can be used to learn logistic models).
  264. Concrete examples are the:
  265. <table>
  266. <tr>
  267. <td>Name</td>
  268. <td>Loss $\ell_i(z)$</td>
  269. <td>Description</td>
  270. </tr>
  271. <tr>
  272. <td>Hinge</td>
  273. <td>$\max\{0, 1-y_i z\}$</td>
  274. <td>The standard SVM loss function.</td>
  275. </tr>
  276. <tr>
  277. <td>Square hinge</td>
  278. <td>$\max\{0, 1-y_i z\}^2$</td>
  279. <td>The standard SVM loss function, but squared. This version is
  280. smoother and may yield numerically easier problems.</td>
  281. </tr>
  282. <tr>
  283. <td>Square or l2</td>
  284. <td>$(y_i - z)^2$</td>
  285. <td>This loss yields the ridge regression model (l2 regularised least
  286. square).</td>
  287. </tr>
  288. <tr>
  289. <td>Linear or l1</td>
  290. <td>$|y_i - z|$</td>
  291. <td>Another loss suitable for regression, usually more robust but
  292. harder to optimize than the squared one.</td>
  293. </tr>
  294. <tr>
  295. <td>Insensitive l1</td>
  296. <td>$\max\{0, |y_i - z| - \epsilon\}$.</td>
  297. <td>This is a variant of the previous loss, proposed in the original
  298. Support Vector Regression formulation. Differently from the previous
  299. two losses, the insensitivity may yield to a sparse selection of
  300. support vectors.</td>
  301. </tr>
  302. <tr>
  303. <td>Logistic</td>
  304. <td>$\log(1 + e^{-y_i z})$</td>
  305. <td>This corresponds to regularized logisitc regression. The loss can
  306. be seen as a negative log-likelihood: $\ell_i(z) = -\log P[y_i | z] =
  307. - \log \sigma(y_iz/2)$, where $\sigma(z) = e^z/(1 + e^z)$ is the
  308. sigmoid function, mapping a score $z$ to a probability. The $1/2$
  309. factor in the sigmoid is due to the fact that labels are in $\{-1,1\}$
  310. rather than $\{0,1\}$ as more common for the standard sigmoid
  311. model.</td>
  312. </tr>
  313. </table>
  314. <!-- ------------------------------------------------------------- -->
  315. @section svm-data-abstraction Data abstraction: working with compressed data
  316. <!-- ------------------------------------------------------------- -->
  317. VLFeat learning algorithms (SGD and SDCA) access the data by means of
  318. only two operations:
  319. - *inner product*: computing the inner product between the model and
  320. a data vector, i.e. $\langle \bw, \bx \rangle$.
  321. - *accumulation*: summing a data vector to the model, i.e. $\bw
  322. \leftarrow \bw + \beta \bx$.
  323. VLFeat learning algorithms are *parameterized* in these two
  324. operations. As a consequence, the data can be stored in any format
  325. suitable to the user (e.g. dense matrices, sparse matrices,
  326. block-sparse matrices, disk caches, and so on) provided that these two
  327. operations can be implemented efficiently. Differently from the data,
  328. however, the model vector $\bw$ is represented simply as a dense array
  329. of doubles. This choice is adequate in almost any case.
  330. A particularly useful aspect of this design choice is that the
  331. training data can be store in *compressed format* (for example by
  332. using product quantization (PQ)). Furthermore, higher-dimensional
  333. encodings such as the homogeneous kernel map (@ref homkermap) and the
  334. intersection kernel map can be *computed on the fly*. Such techniques
  335. are very important when dealing with GBs of data.
  336. <!-- ------------------------------------------------------------- -->
  337. @section svm-dual-problem Dual problem
  338. <!-- ------------------------------------------------------------- -->
  339. In optimization, the *dual objective* $D(\balpha)$ of the SVM
  340. objective $E(\bw)$ is of great interest. To obtain the dual objective,
  341. one starts by approximating each loss term from below by a family of planes:
  342. \[
  343. \ell_i(z) = \sup_{u} (u z - \ell_i^*(u) ),
  344. \qquad
  345. \ell_i^*(u) = \sup_{z} (z u - \ell_i(z) )
  346. \]
  347. where $\ell_i^*(u)$ is the *dual conjugate* of the loss and gives the
  348. intercept of each approximating plane as a function of the slope. When
  349. the loss function is convex, the approximation is in fact exact. Examples
  350. include:
  351. <table>
  352. <tr>
  353. <td>Name</td>
  354. <td>Loss $\ell_i(z)$</td>
  355. <td>Conjugate loss $\ell_i^*(u)$</td>
  356. </tr>
  357. <tr>
  358. <td>Hinge</td>
  359. <td>$\max\{0, 1-y_i z\}$</td>
  360. <td>\[
  361. \ell_i^*(u) =
  362. \begin{cases}
  363. y_i u, & -1 \leq y_i u \leq 0, \\
  364. +\infty, & \text{otherwise}
  365. \end{cases}
  366. \]</td>
  367. </tr>
  368. <tr>
  369. <td>Square hinge</td>
  370. <td>$\max\{0, 1-y_i z\}^2$</td>
  371. <td>\[\ell_i^*(u) =
  372. \begin{cases}
  373. y_i u + \frac{u^2}{4}, & y_i u \leq 0, \\
  374. +\infty, & \text{otherwise} \\
  375. \end{cases}\]</td>
  376. </tr>
  377. <tr>
  378. <td>Linear or l1</td>
  379. <td>$|y_i - z|$</td>
  380. <td>\[\ell_i^*(u) =
  381. \begin{cases}
  382. y_i u, & -1 \leq y_i u \leq 1, \\
  383. +\infty, & \text{otherwise} \\
  384. \end{cases}\]</td>
  385. </tr>
  386. <tr>
  387. <td>Square or l2</td>
  388. <td>$(y_i - z)^2$</td>
  389. <td>\[\ell_i^*(u)=y_iu + \frac{u^2}{4}\]</td>
  390. </tr>
  391. <tr>
  392. <td>Insensitive l1</td>
  393. <td>$\max\{0, |y_i - z| - \epsilon\}$.</td>
  394. <td></td>
  395. </tr>
  396. <tr>
  397. <td>Logistic</td>
  398. <td>$\log(1 + e^{-y_i z})$</td>
  399. <td>\[\ell_i^*(u) =
  400. \begin{cases}
  401. (1+u) \log(1+u) - u \log(-u), & -1 \leq y_i u \leq 0, \\
  402. +\infty, & \text{otherwise} \\
  403. \end{cases}\]
  404. </td>
  405. </tr>
  406. </table>
  407. Since each plane $- z \alpha_i - \ell^*_i(-\alpha_i) \leq \ell_i(z)$
  408. bounds the loss from below, by substituting in $E(\bw)$ one can write
  409. a lower bound for the SVM objective
  410. \[
  411. F(\bw,\balpha) = \frac{\lambda}{2} \|\bw\|^2 -
  412. \frac{1}{n}\sum_{i=1}^n (\bw^\top \bx_i\alpha_i + \ell_i^*(-\alpha_i))
  413. \leq E(\bw).
  414. \]
  415. for each setting of the *dual variables* $\alpha_i$. The dual
  416. objective function $D(\balpha)$ is obtained by minimizing the lower
  417. bound $F(\bw,\balpha)$ w.r.t. to $\bw$:
  418. \[
  419. D(\balpha) = \inf_{\bw} F(\bw,\balpha) \leq E(\bw).
  420. \]
  421. The minimizer and the dual objective are now easy to find:
  422. \[
  423. \boxed{\displaystyle
  424. \bw(\balpha) =
  425. \frac{1}{\lambda n}
  426. \sum_{i=1}^n \bx_i \alpha_i = \frac{1}{\lambda n} X\balpha,
  427. \quad
  428. D(\balpha) = - \frac{1}{2\lambda n^2} \balpha^\top X^\top X \balpha +
  429. \frac{1}{n} \sum_{i=1}^n - \ell_i^*(-\alpha_i)
  430. }
  431. \]
  432. where $X = [\bx_1, \dots, \bx_n]$ is the data matrix. Since the dual
  433. is uniformly smaller than the primal, one has the *duality gap* bound:
  434. \[
  435. D(\balpha) \leq P(\bw^*) \leq P(\bw(\balpha))
  436. \]
  437. This bound can be used to evaluate how far off $\bw(\balpha)$ is from
  438. the primal minimizer $\bw^*$. In fact, due to convexity, this bound
  439. can be shown to be zero when $\balpha^*$ is the dual maximizer (strong
  440. duality):
  441. \[
  442. D(\balpha^*) = P(\bw^*) = P(\bw(\balpha^*)),
  443. \quad \bw^* = \bw(\balpha^*).
  444. \]
  445. <!-- ------------------------------------------------------------- -->
  446. @section svm-C Parametrization in C
  447. <!-- ------------------------------------------------------------- -->
  448. Often a slightly different form of the SVM objective is considered,
  449. where a parameter $C$ is used to scale the loss instead of the regularizer:
  450. \[
  451. E_C(\bw) = \frac{1}{2} \|\bw\|^2 + C \sum_{i=1}^n \ell_i(\langle \bx_i, \bw\rangle)
  452. \]
  453. This and the objective function $E(\bw)$ in $\lambda$ are equivalent
  454. (proportional) if
  455. \[
  456. \lambda = \frac{1}{nC},
  457. \qquad C = \frac{1}{n\lambda}.
  458. \] up to an overall scaling factor to the problem.
  459. **/
  460. /**
  461. <!-- ------------------------------------------------------------- -->
  462. @page svm-sdca Stochastic Dual Coordinate Ascent
  463. @tableofcontents
  464. <!-- ------------------------------------------------------------- -->
  465. This page describes the *Stochastic Dual Coordinate Ascent* (SDCA)
  466. linear SVM solver. Please see @ref svm for an overview of VLFeat SVM
  467. support.
  468. SDCA maximizes the dual SVM objective (see @ref svm-dual-problem
  469. for a derivation of this expression):
  470. \[
  471. D(\balpha) = - \frac{1}{2\lambda n^2} \balpha^\top X^\top X \balpha +
  472. \frac{1}{n} \sum_{i=1}^n - \ell_i^*(-\alpha_i)
  473. \]
  474. where $X$ is the data matrix. Recall that the primal parameter
  475. corresponding to a given setting of the dual variables is:
  476. \[
  477. \bw(\balpha) = \frac{1}{\lambda n} \sum_{i=1}^n \bx_i \alpha_i = \frac{1}{\lambda n} X\balpha
  478. \]
  479. In its most basic form, the *SDCA algorithm* can be summarized as follows:
  480. - Let $\balpha_0 = 0$.
  481. - Until the duality gap $P(\bw(\balpha_t)) - D(\balpha_t) < \epsilon$
  482. - Pick a dual variable $q$ uniformly at random in $1, \dots, n$.
  483. - Maximize the dual with respect to this variable: $\Delta\alpha_q = \max_{\Delta\alpha_q} D(\balpha_t + \Delta\alpha_q \be_q )$
  484. - Update $\balpha_{t+1} = \balpha_{t} + \be_q \Delta\alpha_q$.
  485. In VLFeat, we partially use the nomenclature from @cite{shwartz13a-dual} and @cite{hsieh08a-dual}.
  486. <!-- ------------------------------------------------------------- -->
  487. @section svm-sdca-dual-max Dual coordinate maximization
  488. <!-- ------------------------------------------------------------- -->
  489. The updated dual objective can be expanded as:
  490. \[
  491. D(\balpha_t + \be_q \Delta\alpha_q) =
  492. \text{const.}
  493. - \frac{1}{2\lambda n^2} \bx_q^\top \bx_q (\Delta\alpha_q)^2
  494. - \frac{1}{n} \bx_q^\top \frac{X\alpha_t}{\lambda n} \Delta\alpha_q
  495. - \frac{1}{n} \ell^*_q(- \alpha_q - \Delta\alpha_q)
  496. \]
  497. This can also be written as
  498. @f{align*}
  499. D(\balpha_t + \be_q \Delta\alpha_q) &\propto
  500. - \frac{A}{2} (\Delta\alpha_q)^2
  501. - B \Delta\alpha_q
  502. - \ell^*_q(- \alpha_q - \Delta\alpha_q),
  503. \\
  504. A &= \frac{1}{\lambda n} \bx_q^\top \bx_q = \frac{1}{\lambda n} \| \bx_q \|^2,
  505. \\
  506. B &= \bx_q^\top \frac{X\balpha_t}{\lambda n} = \bx_q^\top \bw_t.
  507. @f}
  508. Maximizing this quantity in the scalar variable $\Delta\balpha$ is usually
  509. not difficult. It is convenient to store and incrementally
  510. update the model $\bw_t$ after the optimal step $\Delta\balpha$ has been
  511. determined:
  512. \[
  513. \bw_t = \frac{X \balpha_t}{\lambda n},
  514. \quad \bw_{t+1} = \bw_t + \frac{1}{\lambda n }\bx_q \be_q \Delta\alpha_q.
  515. \]
  516. For example, consider the hinge loss as given in @ref svm-advanced :
  517. \[
  518. \ell_q^*(u) =
  519. \begin{cases}
  520. y_q u, & -1 \leq y_q u \leq 0, \\
  521. +\infty, & \text{otherwise}.
  522. \end{cases}
  523. \]
  524. The maximizer $\Delta\alpha_q$ of the update objective must be in the
  525. range where the conjugate loss is not infinite. Ignoring such bounds,
  526. the update can be obtained by setting the derivative of the objective
  527. to zero, obtaining
  528. \[
  529. \tilde {\Delta \alpha_q}= \frac{y_q - B}{A}.
  530. \]
  531. Note that $B$ is simply current score associated by the SVM to
  532. the sample $\bx_q$. Incorporating the constraint $-1 \leq - y_q
  533. (\alpha_q + \Delta \alpha_q) \leq 0$,
  534. i.e. $0 \leq y_q (\alpha_q + \Delta \alpha_q) \leq 1$, one obtains the update
  535. \[
  536. \Delta\alpha_q = y_q \max\{0, \min\{1, y_q (\tilde {\Delta\alpha_q } + \alpha_q)\}\} - \alpha_q.
  537. \]
  538. <!-- ------------------------------------------------------------ --->
  539. @section svm-sdca-details Implementation details
  540. <!-- ------------------------------------------------------------ --->
  541. Rather than visiting points completely at random, VLFeat SDCA follows
  542. the best practice of visiting all the points at every epoch (pass
  543. through the data), changing the order of the visit randomly by picking
  544. every time a new random permutation.
  545. **/
  546. /**
  547. <!-- ------------------------------------------------------------- -->
  548. @page svm-sgd Stochastic Gradient Descent
  549. @tableofcontents
  550. <!-- ------------------------------------------------------------- -->
  551. This page describes the *Stochastic Gradient Descent* (SGD) linear SVM
  552. solver. SGD minimizes directly the primal SVM objective (see @ref svm):
  553. \[
  554. E(\bw) = \frac{\lambda}{2} \left\| \bw \right\|^2 + \frac{1}{n} \sum_{i=1}^n
  555. \ell_i(\langle \bw,\bx\rangle)
  556. \]
  557. Firts, rewrite the objective as the average
  558. \[
  559. E(\bw) = \frac{1}{n} \sum_{i=1}^n E_i(\bw),
  560. \quad
  561. E_i(\bw) = \frac{\lambda}{2} \left\| \bw \right\|^2 + \ell_i(\langle \bw,\bx\rangle).
  562. \]
  563. Then SGD performs gradient steps by considering at each iteration
  564. one term $E_i(\bw)$ selected at random from this average.
  565. In its most basic form, the algorithm is:
  566. - Start with $\bw_0 = 0$.
  567. - For $t=1,2,\dots T$:
  568. - Sample one index $i$ in $1,\dots,n$ uniformly at random.
  569. - Compute a subgradient $\bg_t$ of $E_i(\bw)$ at $\bw_t$.
  570. - Compute the learning rate $\eta_t$.
  571. - Update $\bw_{t+1} = \bw_t - \eta_t \bg_t$.
  572. Provided that the learning rate $\eta_t$ is chosen correctly, this
  573. simple algorithm is guaranteed to converge to the minimizer $\bw^*$ of
  574. $E$.
  575. <!-- ------------------------------------------------------------- -->
  576. @section svm-sgd-convergence Convergence and speed
  577. <!-- ------------------------------------------------------------- -->
  578. The goal of the SGD algorithm is to bring the *primal suboptimality*
  579. below a threshold $\epsilon_P$:
  580. \[
  581. E(\bw_t) - E(\bw^*) \leq \epsilon_P.
  582. \]
  583. If the learning rate $\eta_t$ is selected appropriately, SGD can be
  584. shown to converge properly. For example,
  585. @cite{shalev-shwartz07pegasos} show that, since $E(\bw)$ is
  586. $\lambda$-strongly convex, then using the learning rate
  587. \[
  588. \boxed{\eta_t = \frac{1}{\lambda t}}
  589. \]
  590. guarantees that the algorithm reaches primal-suboptimality $\epsilon_P$ in
  591. \[
  592. \tilde O\left( \frac{1}{\lambda \epsilon_P} \right).
  593. \]
  594. iterations. This particular SGD variant is sometimes known as PEGASOS
  595. @cite{shalev-shwartz07pegasos} and is the version implemented in
  596. VLFeat.
  597. The *convergence speed* is not sufficient to tell the *learning speed*,
  598. i.e. how quickly an algorithm can learn an SVM that performs optimally
  599. on the test set. The following two observations
  600. can be used to link convergence speed to learning speed:
  601. - The regularizer strength is often heuristically selected to be
  602. inversely proportional to the number of training samples: $\lambda =
  603. \lambda_0 /n$. This reflects the fact that with more training data
  604. the prior should count less.
  605. - The primal suboptimality $\epsilon_P$ should be about the same as
  606. the estimation error of the SVM primal. This estimation error is due
  607. to the finite training set size and can be shown to be of the order
  608. of $1/\lambda n = 1 / \lambda_0$.
  609. Under these two assumptions, PEGASOS can learn a linear SVM in time
  610. $\tilde O(n)$, which is *linear in the number of training
  611. examples*. This fares much better with $O(n^2)$ or worse of non-linear
  612. SVM solvers.
  613. <!-- ------------------------------------------------------------- -->
  614. @section svm-sgd-bias The bias term
  615. <!-- ------------------------------------------------------------- -->
  616. Adding a bias $b$ to the SVM scoring function $\langle \bw, \bx
  617. \rangle +b$ is done, as explained in @ref svm-bias, by appending a
  618. constant feature $B$ (the *bias multiplier*) to the data vectors $\bx$
  619. and a corresponding weight element $w_b$ to the weight vector $\bw$,
  620. so that $b = B w_b$ As noted, the bias multiplier should be
  621. relatively large in order to avoid shrinking the bias towards zero,
  622. but small to make the optimization stable. In particular, setting $B$
  623. to zero learns an unbiased SVM (::vl_svm_set_bias_multiplier).
  624. To counter instability caused by a large bias multiplier, the learning
  625. rate of the bias is slowed down by multiplying the overall learning
  626. rate $\eta_t$ by a bias-specific rate coefficient
  627. (::vl_svm_set_bias_learning_rate).
  628. As a rule of thumb, if the data vectors $\bx$ are $l^2$ normalized (as
  629. they typically should for optimal performance), then a reasonable bias
  630. multiplier is in the range 1 to 10 and a reasonable bias learning rate
  631. is somewhere in the range of the inverse of that (in this manner the
  632. two parts of the extended feature vector $(\bx, B)$ are balanced).
  633. <!-- ------------------------------------------------------------- -->
  634. @section svm-sgd-starting-iteration Adjusting the learning rate
  635. <!-- ------------------------------------------------------------- -->
  636. Initially, the learning rate $\eta_t = 1/\lambda t$ is usually too
  637. fast: as usually $\lambda \ll 1$, $\eta_1 \gg 1$. But this is clearly
  638. excessive (for example, without a loss term, the best learning rate at
  639. the first iteration is simply $\eta_1=1$, as this nails the optimum in
  640. one step). Thus, the learning rate formula is modified to be $\eta_t =
  641. 1 / \lambda (t + t_0)$, where $t_0 \approx 2/\lambda$, which is
  642. equivalent to start $t_0$ iterations later. In this manner $\eta_1
  643. \approx 1/2$.
  644. <!-- ------------------------------------------------------------ --->
  645. @subsection svm-sgd-warm-start Warm start
  646. <!-- ------------------------------------------------------------ --->
  647. Starting from a given model $\bw$ is easy in SGD as the optimization
  648. runs in the primal. However, the starting iteration index $t$ should
  649. also be advanced for a warm start, as otherwise the initial setting of
  650. $\bw$ is rapidly forgot (::vl_svm_set_model, ::vl_svm_set_bias,
  651. ::vl_svm_set_iteration_number).
  652. <!-- ------------------------------------------------------------- -->
  653. @section svm-sgd-details Implementation details
  654. <!-- ------------------------------------------------------------- -->
  655. @par "Random sampling of points"
  656. Rather than visiting points completely at random, VLFeat SDCA follows
  657. the best practice of visiting all the points at every epoch (pass
  658. through the data), changing the order of the visit randomly by picking
  659. every time a new random permutation.
  660. @par "Factored representation"
  661. At each iteration, the SGD algorithm updates the vector $\bw$
  662. (including the additional bias component $w_b$) as $\bw_{t+1}
  663. \leftarrow \bw_t - \lambda \eta_t \bw_t - \eta_t \bg_t$, where
  664. $\eta_t$ is the learning rate. If the subgradient of the loss function
  665. $\bg_t$ is zero at a given iteration, this amounts to simply shrink
  666. $\bw$ towards the origin by multiplying it by the factor $1 - \lambda
  667. \eta_t$. Thus such an iteration can be accelerated significantly by
  668. representing internally $\bw_t = f_t \bu_t$, where $f_t$ is a scaling
  669. factor. Then, the update becomes
  670. \[
  671. f_{t+1} \bu_{t+1}
  672. = f_{t} \bu_{t} - \lambda \eta_t f_{t} \bu_{t} - \eta_t \bg_t
  673. = (1-\lambda \eta_t) f_{t} \bu_{t} - \eta_t \bg_t.
  674. \]
  675. Setting $f_{t+1} = (1-\lambda \eta_t) f_{t}$, this gives the update
  676. equation for $\bu_t$
  677. \[
  678. \bu_{t+1} = \bu_{t} - \frac{\eta_t}{f_{t+1}} \bg_t.
  679. \]
  680. but this step can be skipped whenever $\bg_t$ is equal to zero.
  681. When the bias component has a different learning rate, this scheme
  682. must be adjusted slightly by adding a separated factor for the bias,
  683. but it is otherwise identical.
  684. **/
  685. /*
  686. <!-- ------------------------------------------------------------ --->
  687. @section svm-pegasos PEGASOS
  688. <!-- ------------------------------------------------------------ --->
  689. <!-- ------------------------------------------------------------ --->
  690. @subsection svm-pegasos-algorithm Algorithm
  691. <!-- ------------------------------------------------------------ --->
  692. PEGASOS @cite{shalev-shwartz07pegasos} is a stochastic subgradient
  693. optimizer. At the <em>t</em>-th iteration the algorithm:
  694. - Samples uniformly at random as subset @f$ A_t @f$ of <em>k</em> of
  695. training pairs @f$(x,y)@f$ from the <em>m</em> pairs provided for
  696. training (this subset is called mini batch).
  697. - Computes a subgradient @f$ \nabla_t @f$ of the function @f$ E_t(w) =
  698. \frac{1}{2}\|w\|^2 + \frac{1}{k} \sum_{(x,y) \in A_t} \ell(w;(x,y))
  699. @f$ (this is the SVM objective function restricted to the
  700. minibatch).
  701. - Compute an intermediate weight vector @f$ w_{t+1/2} @f$ by doing a
  702. step @f$ w_{t+1/2} = w_t - \alpha_t \nabla_t @f$ with learning rate
  703. @f$ \alpha_t = 1/(\eta t) @f$ along the subgradient. Note that the
  704. learning rate is inversely proportional to the iteration number.
  705. - Back projects the weight vector @f$ w_{t+1/2} @f$ on the
  706. hypersphere of radius @f$ \sqrt{\lambda} @f$ to obtain the next
  707. model estimate @f$ w_{t+1} @f$:
  708. @f[
  709. w_t = \min\{1, \sqrt{\lambda}/\|w\|\} w_{t+1/2}.
  710. @f]
  711. The hypersphere is guaranteed to contain the optimal weight vector
  712. @f$ w^* @f$.
  713. VLFeat implementation fixes to one the size of the mini batches @f$ k
  714. @f$.
  715. <!-- ------------------------------------------------------------ --->
  716. @subsection svm-pegasos-permutation Permutation
  717. <!-- ------------------------------------------------------------ --->
  718. VLFeat PEGASOS can use a user-defined permutation to decide the order
  719. in which data points are visited (instead of using random
  720. sampling). By specifying a permutation the algorithm is guaranteed to
  721. visit each data point exactly once in each loop. The permutation needs
  722. not to be bijective. This can be used to visit certain data samples
  723. more or less often than others, implicitly reweighting their relative
  724. importance in the SVM objective function. This can be used to balance
  725. the data.
  726. <!-- ------------------------------------------------------------ --->
  727. @subsection svm-pegasos-kernels Non-linear kernels
  728. <!-- ------------------------------------------------------------ --->
  729. PEGASOS can be extended to non-linear kernels, but the algorithm is
  730. not particularly efficient in this setting [1]. When possible, it may
  731. be preferable to work with explicit feature maps.
  732. Let @f$ k(x,y) @f$ be a positive definite kernel. A <em>feature
  733. map</em> is a function @f$ \Psi(x) @f$ such that @f$ k(x,y) = \langle
  734. \Psi(x), \Psi(y) \rangle @f$. Using this representation the non-linear
  735. SVM learning objective function writes:
  736. @f[
  737. \min_{w} \frac{\lambda}{2} \|w\|^2 + \frac{1}{m} \sum_{i=1}^n
  738. \ell(w; (\Psi(x)_i,y_i)).
  739. @f]
  740. Thus the only difference with the linear case is that the feature @f$
  741. \Psi(x) @f$ is used in place of the data @f$ x @f$.
  742. @f$ \Psi(x) @f$ can be learned off-line, for instance by using the
  743. incomplete Cholesky decomposition @f$ V^\top V @f$ of the Gram matrix
  744. @f$ K = [k(x_i,x_j)] @f$ (in this case @f$ \Psi(x_i) @f$ is the
  745. <em>i</em>-th columns of <em>V</em>). Alternatively, for additive
  746. kernels (e.g. intersection, Chi2) the explicit feature map computed by
  747. @ref homkermap.h can be used.
  748. For additive kernels it is also possible to perform the feature
  749. expansion online inside the solver, setting the specific feature map
  750. via ::vl_svmdataset_set_map. This is particular useful to keep the
  751. size of the training data small, when the number of the samples is big
  752. or the memory is limited.
  753. */
  754. #include "svm.h"
  755. #include "mathop.h"
  756. #include <string.h>
  757. struct VlSvm_ {
  758. VlSvmSolverType solver ; /**< SVM solver type. */
  759. vl_size dimension ; /**< Model dimension. */
  760. double * model ; /**< Model ($\bw$ vector). */
  761. double bias ; /**< Bias. */
  762. double biasMultiplier ; /**< Bias feature multiplier. */
  763. /* valid during a run */
  764. double lambda ; /**< Regularizer multiplier. */
  765. void const * data ;
  766. vl_size numData ;
  767. double const * labels ; /**< Data labels. */
  768. double const * weights ; /**< Data weights. */
  769. VlSvmDataset * ownDataset ; /**< Optional owned dataset. */
  770. VlSvmDiagnosticFunction diagnosticFn ;
  771. void * diagnosticFnData ;
  772. vl_size diagnosticFrequency ; /**< Frequency of diagnostic. */
  773. VlSvmLossFunction lossFn ;
  774. VlSvmLossFunction conjugateLossFn ;
  775. VlSvmLossFunction lossDerivativeFn ;
  776. VlSvmDcaUpdateFunction dcaUpdateFn ;
  777. VlSvmInnerProductFunction innerProductFn ;
  778. VlSvmAccumulateFunction accumulateFn ;
  779. vl_size iteration ; /**< Current iterations number. */
  780. vl_size maxNumIterations ; /**< Maximum number of iterations. */
  781. double epsilon ; /**< Stopping threshold. */
  782. /* Book keeping */
  783. VlSvmStatistics statistics ; /**< Statistcs. */
  784. double * scores ;
  785. /* SGD specific */
  786. double biasLearningRate ; /**< Bias learning rate. */
  787. /* SDCA specific */
  788. double * alpha ; /**< Dual variables. */
  789. } ;
  790. /* ---------------------------------------------------------------- */
  791. /** @brief Create a new object with plain data.
  792. ** @param type type of SMV solver.
  793. ** @param data a pointer to a matrix of data.
  794. ** @param dimension dimension of the SVM model.
  795. ** @param numData number of training samples.
  796. ** @param labels training labels.
  797. ** @param lambda regularizer parameter.
  798. ** @return the new object.
  799. **
  800. ** @a data has one column per sample, in @c double format.
  801. ** More advanced inputs can be used with ::vl_svm_new_with_dataset
  802. ** and ::vl_svm_new_with_abstract_data.
  803. **
  804. ** @sa ::vl_svm_delete
  805. **/
  806. VlSvm *
  807. vl_svm_new (VlSvmSolverType type,
  808. double const * data,
  809. vl_size dimension,
  810. vl_size numData,
  811. double const * labels,
  812. double lambda)
  813. {
  814. VlSvmDataset * dataset = vl_svmdataset_new(VL_TYPE_DOUBLE, (void*)data, dimension, numData) ;
  815. VlSvm * self = vl_svm_new_with_dataset (type, dataset, labels, lambda) ;
  816. self->ownDataset = dataset ;
  817. return self ;
  818. }
  819. /** @brief Create a new object with a dataset.
  820. ** @param solver type of SMV solver.
  821. ** @param dataset SVM dataset object
  822. ** @param labels training samples labels.
  823. ** @param lambda regularizer parameter.
  824. ** @return the new object.
  825. ** @sa ::vl_svm_delete
  826. **/
  827. VlSvm *
  828. vl_svm_new_with_dataset (VlSvmSolverType solver,
  829. VlSvmDataset * dataset,
  830. double const * labels,
  831. double lambda)
  832. {
  833. VlSvm * self = vl_svm_new_with_abstract_data (solver,
  834. dataset,
  835. vl_svmdataset_get_dimension(dataset),
  836. vl_svmdataset_get_num_data(dataset),
  837. labels,
  838. lambda) ;
  839. vl_svm_set_data_functions (self,
  840. vl_svmdataset_get_inner_product_function(dataset),
  841. vl_svmdataset_get_accumulate_function(dataset)) ;
  842. return self ;
  843. }
  844. /** @brief Create a new object with abstract data.
  845. ** @param solver type of SMV solver.
  846. ** @param data pointer to the data.
  847. ** @param dimension dimension of the SVM model.
  848. ** @param numData num training samples.
  849. ** @param labels training samples labels.
  850. ** @param lambda regularizer parameter.
  851. ** @return the new object.
  852. **
  853. ** After calling this function, ::vl_svm_set_data_functions *must*
  854. ** be used to setup suitable callbacks for the inner product
  855. ** and accumulation operations (@see svm-data-abstraction).
  856. **
  857. ** @sa ::vl_svm_delete
  858. **/
  859. VlSvm *
  860. vl_svm_new_with_abstract_data (VlSvmSolverType solver,
  861. void * data,
  862. vl_size dimension,
  863. vl_size numData,
  864. double const * labels,
  865. double lambda)
  866. {
  867. VlSvm * self = (VlSvm*)vl_calloc(1,sizeof(VlSvm)) ;
  868. assert(dimension >= 1) ;
  869. assert(numData >= 1) ;
  870. assert(labels) ;
  871. self->solver = solver ;
  872. self->dimension = dimension ;
  873. self->model = 0 ;
  874. self->bias = 0 ;
  875. self->biasMultiplier = 1.0 ;
  876. self->lambda = lambda ;
  877. self->data = data ;
  878. self->numData = numData ;
  879. self->labels = labels ;
  880. self->diagnosticFrequency = numData ;
  881. self->diagnosticFn = 0 ;
  882. self->diagnosticFnData = 0 ;
  883. self->lossFn = vl_svm_hinge_loss ;
  884. self->conjugateLossFn = vl_svm_hinge_conjugate_loss ;
  885. self->lossDerivativeFn = vl_svm_hinge_loss_derivative ;
  886. self->dcaUpdateFn = vl_svm_hinge_dca_update ;
  887. self->innerProductFn = 0 ;
  888. self->accumulateFn = 0 ;
  889. self->iteration = 0 ;
  890. self->maxNumIterations = VL_MAX((double)numData, vl_ceil_f(10.0 / lambda)) ;
  891. self->epsilon = 1e-2 ;
  892. /* SGD */
  893. self->biasLearningRate = 0.01 ;
  894. /* SDCA */
  895. self->alpha = 0 ;
  896. /* allocations */
  897. self->model = (double*)vl_calloc(dimension, sizeof(double)) ;
  898. if (self->model == NULL) goto err_alloc ;
  899. if (self->solver == VlSvmSolverSdca) {
  900. self->alpha = (double*)vl_calloc(self->numData, sizeof(double)) ;
  901. if (self->alpha == NULL) goto err_alloc ;
  902. }
  903. self->scores = (double*)vl_calloc(numData, sizeof(double)) ;
  904. if (self->scores == NULL) goto err_alloc ;
  905. return self ;
  906. err_alloc:
  907. if (self->scores) {
  908. vl_free (self->scores) ;
  909. self->scores = 0 ;
  910. }
  911. if (self->model) {
  912. vl_free (self->model) ;
  913. self->model = 0 ;
  914. }
  915. if (self->alpha) {
  916. vl_free (self->alpha) ;
  917. self->alpha = 0 ;
  918. }
  919. return 0 ;
  920. }
  921. /** @brief Delete object.
  922. ** @param self object.
  923. ** @sa ::vl_svm_new
  924. **/
  925. void
  926. vl_svm_delete (VlSvm * self)
  927. {
  928. if (self->model) {
  929. vl_free (self->model) ;
  930. self->model = 0 ;
  931. }
  932. if (self->alpha) {
  933. vl_free (self->alpha) ;
  934. self->alpha = 0 ;
  935. }
  936. if (self->ownDataset) {
  937. vl_svmdataset_delete(self->ownDataset) ;
  938. self->ownDataset = 0 ;
  939. }
  940. vl_free (self) ;
  941. }
  942. /* ---------------------------------------------------------------- */
  943. /* Setters and getters */
  944. /* ---------------------------------------------------------------- */
  945. /** @brief Set the convergence threshold
  946. ** @param self object
  947. ** @param epsilon threshold (non-negative).
  948. **/
  949. void vl_svm_set_epsilon (VlSvm *self, double epsilon)
  950. {
  951. assert(self) ;
  952. assert(epsilon >= 0) ;
  953. self->epsilon = epsilon ;
  954. }
  955. /** @brief Get the convergence threshold
  956. ** @param self object
  957. ** @return epsilon threshold.
  958. **/
  959. double vl_svm_get_epsilon (VlSvm const *self)
  960. {
  961. assert(self) ;
  962. return self->epsilon ;
  963. }
  964. /** @brief Set the bias learning rate
  965. ** @param self object
  966. ** @param rate bias learning rate (positive).
  967. **
  968. ** This parameter applies only to the SGD solver.
  969. **/
  970. void vl_svm_set_bias_learning_rate (VlSvm *self, double rate)
  971. {
  972. assert(self) ;
  973. assert(rate > 0) ;
  974. self->biasLearningRate = rate ;
  975. }
  976. /** @brief Get the bias leraning rate.
  977. ** @param self object
  978. ** @return bias learning rate.
  979. **/
  980. double vl_svm_get_bias_learning_rate (VlSvm const *self)
  981. {
  982. assert(self) ;
  983. return self->biasLearningRate ;
  984. }
  985. /** @brief Set the bias multiplier.
  986. ** @param self object
  987. ** @param b bias multiplier.
  988. **
  989. ** The *bias multiplier* is the value of the constant feature
  990. ** appended to the data vectors to implement the bias (@ref svm-bias).
  991. **/
  992. void vl_svm_set_bias_multiplier (VlSvm * self, double b)
  993. {
  994. assert(self) ;
  995. assert(b >= 0) ;
  996. self->biasMultiplier = b ;
  997. }
  998. /** @brief Get the bias multiplier.
  999. ** @param self object.
  1000. ** @return bias multiplier.
  1001. **/
  1002. double vl_svm_get_bias_multiplier (VlSvm const * self)
  1003. {
  1004. assert(self) ;
  1005. return self->biasMultiplier ;
  1006. }
  1007. /** @brief Set the current iteratio number.
  1008. ** @param self object.
  1009. ** @param n iteration number.
  1010. **
  1011. ** If called before training,
  1012. ** this can be used with SGD for a warm start, as the net
  1013. ** effect is to slow down the learning rate.
  1014. **/
  1015. void vl_svm_set_iteration_number (VlSvm *self, vl_uindex n)
  1016. {
  1017. assert(self) ;
  1018. self->iteration = n ;
  1019. }
  1020. /** @brief Get the current iteration number.
  1021. ** @param self object.
  1022. ** @return current iteration number.
  1023. **/
  1024. vl_size vl_svm_get_iteration_number (VlSvm const *self)
  1025. {
  1026. assert(self) ;
  1027. return self->iteration ;
  1028. }
  1029. /** @brief Set the maximum number of iterations.
  1030. ** @param self object.
  1031. ** @param n maximum number of iterations.
  1032. **/
  1033. void vl_svm_set_max_num_iterations (VlSvm *self, vl_size n)
  1034. {
  1035. assert(self) ;
  1036. self->maxNumIterations = n ;
  1037. }
  1038. /** @brief Get the maximum number of iterations.
  1039. ** @param self object.
  1040. ** @return maximum number of iterations.
  1041. **/
  1042. vl_size vl_svm_get_max_num_iterations (VlSvm const *self)
  1043. {
  1044. assert(self) ;
  1045. return self->maxNumIterations ;
  1046. }
  1047. /** @brief Set the diagnostic frequency.
  1048. ** @param self object.
  1049. ** @param f diagnostic frequency (@c >= 1).
  1050. **
  1051. ** A diagnostic round (to test for convergence and to printout
  1052. ** information) is performed every @a f iterations.
  1053. **/
  1054. void vl_svm_set_diagnostic_frequency (VlSvm *self, vl_size f)
  1055. {
  1056. assert(self) ;
  1057. assert(f > 0) ;
  1058. self->diagnosticFrequency = f ;
  1059. }
  1060. /** @brief Get the diagnostic frequency.
  1061. ** @param self object.
  1062. ** @return diagnostic frequency.
  1063. **/
  1064. vl_size vl_svm_get_diagnostic_frequency (VlSvm const *self)
  1065. {
  1066. assert(self) ;
  1067. return self->diagnosticFrequency ;
  1068. }
  1069. /** @brief Get the SVM solver type.
  1070. ** @param self object.
  1071. ** @return SVM solver type.
  1072. **/
  1073. VlSvmSolverType vl_svm_get_solver (VlSvm const * self)
  1074. {
  1075. assert(self) ;
  1076. return self->solver ;
  1077. }
  1078. /** @brief Set the regularizer parameter lambda.
  1079. ** @param self object.
  1080. ** @param lambda regularizer parameter.
  1081. **
  1082. ** Note that @a lambda is usually set when calling a
  1083. ** constructor for ::VlSvm as certain parameters, such
  1084. ** as the maximum number of iterations, are tuned accordingly.
  1085. ** This tuning is not performed when @a lambda is changed
  1086. ** using this function.
  1087. **/
  1088. void vl_svm_set_lambda (VlSvm * self, double lambda)
  1089. {
  1090. assert(self) ;
  1091. assert(lambda >= 0) ;
  1092. self->lambda = lambda ;
  1093. }
  1094. /** @brief Get the regularizer parameter lambda.
  1095. ** @param self object.
  1096. ** @return diagnostic frequency.
  1097. **/
  1098. double vl_svm_get_lambda (VlSvm const * self)
  1099. {
  1100. assert(self) ;
  1101. return self->lambda ;
  1102. }
  1103. /** @brief Set the data weights.
  1104. ** @param self object.
  1105. ** @param weights data weights.
  1106. **
  1107. ** @a weights must be an array of non-negative weights.
  1108. ** The loss of each data point is multiplied by the corresponding
  1109. ** weight.
  1110. **
  1111. ** Set @a weights to @c NULL to weight the data uniformly by 1 (default).
  1112. **
  1113. ** Note that the @a weights array is *not* copied and must be valid
  1114. ** througout the object lifetime (unless it is replaced).
  1115. **/
  1116. void vl_svm_set_weights (VlSvm * self, double const *weights)
  1117. {
  1118. assert(self) ;
  1119. self->weights = weights ;
  1120. }
  1121. /** @brief Get the data weights.
  1122. ** @param self object.
  1123. ** @return data weights.
  1124. **/
  1125. double const *vl_svm_get_weights (VlSvm const * self)
  1126. {
  1127. assert(self) ;
  1128. return self->weights ;
  1129. }
  1130. /* ---------------------------------------------------------------- */
  1131. /* Get data */
  1132. /* ---------------------------------------------------------------- */
  1133. /** @brief Get the model dimenison.
  1134. ** @param self object.
  1135. ** @return model dimension.
  1136. **
  1137. ** This is the dimensionality of the weight vector $\bw$.
  1138. **/
  1139. vl_size vl_svm_get_dimension (VlSvm *self)
  1140. {
  1141. assert(self) ;
  1142. return self->dimension ;
  1143. }
  1144. /** @brief Get the number of data samples.
  1145. ** @param self object.
  1146. ** @return model number of data samples
  1147. **
  1148. ** This is the dimensionality of the weight vector $\bw$.
  1149. **/
  1150. vl_size vl_svm_get_num_data (VlSvm *self)
  1151. {
  1152. assert(self) ;
  1153. return self->numData ;
  1154. }
  1155. /** @brief Get the SVM model.
  1156. ** @param self object.
  1157. ** @return model.
  1158. **
  1159. ** This is the weight vector $\bw$.
  1160. **/
  1161. double const * vl_svm_get_model (VlSvm const *self)
  1162. {
  1163. assert(self) ;
  1164. return self->model ;
  1165. }
  1166. /** @brief Set the SVM model.
  1167. ** @param self object.
  1168. ** @param model model.
  1169. **
  1170. ** The function *copies* the content of the vector @a model to the
  1171. ** internal model buffer. This operation can be used for warm start
  1172. ** with the SGD algorithm, but has undefined effect with the SDCA algorithm.
  1173. **/
  1174. void vl_svm_set_model (VlSvm *self, double const *model)
  1175. {
  1176. assert(self) ;
  1177. assert(model) ;
  1178. memcpy(self->model, model, sizeof(double) * vl_svm_get_dimension(self)) ;
  1179. }
  1180. /** @brief Set the SVM bias.
  1181. ** @param self object.
  1182. ** @param b bias.
  1183. **
  1184. ** The function set the internal representation of the SVM bias to
  1185. ** be equal to @a b (the bias multiplier
  1186. ** is applied). The same remark
  1187. ** that applies to ::vl_svm_set_model applies here too.
  1188. **/
  1189. void vl_svm_set_bias (VlSvm *self, double b)
  1190. {
  1191. assert(self);
  1192. if (self->biasMultiplier) {
  1193. self->bias = b / self->biasMultiplier ;
  1194. }
  1195. }
  1196. /** @brief Get the value of the bias.
  1197. ** @param self object.
  1198. ** @return bias $b$.
  1199. **
  1200. ** The value of the bias returned already include the effect of
  1201. ** bias mutliplier.
  1202. **/
  1203. double vl_svm_get_bias (VlSvm const *self)
  1204. {
  1205. assert(self) ;
  1206. return self->bias * self->biasMultiplier ;
  1207. }
  1208. /** @brief Get the solver statistics.
  1209. ** @param self object.
  1210. ** @return statistics.
  1211. **/
  1212. VlSvmStatistics const * vl_svm_get_statistics (VlSvm const *self)
  1213. {
  1214. assert(self) ;
  1215. return &self->statistics ;
  1216. }
  1217. /** @brief Get the scores of the data points.
  1218. ** @param self object.
  1219. ** @return vector of scores.
  1220. **
  1221. ** After training or during the diagnostic callback,
  1222. ** this function can be used to retrieve the scores
  1223. ** of the points, i.e. $\langle \bx_i, \bw \rangle + b$.
  1224. **/
  1225. double const * vl_svm_get_scores (VlSvm const *self)
  1226. {
  1227. return self->scores ;
  1228. }
  1229. /* ---------------------------------------------------------------- */
  1230. /* Callbacks */
  1231. /* ---------------------------------------------------------------- */
  1232. /** @typedef VlSvmDiagnosticFunction
  1233. ** @brief SVM diagnostic function pointer.
  1234. ** @param svm is an instance of ::VlSvm .
  1235. **/
  1236. /** @typedef VlSvmAccumulateFunction
  1237. ** @brief Pointer to a function that adds to @a model the data point at
  1238. ** position @a element multiplied by the constant @a multiplier.
  1239. **/
  1240. /** @typedef VlSvmInnerProductFunction
  1241. ** @brief Pointer to a function that defines the inner product
  1242. ** between the data point at position @a element and the SVM model
  1243. **/
  1244. /** @brief Set the diagnostic function callback
  1245. ** @param self object.
  1246. ** @param f diagnostic function pointer.
  1247. ** @param data pointer to data used by the diagnostic function.
  1248. **/
  1249. void
  1250. vl_svm_set_diagnostic_function (VlSvm *self, VlSvmDiagnosticFunction f, void *data) {
  1251. self->diagnosticFn = f ;
  1252. self->diagnosticFnData = data ;
  1253. }
  1254. /** @brief Set the data functions.
  1255. ** @param self object.
  1256. ** @param inner inner product function.
  1257. ** @param acc accumulate function.
  1258. **
  1259. ** See @ref svm-data-abstraction.
  1260. **/
  1261. void vl_svm_set_data_functions (VlSvm *self, VlSvmInnerProductFunction inner, VlSvmAccumulateFunction acc)
  1262. {
  1263. assert(self) ;
  1264. assert(inner) ;
  1265. assert(acc) ;
  1266. self->innerProductFn = inner ;
  1267. self->accumulateFn = acc ;
  1268. }
  1269. /** @brief Set the loss function callback.
  1270. ** @param self object.
  1271. ** @param f loss function callback.
  1272. **
  1273. ** Note that setting up a loss requires specifying more than just one
  1274. ** callback. See @ref svm-loss-functions for details.
  1275. **/
  1276. void vl_svm_set_loss_function (VlSvm *self, VlSvmLossFunction f)
  1277. {
  1278. assert(self) ;
  1279. self->lossFn = f ;
  1280. }
  1281. /** @brief Set the loss derivative function callback.
  1282. ** @copydetails vl_svm_set_loss_function.
  1283. **/
  1284. void vl_svm_set_loss_derivative_function (VlSvm *self, VlSvmLossFunction f)
  1285. {
  1286. assert(self) ;
  1287. self->lossDerivativeFn = f ;
  1288. }
  1289. /** @brief Set the conjugate loss function callback.
  1290. ** @copydetails vl_svm_set_loss_function.
  1291. **/
  1292. void vl_svm_set_conjugate_loss_function (VlSvm *self, VlSvmLossFunction f)
  1293. {
  1294. assert(self) ;
  1295. self->conjugateLossFn = f ;
  1296. }
  1297. /** @brief Set the DCA update function callback.
  1298. ** @copydetails vl_svm_set_loss_function.
  1299. **/
  1300. void vl_svm_set_dca_update_function (VlSvm *self, VlSvmDcaUpdateFunction f)
  1301. {
  1302. assert(self) ;
  1303. self->dcaUpdateFn = f ;
  1304. }
  1305. /** @brief Set the loss function to one of the default types.
  1306. ** @param self object.
  1307. ** @param loss type of loss function.
  1308. ** @sa @ref svm-loss-functions.
  1309. **/
  1310. void
  1311. vl_svm_set_loss (VlSvm *self, VlSvmLossType loss)
  1312. {
  1313. #define SETLOSS(x,y) \
  1314. case VlSvmLoss ## x: \
  1315. vl_svm_set_loss_function(self, vl_svm_ ## y ## _loss) ; \
  1316. vl_svm_set_loss_derivative_function(self, vl_svm_ ## y ## _loss_derivative) ; \
  1317. vl_svm_set_conjugate_loss_function(self, vl_svm_ ## y ## _conjugate_loss) ; \
  1318. vl_svm_set_dca_update_function(self, vl_svm_ ## y ## _dca_update) ; \
  1319. break;
  1320. switch (loss) {
  1321. SETLOSS(Hinge, hinge) ;
  1322. SETLOSS(Hinge2, hinge2) ;
  1323. SETLOSS(L1, l1) ;
  1324. SETLOSS(L2, l2) ;
  1325. SETLOSS(Logistic, logistic) ;
  1326. default:
  1327. assert(0) ;
  1328. }
  1329. }
  1330. /* ---------------------------------------------------------------- */
  1331. /* Pre-defined losses */
  1332. /* ---------------------------------------------------------------- */
  1333. /** @typedef VlSvmLossFunction
  1334. ** @brief SVM loss function pointer.
  1335. ** @param inner inner product between sample and model $\bw^\top \bx$.
  1336. ** @param label sample label $y$.
  1337. ** @return value of the loss.
  1338. **
  1339. ** The interface is the same for a loss function, its derivative,
  1340. ** or the conjugate loss.
  1341. **
  1342. ** @sa @ref svm-fundamentals
  1343. **/
  1344. /** @typedef VlSvmDcaUpdateFunction
  1345. ** @brief SVM SDCA update function pointer.
  1346. ** @param alpha current value of the dual variable.
  1347. ** @param inner inner product $\bw^\top \bx$ of the sample with the SVM model.
  1348. ** @param norm2 normalization factor $\|\bx\|^2/\lambda n$.
  1349. ** @param label label $y$ of the sample.
  1350. ** @return incremental update $\Delta\alpha$ of the dual variable.
  1351. **
  1352. ** @sa @ref svm-sdca
  1353. **/
  1354. /** @brief SVM hinge loss
  1355. ** @copydetails VlSvmLossFunction */
  1356. double
  1357. vl_svm_hinge_loss (double inner, double label)
  1358. {
  1359. return VL_MAX(1 - label * inner, 0.0);
  1360. }
  1361. /** @brief SVM hinge loss derivative
  1362. ** @copydetails VlSvmLossFunction */
  1363. double
  1364. vl_svm_hinge_loss_derivative (double inner, double label)
  1365. {
  1366. if (label * inner < 1.0) {
  1367. return - label ;
  1368. } else {
  1369. return 0.0 ;
  1370. }
  1371. }
  1372. /** @brief SVM hinge loss conjugate
  1373. ** @param u dual variable.
  1374. ** @param label label value.
  1375. ** @return conjugate loss.
  1376. **/
  1377. double
  1378. vl_svm_hinge_conjugate_loss (double u, double label) {
  1379. double z = label * u ;
  1380. if (-1 <= z && z <= 0) {
  1381. return label * u ;
  1382. } else {
  1383. return VL_INFINITY_D ;
  1384. }
  1385. }
  1386. /** @brief SVM hinge loss DCA update
  1387. ** @copydetails VlSvmDcaUpdateFunction */
  1388. double
  1389. vl_svm_hinge_dca_update (double alpha, double inner, double norm2, double label) {
  1390. double palpha = (label - inner) / norm2 + alpha ;
  1391. return label * VL_MAX(0, VL_MIN(1, label * palpha)) - alpha ;
  1392. }
  1393. /** @brief SVM square hinge loss
  1394. ** @copydetails VlSvmLossFunction */
  1395. double
  1396. vl_svm_hinge2_loss (double inner,double label)
  1397. {
  1398. double z = VL_MAX(1 - label * inner, 0.0) ;
  1399. return z*z ;
  1400. }
  1401. /** @brief SVM square hinge loss derivative
  1402. ** @copydetails VlSvmLossFunction */
  1403. double
  1404. vl_svm_hinge2_loss_derivative (double inner, double label)
  1405. {
  1406. if (label * inner < 1.0) {
  1407. return 2 * (inner - label) ;
  1408. } else {
  1409. return 0 ;
  1410. }
  1411. }
  1412. /** @brief SVM square hinge loss conjugate
  1413. ** @copydetails vl_svm_hinge_conjugate_loss */
  1414. double
  1415. vl_svm_hinge2_conjugate_loss (double u, double label) {
  1416. if (label * u <= 0) {
  1417. return (label + u/4) * u ;
  1418. } else {
  1419. return VL_INFINITY_D ;
  1420. }
  1421. }
  1422. /** @brief SVM square hinge loss DCA update
  1423. ** @copydetails VlSvmDcaUpdateFunction */
  1424. double
  1425. vl_svm_hinge2_dca_update (double alpha, double inner, double norm2, double label) {
  1426. double palpha = (label - inner - 0.5*alpha) / (norm2 + 0.5) + alpha ;
  1427. return label * VL_MAX(0, label * palpha) - alpha ;
  1428. }
  1429. /** @brief SVM l1 loss
  1430. ** @copydetails VlSvmLossFunction */
  1431. double
  1432. vl_svm_l1_loss (double inner,double label)
  1433. {
  1434. return vl_abs_d(label - inner) ;
  1435. }
  1436. /** @brief SVM l1 loss derivative
  1437. ** @copydetails VlSvmLossFunction */
  1438. double
  1439. vl_svm_l1_loss_derivative (double inner, double label)
  1440. {
  1441. if (label > inner) {
  1442. return - 1.0 ;
  1443. } else {
  1444. return + 1.0 ;
  1445. }
  1446. }
  1447. /** @brief SVM l1 loss conjugate
  1448. ** @copydetails vl_svm_hinge_conjugate_loss */
  1449. double
  1450. vl_svm_l1_conjugate_loss (double u, double label) {
  1451. if (vl_abs_d(u) <= 1) {
  1452. return label*u ;
  1453. } else {
  1454. return VL_INFINITY_D ;
  1455. }
  1456. }
  1457. /** @brief SVM l1 loss DCA update
  1458. ** @copydetails VlSvmDcaUpdateFunction */
  1459. double
  1460. vl_svm_l1_dca_update (double alpha, double inner, double norm2, double label) {
  1461. if (vl_abs_d(alpha) <= 1) {
  1462. double palpha = (label - inner) / norm2 + alpha ;
  1463. return VL_MAX(-1.0, VL_MIN(1.0, palpha)) - alpha ;
  1464. } else {
  1465. return VL_INFINITY_D ;
  1466. }
  1467. }
  1468. /** @brief SVM l2 loss
  1469. ** @copydetails VlSvmLossFunction */
  1470. double
  1471. vl_svm_l2_loss (double inner,double label)
  1472. {
  1473. double z = label - inner ;
  1474. return z*z ;
  1475. }
  1476. /** @brief SVM l2 loss derivative
  1477. ** @copydetails VlSvmLossFunction */
  1478. double
  1479. vl_svm_l2_loss_derivative (double inner, double label)
  1480. {
  1481. return - 2 * (label - inner) ;
  1482. }
  1483. /** @brief SVM l2 loss conjugate
  1484. ** @copydetails vl_svm_hinge_conjugate_loss */
  1485. double
  1486. vl_svm_l2_conjugate_loss (double u, double label) {
  1487. return (label + u/4) * u ;
  1488. }
  1489. /** @brief SVM l2 loss DCA update
  1490. ** @copydetails VlSvmDcaUpdateFunction */
  1491. double
  1492. vl_svm_l2_dca_update (double alpha, double inner, double norm2, double label) {
  1493. return (label - inner - 0.5*alpha) / (norm2 + 0.5) ;
  1494. }
  1495. /** @brief SVM l2 loss
  1496. ** @copydetails VlSvmLossFunction */
  1497. double
  1498. vl_svm_logistic_loss (double inner,double label)
  1499. {
  1500. double z = label * inner ;
  1501. if (z >= 0) {
  1502. return log(1.0 + exp(-z)) ;
  1503. } else {
  1504. return -z + log(exp(z) + 1.0) ;
  1505. }
  1506. }
  1507. /** @brief SVM l2 loss derivative
  1508. ** @copydetails VlSvmLossFunction */
  1509. double
  1510. vl_svm_logistic_loss_derivative (double inner, double label)
  1511. {
  1512. double z = label * inner ;
  1513. double t = 1 / (1 + exp(-z)) ; /* this is stable for z << 0 too */
  1514. return label * (t - 1) ; /* = -label exp(-z) / (1 + exp(-z)) */
  1515. }
  1516. VL_INLINE double xlogx(double x)
  1517. {
  1518. if (x <= 1e-10) return 0 ;
  1519. return x*log(x) ;
  1520. }
  1521. /** @brief SVM l2 loss conjugate
  1522. ** @copydetails vl_svm_hinge_conjugate_loss */
  1523. double
  1524. vl_svm_logistic_conjugate_loss (double u, double label) {
  1525. double z = label * u ;
  1526. if (-1 <= z && z <= 0) {
  1527. return xlogx(-z) + xlogx(1+z) ;
  1528. } else {
  1529. return VL_INFINITY_D ;
  1530. }
  1531. }
  1532. /** @brief SVM l2 loss DCA update
  1533. ** @copydetails VlSvmDcaUpdateFunction */
  1534. double
  1535. vl_svm_logistic_dca_update (double alpha, double inner, double norm2, double label) {
  1536. /*
  1537. The goal is to solve the problem
  1538. min_delta A/2 delta^2 + B delta + l*(-alpha - delta|y), -1 <= - y (alpha+delta) <= 0
  1539. where A = norm2, B = inner, and y = label. To simplify the notation, we set
  1540. f(beta) = beta * log(beta) + (1 - beta) * log(1 - beta)
  1541. where beta = y(alpha + delta) such that
  1542. l*(-alpha - delta |y) = f(beta).
  1543. Hence 0 <= beta <= 1, delta = + y beta - alpha. Substituting
  1544. min_beta A/2 beta^2 + y (B - A alpha) beta + f(beta) + const
  1545. The Newton step is then given by
  1546. beta = beta - (A beta + y(B - A alpha) + df) / (A + ddf).
  1547. However, the function is singluar for beta=0 and beta=1 (infinite
  1548. first and second order derivatives). Since the function is monotonic
  1549. (second derivarive always strictly greater than zero) and smooth,
  1550. we canuse bisection to find the zero crossing of the first derivative.
  1551. Once one is sufficiently close to the optimum, a one or two Newton
  1552. steps are sufficien to land on it with excellent accuracy.
  1553. */
  1554. double df, ddf, der, dder ;
  1555. vl_index t ;
  1556. /* bisection */
  1557. double beta1 = 0 ;
  1558. double beta2 = 1 ;
  1559. double beta = 0.5 ;
  1560. for (t = 0 ; t < 5 ; ++t) {
  1561. df = log(beta) - log(1-beta) ;
  1562. der = norm2 * beta + label * (inner - norm2*alpha) + df ;
  1563. if (der >= 0) {
  1564. beta2 = beta ;
  1565. } else {
  1566. beta1 = beta ;
  1567. }
  1568. beta = 0.5 * (beta1 + beta2) ;
  1569. }
  1570. #if 1
  1571. /* a final Newton step, but not too close to the singularities */
  1572. for (t = 0 ; (t < 2) & (beta > VL_EPSILON_D) & (beta < 1-VL_EPSILON_D) ; ++t) {
  1573. df = log(beta) - log(1-beta) ;
  1574. ddf = 1 / (beta * (1-beta)) ;
  1575. der = norm2 * beta + label * (inner - norm2*alpha) + df ;
  1576. dder = norm2 + ddf ;
  1577. beta -= der / dder ;
  1578. beta = VL_MAX(0, VL_MIN(1, beta)) ;
  1579. }
  1580. #endif
  1581. return label * beta - alpha ;
  1582. }
  1583. /* ---------------------------------------------------------------- */
  1584. /** @internal @brief Update SVM statistics
  1585. ** @param self object.
  1586. **/
  1587. void _vl_svm_update_statistics (VlSvm *self)
  1588. {
  1589. vl_size i, k ;
  1590. double inner, p ;
  1591. memset(&self->statistics, 0, sizeof(VlSvmStatistics)) ;
  1592. self->statistics.regularizer = self->bias * self->bias ;
  1593. for (i = 0; i < self->dimension; i++) {
  1594. self->statistics.regularizer += self->model[i] * self->model[i] ;
  1595. }
  1596. self->statistics.regularizer *= self->lambda * 0.5 ;
  1597. for (k = 0; k < self->numData ; k++) {
  1598. p = (self->weights) ? self->weights[k] : 1.0 ;
  1599. if (p <= 0) continue ;
  1600. inner = self->innerProductFn(self->data, k, self->model) ;
  1601. inner += self->bias * self->biasMultiplier ;
  1602. self->scores[k] = inner ;
  1603. self->statistics.loss += p * self->lossFn(inner, self->labels[k]) ;
  1604. if (self->solver == VlSvmSolverSdca) {
  1605. self->statistics.dualLoss -= p * self->conjugateLossFn(- self->alpha[k] / p, self->labels[k]) ;
  1606. }
  1607. }
  1608. self->statistics.loss /= self->numData ;
  1609. self->statistics.objective = self->statistics.regularizer + self->statistics.loss ;
  1610. if (self->solver == VlSvmSolverSdca) {
  1611. self->statistics.dualLoss /= self->numData ;
  1612. self->statistics.dualObjective = - self->statistics.regularizer + self->statistics.dualLoss ;
  1613. self->statistics.dualityGap = self->statistics.objective - self->statistics.dualObjective ;
  1614. }
  1615. }
  1616. /* ---------------------------------------------------------------- */
  1617. /* Evaluate rather than solve */
  1618. /* ---------------------------------------------------------------- */
  1619. void _vl_svm_evaluate (VlSvm *self)
  1620. {
  1621. double startTime = vl_get_cpu_time () ;
  1622. _vl_svm_update_statistics (self) ;
  1623. self->statistics.elapsedTime = vl_get_cpu_time() - startTime ;
  1624. self->statistics.iteration = 0 ;
  1625. self->statistics.epoch = 0 ;
  1626. self->statistics.status = VlSvmStatusConverged ;
  1627. if (self->diagnosticFn) {
  1628. self->diagnosticFn(self, self->diagnosticFnData) ;
  1629. }
  1630. }
  1631. /* ---------------------------------------------------------------- */
  1632. /* Stochastic Dual Coordinate Ascent Solver */
  1633. /* ---------------------------------------------------------------- */
  1634. void _vl_svm_sdca_train (VlSvm *self)
  1635. {
  1636. double * norm2 ;
  1637. vl_index * permutation ;
  1638. vl_uindex i, t ;
  1639. double inner, delta, multiplier, p ;
  1640. double startTime = vl_get_cpu_time () ;
  1641. VlRand * rand = vl_get_rand() ;
  1642. norm2 = (double*) vl_calloc(self->numData, sizeof(double));
  1643. permutation = (vl_index*)vl_calloc(self->numData, sizeof(vl_index)) ;
  1644. {
  1645. double * buffer = (double*)vl_calloc(self->dimension, sizeof(double)) ;
  1646. for (i = 0 ; i < (unsigned)self->numData; i++) {
  1647. double n2 ;
  1648. permutation [i] = i ;
  1649. memset(buffer, 0, self->dimension * sizeof(double)) ;
  1650. self->accumulateFn (self->data, i, buffer, 1) ;
  1651. n2 = self->innerProductFn (self->data, i, buffer) ;
  1652. n2 += self->biasMultiplier * self->biasMultiplier ;
  1653. norm2[i] = n2 / (self->lambda * self->numData) ;
  1654. }
  1655. vl_free(buffer) ;
  1656. }
  1657. for (t = 0 ; 1 ; ++t) {
  1658. if (t % self->numData == 0) {
  1659. /* once a new epoch is reached (all data have been visited),
  1660. change permutation */
  1661. vl_rand_permute_indexes(rand, permutation, self->numData) ;
  1662. }
  1663. /* pick a sample and compute update */
  1664. i = permutation[t % self->numData] ;
  1665. p = (self->weights) ? self->weights[i] : 1.0 ;
  1666. if (p > 0) {
  1667. inner = self->innerProductFn(self->data, i, self->model) ;
  1668. inner += self->bias * self->biasMultiplier ;
  1669. delta = p * self->dcaUpdateFn(self->alpha[i] / p, inner, p * norm2[i], self->labels[i]) ;
  1670. } else {
  1671. delta = 0 ;
  1672. }
  1673. /* apply update */
  1674. if (delta != 0) {
  1675. self->alpha[i] += delta ;
  1676. multiplier = delta / (self->numData * self->lambda) ;
  1677. self->accumulateFn(self->data,i,self->model,multiplier) ;
  1678. self->bias += self->biasMultiplier * multiplier;
  1679. }
  1680. /* call diagnostic occasionally */
  1681. if ((t + 1) % self->diagnosticFrequency == 0 || t + 1 == self->maxNumIterations) {
  1682. _vl_svm_update_statistics (self) ;
  1683. self->statistics.elapsedTime = vl_get_cpu_time() - startTime ;
  1684. self->statistics.iteration = t ;
  1685. self->statistics.epoch = t / self->numData ;
  1686. self->statistics.status = VlSvmStatusTraining ;
  1687. if (self->statistics.dualityGap < self->epsilon) {
  1688. self->statistics.status = VlSvmStatusConverged ;
  1689. }
  1690. else if (t + 1 == self->maxNumIterations) {
  1691. self->statistics.status = VlSvmStatusMaxNumIterationsReached ;
  1692. }
  1693. if (self->diagnosticFn) {
  1694. self->diagnosticFn(self, self->diagnosticFnData) ;
  1695. }
  1696. if (self->statistics.status != VlSvmStatusTraining) {
  1697. break ;
  1698. }
  1699. }
  1700. } /* next iteration */
  1701. vl_free (norm2) ;
  1702. vl_free (permutation) ;
  1703. }
  1704. /* ---------------------------------------------------------------- */
  1705. /* Stochastic Gradient Descent Solver */
  1706. /* ---------------------------------------------------------------- */
  1707. void _vl_svm_sgd_train (VlSvm *self)
  1708. {
  1709. vl_index * permutation ;
  1710. double * scores ;
  1711. double * previousScores ;
  1712. vl_uindex i, t, k ;
  1713. double inner, gradient, rate, biasRate, p ;
  1714. double factor = 1.0 ;
  1715. double biasFactor = 1.0 ; /* to allow slower bias learning rate */
  1716. vl_index t0 = VL_MAX(2, vl_ceil_d(1.0 / self->lambda)) ;
  1717. //t0=2 ;
  1718. double startTime = vl_get_cpu_time () ;
  1719. VlRand * rand = vl_get_rand() ;
  1720. permutation = (vl_index*)vl_calloc(self->numData, sizeof(vl_index)) ;
  1721. scores = (double*)vl_calloc(self->numData * 2, sizeof(double)) ;
  1722. previousScores = scores + self->numData ;
  1723. for (i = 0 ; i < (unsigned)self->numData; i++) {
  1724. permutation [i] = i ;
  1725. previousScores [i] = - VL_INFINITY_D ;
  1726. }
  1727. /*
  1728. We store the w vector as the product fw (factor * model).
  1729. We also use a different factor for the bias: biasFactor * biasMultiplier
  1730. to enable a slower learning rate for the bias.
  1731. Given this representation, it is easy to carry the two key operations:
  1732. * Inner product: <fw,x> = f <w,x>
  1733. * Model update: fp wp = fw - rate * lambda * w - rate * g
  1734. = f(1 - rate * lambda) w - rate * g
  1735. Thus the update equations are:
  1736. fp = f(1 - rate * lambda), and
  1737. wp = w + rate / fp * g ;
  1738. * Realization of the scaling factor. Before the statistics function
  1739. is called, or training finishes, the factor (and biasFactor)
  1740. are explicitly applied to the model and the bias.
  1741. */
  1742. for (t = 0 ; 1 ; ++t) {
  1743. if (t % self->numData == 0) {
  1744. /* once a new epoch is reached (all data have been visited),
  1745. change permutation */
  1746. vl_rand_permute_indexes(rand, permutation, self->numData) ;
  1747. }
  1748. /* pick a sample and compute update */
  1749. i = permutation[t % self->numData] ;
  1750. p = (self->weights) ? self->weights[i] : 1.0 ;
  1751. p = VL_MAX(0.0, p) ; /* we assume non-negative weights, so this is just for robustness */
  1752. inner = factor * self->innerProductFn(self->data, i, self->model) ;
  1753. inner += biasFactor * (self->biasMultiplier * self->bias) ;
  1754. gradient = p * self->lossDerivativeFn(inner, self->labels[i]) ;
  1755. previousScores[i] = scores[i] ;
  1756. scores[i] = inner ;
  1757. /* apply update */
  1758. rate = 1.0 / (self->lambda * (t + t0)) ;
  1759. biasRate = rate * self->biasLearningRate ;
  1760. factor *= (1.0 - self->lambda * rate) ;
  1761. biasFactor *= (1.0 - self->lambda * biasRate) ;
  1762. /* debug: realize the scaling factor all the times */
  1763. /*
  1764. for (k = 0 ; k < self->dimension ; ++k) self->model[k] *= factor ;
  1765. self->bias *= biasFactor;
  1766. factor = 1.0 ;
  1767. biasFactor = 1.0 ;
  1768. */
  1769. if (gradient != 0) {
  1770. self->accumulateFn(self->data, i, self->model, - gradient * rate / factor) ;
  1771. self->bias += self->biasMultiplier * (- gradient * biasRate / biasFactor) ;
  1772. }
  1773. /* call diagnostic occasionally */
  1774. if ((t + 1) % self->diagnosticFrequency == 0 || t + 1 == self->maxNumIterations) {
  1775. /* realize factor before computing statistics or completing training */
  1776. for (k = 0 ; k < self->dimension ; ++k) self->model[k] *= factor ;
  1777. self->bias *= biasFactor;
  1778. factor = 1.0 ;
  1779. biasFactor = 1.0 ;
  1780. _vl_svm_update_statistics (self) ;
  1781. for (k = 0 ; k < self->numData ; ++k) {
  1782. double delta = scores[k] - previousScores[k] ;
  1783. self->statistics.scoresVariation += delta * delta ;
  1784. }
  1785. self->statistics.scoresVariation = sqrt(self->statistics.scoresVariation) / self->numData ;
  1786. self->statistics.elapsedTime = vl_get_cpu_time() - startTime ;
  1787. self->statistics.iteration = t ;
  1788. self->statistics.epoch = t / self->numData ;
  1789. self->statistics.status = VlSvmStatusTraining ;
  1790. if (self->statistics.scoresVariation < self->epsilon) {
  1791. self->statistics.status = VlSvmStatusConverged ;
  1792. }
  1793. else if (t + 1 == self->maxNumIterations) {
  1794. self->statistics.status = VlSvmStatusMaxNumIterationsReached ;
  1795. }
  1796. if (self->diagnosticFn) {
  1797. self->diagnosticFn(self, self->diagnosticFnData) ;
  1798. }
  1799. if (self->statistics.status != VlSvmStatusTraining) {
  1800. break ;
  1801. }
  1802. }
  1803. } /* next iteration */
  1804. vl_free (scores) ;
  1805. vl_free (permutation) ;
  1806. }
  1807. /* ---------------------------------------------------------------- */
  1808. /* Dispatcher */
  1809. /* ---------------------------------------------------------------- */
  1810. /** @brief Run the SVM solver
  1811. ** @param self object.
  1812. **
  1813. ** The data on which the SVM operates is passed upon the cration of
  1814. ** the ::VlSvm object. This function runs a solver to learn a
  1815. ** corresponding model. See @ref svm-starting.
  1816. **/
  1817. void vl_svm_train (VlSvm * self)
  1818. {
  1819. assert (self) ;
  1820. switch (self->solver) {
  1821. case VlSvmSolverSdca:
  1822. _vl_svm_sdca_train(self) ;
  1823. break ;
  1824. case VlSvmSolverSgd:
  1825. _vl_svm_sgd_train(self) ;
  1826. break ;
  1827. case VlSvmSolverNone:
  1828. _vl_svm_evaluate(self) ;
  1829. break ;
  1830. default:
  1831. assert(0) ;
  1832. }
  1833. }