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.

1709 lines
52 KiB

8 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file gmm.c
  2. ** @brief Gaussian Mixture Models - Implementation
  3. ** @author David Novotny
  4. ** @author Andrea Vedaldi
  5. **/
  6. /*
  7. Copyright (C) 2013 David Novotny and Andrea Vedaldi.
  8. All rights reserved.
  9. This file is part of the VLFeat library and is made available under
  10. the terms of the BSD license (see the COPYING file).
  11. */
  12. /**
  13. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  14. @page gmm Gaussian Mixture Models (GMM)
  15. @author David Novotny
  16. @author Andrea Vedaldi
  17. @tableofcontents
  18. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  19. @ref gmm.h is an implementation of *Gaussian Mixture Models* (GMMs).
  20. The main functionality provided by this module is learning GMMs from
  21. data by maximum likelihood. Model optimization uses the Expectation
  22. Maximization (EM) algorithm @cite{dempster77maximum}. The
  23. implementation supports @c float or @c double data types, is
  24. parallelized, and is tuned to work reliably and effectively on
  25. datasets of visual features. Stability is obtained in part by
  26. regularizing and restricting the parameters of the GMM.
  27. @ref gmm-starting demonstreates how to use the C API to compute the FV
  28. representation of an image. For further details refer to:
  29. - @subpage gmm-fundamentals
  30. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  31. @section gmm-starting Getting started
  32. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  33. In order to use @ref gmm.h to learn a GMM from training data, create a
  34. new ::VlGMM object instance, set the parameters as desired, and run
  35. the training code. The following example learns @c numClusters
  36. Gaussian components from @c numData vectors of dimension @c dimension
  37. and storage class @c float using at most 100 EM iterations:
  38. @code
  39. float * means ;
  40. float * covariances ;
  41. float * priors ;
  42. float * posteriors ;
  43. double loglikelihood ;
  44. // create a new instance of a GMM object for float data
  45. gmm = vl_gmm_new (VL_TYPE_FLOAT, dimension, numClusters) ;
  46. // set the maximum number of EM iterations to 100
  47. vl_gmm_set_max_num_iterations (gmm, 100) ;
  48. // set the initialization to random selection
  49. vl_gmm_set_initialization (gmm,VlGMMRand);
  50. // cluster the data, i.e. learn the GMM
  51. vl_gmm_cluster (gmm, data, numData);
  52. // get the means, covariances, and priors of the GMM
  53. means = vl_gmm_get_means(gmm);
  54. covariances = vl_gmm_get_covariances(gmm);
  55. priors = vl_gmm_get_priors(gmm);
  56. // get loglikelihood of the estimated GMM
  57. loglikelihood = vl_gmm_get_loglikelihood(gmm) ;
  58. // get the soft assignments of the data points to each cluster
  59. posteriors = vl_gmm_get_posteriors(gmm) ;
  60. @endcode
  61. @note ::VlGMM assumes that the covariance matrices of the GMM are
  62. diagonal. This reduces significantly the number of parameters to learn
  63. and is usually an acceptable compromise in vision applications. If the
  64. data is significantly correlated, it can be beneficial to de-correlate
  65. it by PCA rotation or projection in pre-processing.
  66. ::vl_gmm_get_loglikelihood is used to get the final loglikelihood of
  67. the estimated mixture, ::vl_gmm_get_means and ::vl_gmm_get_covariances
  68. to obtain the means and the diagonals of the covariance matrices of
  69. the estimated Gaussian modes, and ::vl_gmm_get_posteriors to get the
  70. posterior probabilities that a given point is associated to each of
  71. the modes (soft assignments).
  72. The learning algorithm, which uses EM, finds a local optimum of the
  73. objective function. Therefore the initialization is crucial in
  74. obtaining a good model, measured in term of the final
  75. loglikelihood. ::VlGMM supports a few methods (use
  76. ::vl_gmm_set_initialization to choose one) as follows:
  77. Method | ::VlGMMInitialization enumeration | Description
  78. ----------------------|-----------------------------------------|-----------------------------------------------
  79. Random initialization | ::VlGMMRand | Random initialization of the mixture parameters
  80. KMeans | ::VlGMMKMeans | Initialization of the mixture parameters using ::VlKMeans
  81. Custom | ::VlGMMCustom | User specified initialization
  82. Note that in the case of ::VlGMMKMeans initialization, an object of
  83. type ::VlKMeans object must be created and passed to the ::VlGMM
  84. instance (see @ref kmeans to see how to correctly set up this object).
  85. When a user wants to use the ::VlGMMCustom method, the initial means,
  86. covariances and priors have to be specified using the
  87. ::vl_gmm_set_means, ::vl_gmm_set_covariances and ::vl_gmm_set_priors
  88. methods.
  89. **/
  90. /**
  91. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  92. @page gmm-fundamentals GMM fundamentals
  93. @tableofcontents
  94. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  95. A *Gaussian Mixture Model* (GMM) is a mixture of $K$ multivariate
  96. Gaussian distributions. In order to sample from a GMM, one samples
  97. first the component index $k \in \{1,\dots,K\}$ with *prior
  98. probability* $\pi_k$, and then samples the vector $\bx \in
  99. \mathbb{R}^d$ from the $k$-th Gaussian distribution
  100. $p(\bx|\mu_k,\Sigma_k)$. Here $\mu_k$ and $\Sigma_k$ are respectively
  101. the *mean* and *covariance* of the distribution. The GMM is completely
  102. specified by the parameters $\Theta=\{\pi_k,\mu_k,\Sigma_k; k =
  103. 1,\dots,K\}$
  104. The density $p(\bx|\Theta)$ induced on the training data is obtained
  105. by marginalizing the component selector $k$, obtaining
  106. \[
  107. p(\bx|\Theta)
  108. = \sum_{k=1}^{K} \pi_k p( \bx_i |\mu_k,\Sigma_k),
  109. \qquad
  110. p( \bx |\mu_k,\Sigma_k)
  111. =
  112. \frac{1}{\sqrt{(2\pi)^d\det\Sigma_k}}
  113. \exp\left[
  114. -\frac{1}{2} (\bx-\mu_k)^\top\Sigma_k^{-1}(\bx-\mu_k)
  115. \right].
  116. \]
  117. Learning a GMM to fit a dataset $X=(\bx_1, \dots, \bx_n)$ is usually
  118. done by maximizing the log-likelihood of the data:
  119. @f[
  120. \ell(\Theta;X)
  121. = E_{\bx\sim\hat p} [ \log p(\bx|\Theta) ]
  122. = \frac{1}{n}\sum_{i=1}^{n} \log \sum_{k=1}^{K} \pi_k p(\bx_i|\mu_k, \Sigma_k)
  123. @f]
  124. where $\hat p$ is the empirical distribution of the data. An algorithm
  125. to solve this problem is introduced next.
  126. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  127. @section gmm-em Learning a GMM by expectation maximization
  128. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  129. The direct maximization of the log-likelihood function of a GMM is
  130. difficult due to the fact that the assignments of points to Gaussian
  131. mode is not observable and, as such, must be treated as a latent
  132. variable.
  133. Usually, GMMs are learned by using the *Expectation Maximization* (EM)
  134. algorithm @cite{dempster77maximum}. Consider in general the problem of
  135. estimating to the maximum likelihood a distribution $p(x|\Theta) =
  136. \int p(x,h|\Theta)\,dh$, where $x$ is a measurement, $h$ is a *latent
  137. variable*, and $\Theta$ are the model parameters. By introducing an
  138. auxiliary distribution $q(h|x)$ on the latent variable, one can use
  139. Jensen inequality to obtain the following lower bound on the
  140. log-likelihood:
  141. @f{align*}
  142. \ell(\Theta;X) =
  143. E_{x\sim\hat p} \log p(x|\Theta)
  144. &= E_{x\sim\hat p} \log \int p(x,h|\Theta) \,dh \\
  145. &= E_{x\sim\hat p} \log \int \frac{p(x,h|\Theta)}{q(h|x)} q(h|x)\,dh \\
  146. &\geq E_{x\sim\hat p} \int q(h) \log \frac{p(x,h|\Theta)}{q(h|x)}\,dh \\
  147. &= E_{(x,q) \sim q(h|x) \hat p(x)} \log p(x,h|\Theta) -
  148. E_{(x,q) \sim q(h|x) \hat p(x)} \log q(h|x)
  149. @f}
  150. The first term of the last expression is the log-likelihood of the
  151. model where both the $x$ and $h$ are observed and joinlty distributed
  152. as $q(x|h)\hat p(x)$; the second term is the a average entropy of the
  153. latent variable, which does not depend on $\Theta$. This lower bound
  154. is maximized and becomes tight by setting $q(h|x) = p(h|x,\Theta)$ to
  155. be the posterior distribution on the latent variable $h$ (given the
  156. current estimate of the parameters $\Theta$). In fact:
  157. \[
  158. E_{x \sim \hat p} \log p(x|\Theta)
  159. =
  160. E_{(x,h) \sim p(h|x,\Theta) \hat p(x)}\left[ \log \frac{p(x,h|\Theta)}{p(h|x,\Theta)} \right]
  161. =
  162. E_{(x,h) \sim p(h|x,\Theta) \hat p(x)} [ \log p(x|\Theta) ]
  163. =
  164. \ell(\Theta;X).
  165. \]
  166. EM alternates between updating the latent variable auxiliary
  167. distribution $q(h|x) = p(h|x,\Theta_t)$ (*expectation step*) given the
  168. current estimate of the parameters $\Theta_t$, and then updating the
  169. model parameters $\Theta_{t+1}$ by maximizing the log-likelihood lower
  170. bound derived (*maximization step*). The simplification is that in the
  171. maximization step both $x$ and $h$ are now ``observed'' quantities.
  172. This procedure converges to a local optimum of the model
  173. log-likelihood.
  174. @subsection gmm-expectation-step Expectation step
  175. In the case of a GMM, the latent variables are the point-to-cluster
  176. assignments $k_i, i=1,\dots,n$, one for each of $n$ data points. The
  177. auxiliary distribution $q(k_i|\bx_i) = q_{ik}$ is a matrix with $n
  178. \times K$ entries. Each row $q_{i,:}$ can be thought of as a vector of
  179. soft assignments of the data points $\bx_i$ to each of the Gaussian
  180. modes. Setting $q_{ik} = p(k_i | \bx_i, \Theta)$ yields
  181. \[
  182. q_{ik} =
  183. \frac
  184. {\pi_k p(\bx_i|\mu_k,\Sigma_k)}
  185. {\sum_{l=1}^K \pi_l p(\bx_i|\mu_l,\Sigma_l)}
  186. \]
  187. where the Gaussian density $p(\bx_i|\mu_k,\Sigma_k)$ was given above.
  188. One important point to keep in mind when these probabilities are
  189. computed is the fact that the Gaussian densities may attain very low
  190. values and underflow in a vanilla implementation. Furthermore, VLFeat
  191. GMM implementation restricts the covariance matrices to be
  192. diagonal. In this case, the computation of the determinant of
  193. $\Sigma_k$ reduces to computing the trace of the matrix and the
  194. inversion of $\Sigma_k$ could be obtained by inverting the elements on
  195. the diagonal of the covariance matrix.
  196. @subsection gmm-maximization-step Maximization step
  197. The M step estimates the parameters of the Gaussian mixture components
  198. and the prior probabilities $\pi_k$ given the auxiliary distribution
  199. on the point-to-cluster assignments computed in the E step. Since all
  200. the variables are now ``observed'', the estimate is quite simple. For
  201. example, the mean $\mu_k$ of a Gaussian mode is obtained as the mean
  202. of the data points assigned to it (accounting for the strength of the
  203. soft assignments). The other quantities are obtained in a similar
  204. manner, yielding to:
  205. @f{align*}
  206. \mu_k &= { { \sum_{i=1}^n q_{ik} \bx_{i} } \over { \sum_{i=1}^n q_{ik} } },
  207. \\
  208. \Sigma_k &= { { \sum_{i=1}^n { q_{ik} (\bx_{i} - \mu_{k}) {(\bx_{i} - \mu_{k})}^T } } \over { \sum_{i=1}^n q_{ik} } },
  209. \\
  210. \pi_k &= { \sum_{i=1}^n { q_{ik} } \over { \sum_{i=1}^n \sum_{l=1}^K q_{il} } }.
  211. @f}
  212. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  213. @section gmm-fundamentals-init Initialization algorithms
  214. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  215. The EM algorithm is a local optimization method. As such, the quality
  216. of the solution strongly depends on the quality of the initial values
  217. of the parameters (i.e. of the locations and shapes of the Gaussian
  218. modes).
  219. @ref gmm.h supports the following cluster initialization algorithms:
  220. - <b>Random data points.</b> (::vl_gmm_init_with_rand_data) This method
  221. sets the means of the modes by sampling at random a corresponding
  222. number of data points, sets the covariance matrices of all the modes
  223. are to the covariance of the entire dataset, and sets the prior
  224. probabilities of the Gaussian modes to be uniform. This
  225. initialization method is the fastest, simplest, as well as the one
  226. most likely to end in a bad local minimum.
  227. - <b>KMeans initialization</b> (::vl_gmm_init_with_kmeans) This
  228. method uses KMeans to pre-cluster the points. It then sets the means
  229. and covariances of the Gaussian distributions the sample means and
  230. covariances of each KMeans cluster. It also sets the prior
  231. probabilities to be proportional to the mass of each cluster. In
  232. order to use this initialization method, a user can specify an
  233. instance of ::VlKMeans by using the function
  234. ::vl_gmm_set_kmeans_init_object, or let ::VlGMM create one
  235. automatically.
  236. Alternatively, one can manually specify a starting point
  237. (::vl_gmm_set_priors, ::vl_gmm_set_means, ::vl_gmm_set_covariances).
  238. **/
  239. #include "gmm.h"
  240. #include <stdio.h>
  241. #include <stdlib.h>
  242. #include <string.h>
  243. #ifdef _OPENMP
  244. #include <omp.h>
  245. #endif
  246. #ifndef VL_DISABLE_SSE2
  247. #include "mathop_sse2.h"
  248. #endif
  249. #ifndef VL_DISABLE_AVX
  250. #include "mathop_avx.h"
  251. #endif
  252. /* ---------------------------------------------------------------- */
  253. #ifndef VL_GMM_INSTANTIATING
  254. /* ---------------------------------------------------------------- */
  255. #define VL_GMM_MIN_VARIANCE 1e-6
  256. #define VL_GMM_MIN_POSTERIOR 1e-2
  257. #define VL_GMM_MIN_PRIOR 1e-6
  258. struct _VlGMM
  259. {
  260. vl_type dataType ; /**< Data type. */
  261. vl_size dimension ; /**< Data dimensionality. */
  262. vl_size numClusters ; /**< Number of clusters */
  263. vl_size numData ; /**< Number of last time clustered data points. */
  264. vl_size maxNumIterations ; /**< Maximum number of refinement iterations. */
  265. vl_size numRepetitions ; /**< Number of clustering repetitions. */
  266. int verbosity ; /**< Verbosity level. */
  267. void * means; /**< Means of Gaussian modes. */
  268. void * covariances; /**< Diagonals of covariance matrices of Gaussian modes. */
  269. void * priors; /**< Weights of Gaussian modes. */
  270. void * posteriors; /**< Probabilities of correspondences of points to clusters. */
  271. double * sigmaLowBound ; /**< Lower bound on the diagonal covariance values. */
  272. VlGMMInitialization initialization; /**< Initialization option */
  273. VlKMeans * kmeansInit; /**< Kmeans object for initialization of gaussians */
  274. double LL ; /**< Current solution loglikelihood */
  275. vl_bool kmeansInitIsOwner; /**< Indicates whether a user provided the kmeans initialization object */
  276. } ;
  277. /* ---------------------------------------------------------------- */
  278. /* Life-cycle */
  279. /* ---------------------------------------------------------------- */
  280. static void
  281. _vl_gmm_prepare_for_data (VlGMM* self, vl_size numData)
  282. {
  283. if (self->numData < numData) {
  284. vl_free(self->posteriors) ;
  285. self->posteriors = vl_malloc(vl_get_type_size(self->dataType) * numData * self->numClusters) ;
  286. }
  287. self->numData = numData ;
  288. }
  289. /** @brief Create a new GMM object
  290. ** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE)
  291. ** @param dimension dimension of the data.
  292. ** @param numComponents number of Gaussian mixture components.
  293. ** @return new GMM object instance.
  294. **/
  295. VlGMM *
  296. vl_gmm_new (vl_type dataType, vl_size dimension, vl_size numComponents)
  297. {
  298. vl_index i ;
  299. vl_size size = vl_get_type_size(dataType) ;
  300. VlGMM * self = (VlGMM*)vl_calloc(1, sizeof(VlGMM)) ;
  301. self->dataType = dataType;
  302. self->numClusters = numComponents ;
  303. self->numData = 0;
  304. self->dimension = dimension ;
  305. self->initialization = VlGMMRand;
  306. self->verbosity = 0 ;
  307. self->maxNumIterations = 50;
  308. self->numRepetitions = 1;
  309. self->sigmaLowBound = NULL ;
  310. self->priors = NULL ;
  311. self->covariances = NULL ;
  312. self->means = NULL ;
  313. self->posteriors = NULL ;
  314. self->kmeansInit = NULL ;
  315. self->kmeansInitIsOwner = VL_FALSE;
  316. self->priors = vl_calloc (numComponents, size) ;
  317. self->means = vl_calloc (numComponents * dimension, size) ;
  318. self->covariances = vl_calloc (numComponents * dimension, size) ;
  319. self->sigmaLowBound = (double*) vl_calloc (dimension, sizeof(double)) ;
  320. for (i = 0 ; i < (unsigned)self->dimension ; ++i) { self->sigmaLowBound[i] = 1e-4 ; }
  321. return self ;
  322. }
  323. /** @brief Reset state
  324. ** @param self object.
  325. **
  326. ** The function reset the state of the GMM object. It deletes
  327. ** any stored posterior and other internal state variables.
  328. **/
  329. void
  330. vl_gmm_reset (VlGMM * self)
  331. {
  332. if (self->posteriors) {
  333. vl_free(self->posteriors) ;
  334. self->posteriors = NULL ;
  335. self->numData = 0 ;
  336. }
  337. if (self->kmeansInit && self->kmeansInitIsOwner) {
  338. vl_kmeans_delete(self->kmeansInit) ;
  339. self->kmeansInit = NULL ;
  340. self->kmeansInitIsOwner = VL_FALSE ;
  341. }
  342. }
  343. /** @brief Deletes a GMM object
  344. ** @param self GMM object instance.
  345. **
  346. ** The function deletes the GMM object instance created
  347. ** by ::vl_gmm_new.
  348. **/
  349. void
  350. vl_gmm_delete (VlGMM * self)
  351. {
  352. if(self->means) vl_free(self->means);
  353. if(self->covariances) vl_free(self->covariances);
  354. if(self->priors) vl_free(self->priors);
  355. if(self->posteriors) vl_free(self->posteriors);
  356. if(self->kmeansInit && self->kmeansInitIsOwner) {
  357. vl_kmeans_delete(self->kmeansInit);
  358. }
  359. vl_free(self);
  360. }
  361. /* ---------------------------------------------------------------- */
  362. /* Getters and setters */
  363. /* ---------------------------------------------------------------- */
  364. /** @brief Get data type
  365. ** @param self object
  366. ** @return data type.
  367. **/
  368. vl_type
  369. vl_gmm_get_data_type (VlGMM const * self)
  370. {
  371. return self->dataType ;
  372. }
  373. /** @brief Get the number of clusters
  374. ** @param self object
  375. ** @return number of clusters.
  376. **/
  377. vl_size
  378. vl_gmm_get_num_clusters (VlGMM const * self)
  379. {
  380. return self->numClusters ;
  381. }
  382. /** @brief Get the number of data points
  383. ** @param self object
  384. ** @return number of data points.
  385. **/
  386. vl_size
  387. vl_gmm_get_num_data (VlGMM const * self)
  388. {
  389. return self->numData ;
  390. }
  391. /** @brief Get the log likelihood of the current mixture
  392. ** @param self object
  393. ** @return loglikelihood.
  394. **/
  395. double
  396. vl_gmm_get_loglikelihood (VlGMM const * self)
  397. {
  398. return self->LL ;
  399. }
  400. /** @brief Get verbosity level
  401. ** @param self object
  402. ** @return verbosity level.
  403. **/
  404. int
  405. vl_gmm_get_verbosity (VlGMM const * self)
  406. {
  407. return self->verbosity ;
  408. }
  409. /** @brief Set verbosity level
  410. ** @param self object
  411. ** @param verbosity verbosity level.
  412. **/
  413. void
  414. vl_gmm_set_verbosity (VlGMM * self, int verbosity)
  415. {
  416. self->verbosity = verbosity ;
  417. }
  418. /** @brief Get means
  419. ** @param self object
  420. ** @return cluster means.
  421. **/
  422. void const *
  423. vl_gmm_get_means (VlGMM const * self)
  424. {
  425. return self->means ;
  426. }
  427. /** @brief Get covariances
  428. ** @param self object
  429. ** @return diagonals of cluster covariance matrices.
  430. **/
  431. void const *
  432. vl_gmm_get_covariances (VlGMM const * self)
  433. {
  434. return self->covariances ;
  435. }
  436. /** @brief Get priors
  437. ** @param self object
  438. ** @return priors of cluster gaussians.
  439. **/
  440. void const *
  441. vl_gmm_get_priors (VlGMM const * self)
  442. {
  443. return self->priors ;
  444. }
  445. /** @brief Get posteriors
  446. ** @param self object
  447. ** @return posterior probabilities of cluster memberships.
  448. **/
  449. void const *
  450. vl_gmm_get_posteriors (VlGMM const * self)
  451. {
  452. return self->posteriors ;
  453. }
  454. /** @brief Get maximum number of iterations
  455. ** @param self object
  456. ** @return maximum number of iterations.
  457. **/
  458. vl_size
  459. vl_gmm_get_max_num_iterations (VlGMM const * self)
  460. {
  461. return self->maxNumIterations ;
  462. }
  463. /** @brief Set maximum number of iterations
  464. ** @param self VlGMM filter.
  465. ** @param maxNumIterations maximum number of iterations.
  466. **/
  467. void
  468. vl_gmm_set_max_num_iterations (VlGMM * self, vl_size maxNumIterations)
  469. {
  470. self->maxNumIterations = maxNumIterations ;
  471. }
  472. /** @brief Get maximum number of repetitions.
  473. ** @param self object
  474. ** @return current number of repretitions for quantization.
  475. **/
  476. vl_size
  477. vl_gmm_get_num_repetitions (VlGMM const * self)
  478. {
  479. return self->numRepetitions ;
  480. }
  481. /** @brief Set maximum number of repetitions
  482. ** @param self object
  483. ** @param numRepetitions maximum number of repetitions.
  484. ** The number of repetitions cannot be smaller than 1.
  485. **/
  486. void
  487. vl_gmm_set_num_repetitions (VlGMM * self, vl_size numRepetitions)
  488. {
  489. assert (numRepetitions >= 1) ;
  490. self->numRepetitions = numRepetitions ;
  491. }
  492. /** @brief Get data dimension
  493. ** @param self object
  494. ** @return data dimension.
  495. **/
  496. vl_size
  497. vl_gmm_get_dimension (VlGMM const * self)
  498. {
  499. return self->dimension ;
  500. }
  501. /** @brief Get initialization algorithm
  502. ** @param self object
  503. ** @return initialization algorithm.
  504. **/
  505. VlGMMInitialization
  506. vl_gmm_get_initialization (VlGMM const * self)
  507. {
  508. return self->initialization ;
  509. }
  510. /** @brief Set initialization algorithm.
  511. ** @param self object
  512. ** @param init initialization algorithm.
  513. **/
  514. void
  515. vl_gmm_set_initialization (VlGMM * self, VlGMMInitialization init)
  516. {
  517. self->initialization = init;
  518. }
  519. /** @brief Get KMeans initialization object.
  520. ** @param self object
  521. ** @return kmeans initialization object.
  522. **/
  523. VlKMeans * vl_gmm_get_kmeans_init_object (VlGMM const * self)
  524. {
  525. return self->kmeansInit;
  526. }
  527. /** @brief Set KMeans initialization object.
  528. ** @param self object
  529. ** @param kmeans initialization KMeans object.
  530. **/
  531. void vl_gmm_set_kmeans_init_object (VlGMM * self, VlKMeans * kmeans)
  532. {
  533. if (self->kmeansInit && self->kmeansInitIsOwner) {
  534. vl_kmeans_delete(self->kmeansInit) ;
  535. }
  536. self->kmeansInit = kmeans;
  537. self->kmeansInitIsOwner = VL_FALSE;
  538. }
  539. /** @brief Get the lower bound on the diagonal covariance values.
  540. ** @param self object
  541. ** @return lower bound on covariances.
  542. **/
  543. double const * vl_gmm_get_covariance_lower_bounds (VlGMM const * self)
  544. {
  545. return self->sigmaLowBound;
  546. }
  547. /** @brief Set the lower bounds on diagonal covariance values.
  548. ** @param self object.
  549. ** @param bounds bounds.
  550. **
  551. ** There is one lower bound per dimension. Use ::vl_gmm_set_covariance_lower_bound
  552. ** to set all of them to a given scalar.
  553. **/
  554. void vl_gmm_set_covariance_lower_bounds (VlGMM * self, double const * bounds)
  555. {
  556. memcpy(self->sigmaLowBound, bounds, sizeof(double) * self->dimension) ;
  557. }
  558. /** @brief Set the lower bounds on diagonal covariance values.
  559. ** @param self object.
  560. ** @param bound bound.
  561. **
  562. ** While there is one lower bound per dimension, this function sets
  563. ** all of them to the specified scalar. Use ::vl_gmm_set_covariance_lower_bounds
  564. ** to set them individually.
  565. **/
  566. void vl_gmm_set_covariance_lower_bound (VlGMM * self, double bound)
  567. {
  568. int i ;
  569. for (i = 0 ; i < (signed)self->dimension ; ++i) {
  570. self->sigmaLowBound[i] = bound ;
  571. }
  572. }
  573. /* ---------------------------------------------------------------- */
  574. /* Instantiate shuffle algorithm */
  575. #define VL_SHUFFLE_type vl_uindex
  576. #define VL_SHUFFLE_prefix _vl_gmm
  577. #include "shuffle-def.h"
  578. /* #ifdef VL_GMM_INSTANTITATING */
  579. #endif
  580. /* ---------------------------------------------------------------- */
  581. #ifdef VL_GMM_INSTANTIATING
  582. /* ---------------------------------------------------------------- */
  583. /* ---------------------------------------------------------------- */
  584. /* Posterior assignments */
  585. /* ---------------------------------------------------------------- */
  586. /** @fn vl_get_gmm_data_posterior_f(float*,vl_size,vl_size,float const*,float const*,vl_size,float const*,float const*)
  587. ** @brief Get Gaussian modes posterior probabilities
  588. ** @param posteriors posterior probabilities (output)/
  589. ** @param numClusters number of modes in the GMM model.
  590. ** @param numData number of data elements.
  591. ** @param priors prior mode probabilities of the GMM model.
  592. ** @param means means of the GMM model.
  593. ** @param dimension data dimension.
  594. ** @param covariances diagonal covariances of the GMM model.
  595. ** @param data data.
  596. ** @return data log-likelihood.
  597. **
  598. ** This is a helper function that does not require a ::VlGMM object
  599. ** instance to operate.
  600. **/
  601. double
  602. VL_XCAT(vl_get_gmm_data_posteriors_, SFX)
  603. (TYPE * posteriors,
  604. vl_size numClusters,
  605. vl_size numData,
  606. TYPE const * priors,
  607. TYPE const * means,
  608. vl_size dimension,
  609. TYPE const * covariances,
  610. TYPE const * data)
  611. {
  612. vl_index i_d, i_cl;
  613. vl_size dim;
  614. double LL = 0;
  615. TYPE halfDimLog2Pi = (dimension / 2.0) * log(2.0*VL_PI);
  616. TYPE * logCovariances ;
  617. TYPE * logWeights ;
  618. TYPE * invCovariances ;
  619. #if (FLT == VL_TYPE_FLOAT)
  620. VlFloatVector3ComparisonFunction distFn = vl_get_vector_3_comparison_function_f(VlDistanceMahalanobis) ;
  621. #else
  622. VlDoubleVector3ComparisonFunction distFn = vl_get_vector_3_comparison_function_d(VlDistanceMahalanobis) ;
  623. #endif
  624. logCovariances = (TYPE*) vl_malloc(sizeof(TYPE) * numClusters) ;
  625. invCovariances = (TYPE*) vl_malloc(sizeof(TYPE) * numClusters * dimension) ;
  626. logWeights = (TYPE*) vl_malloc(sizeof(TYPE) * numClusters) ;
  627. #if defined(_OPENMP)
  628. #pragma omp parallel for private(i_cl,dim) num_threads(vl_get_max_threads())
  629. #endif
  630. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
  631. TYPE logSigma = 0 ;
  632. if (priors[i_cl] < VL_GMM_MIN_PRIOR) {
  633. logWeights[i_cl] = - (TYPE) VL_INFINITY_D ;
  634. } else {
  635. logWeights[i_cl] = log(priors[i_cl]);
  636. }
  637. for(dim = 0 ; dim < dimension ; ++ dim) {
  638. logSigma += log(covariances[i_cl*dimension + dim]);
  639. invCovariances [i_cl*dimension + dim] = (TYPE) 1.0 / covariances[i_cl*dimension + dim];
  640. }
  641. logCovariances[i_cl] = logSigma;
  642. } /* end of parallel region */
  643. #if defined(_OPENMP)
  644. #pragma omp parallel for private(i_cl,i_d) reduction(+:LL) \
  645. num_threads(vl_get_max_threads())
  646. #endif
  647. for (i_d = 0 ; i_d < (signed)numData ; ++ i_d) {
  648. TYPE clusterPosteriorsSum = 0;
  649. TYPE maxPosterior = (TYPE)(-VL_INFINITY_D) ;
  650. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
  651. TYPE p =
  652. logWeights[i_cl]
  653. - halfDimLog2Pi
  654. - 0.5 * logCovariances[i_cl]
  655. - 0.5 * distFn (dimension,
  656. data + i_d * dimension,
  657. means + i_cl * dimension,
  658. invCovariances + i_cl * dimension) ;
  659. posteriors[i_cl + i_d * numClusters] = p ;
  660. if (p > maxPosterior) { maxPosterior = p ; }
  661. }
  662. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  663. TYPE p = posteriors[i_cl + i_d * numClusters] ;
  664. p = exp(p - maxPosterior) ;
  665. posteriors[i_cl + i_d * numClusters] = p ;
  666. clusterPosteriorsSum += p ;
  667. }
  668. LL += log(clusterPosteriorsSum) + (double) maxPosterior ;
  669. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  670. posteriors[i_cl + i_d * numClusters] /= clusterPosteriorsSum ;
  671. }
  672. } /* end of parallel region */
  673. vl_free(logCovariances);
  674. vl_free(logWeights);
  675. vl_free(invCovariances);
  676. return LL;
  677. }
  678. /* ---------------------------------------------------------------- */
  679. /* Restarts zero-weighted Gaussians */
  680. /* ---------------------------------------------------------------- */
  681. static void
  682. VL_XCAT(_vl_gmm_maximization_, SFX)
  683. (VlGMM * self,
  684. TYPE * posteriors,
  685. TYPE * priors,
  686. TYPE * covariances,
  687. TYPE * means,
  688. TYPE const * data,
  689. vl_size numData) ;
  690. static vl_size
  691. VL_XCAT(_vl_gmm_restart_empty_modes_, SFX) (VlGMM * self, TYPE const * data)
  692. {
  693. vl_size dimension = self->dimension;
  694. vl_size numClusters = self->numClusters;
  695. vl_index i_cl, j_cl, i_d, d;
  696. vl_size zeroWNum = 0;
  697. TYPE * priors = (TYPE*)self->priors ;
  698. TYPE * means = (TYPE*)self->means ;
  699. TYPE * covariances = (TYPE*)self->covariances ;
  700. TYPE * posteriors = (TYPE*)self->posteriors ;
  701. //VlRand * rand = vl_get_rand() ;
  702. TYPE * mass = (TYPE*)vl_calloc(sizeof(TYPE), self->numClusters) ;
  703. if (numClusters <= 1) { return 0 ; }
  704. /* compute statistics */
  705. {
  706. vl_uindex i, k ;
  707. vl_size numNullAssignments = 0 ;
  708. for (i = 0 ; i < self->numData ; ++i) {
  709. for (k = 0 ; k < self->numClusters ; ++k) {
  710. TYPE p = ((TYPE*)self->posteriors)[k + i * self->numClusters] ;
  711. mass[k] += p ;
  712. if (p < VL_GMM_MIN_POSTERIOR) {
  713. numNullAssignments ++ ;
  714. }
  715. }
  716. }
  717. if (self->verbosity) {
  718. VL_PRINTF("gmm: sparsity of data posterior: %.1f%%\n", (double)numNullAssignments / (self->numData * self->numClusters) * 100) ;
  719. }
  720. }
  721. #if 0
  722. /* search for cluster with negligible weight and reassign them to fat clusters */
  723. for (i_cl = 0 ; i_cl < numClusters ; ++i_cl) {
  724. if (priors[i_cl] < 0.00001/numClusters) {
  725. double mass = priors[0] ;
  726. vl_index best = 0 ;
  727. for (j_cl = 1 ; j_cl < numClusters ; ++j_cl) {
  728. if (priors[j_cl] > mass) { mass = priors[j_cl] ; best = j_cl ; }
  729. }
  730. if (j_cl == i_cl) {
  731. /* this should never happen */
  732. continue ;
  733. }
  734. j_cl = best ;
  735. zeroWNum ++ ;
  736. VL_PRINTF("gmm: restarting mode %d by splitting mode %d (with prior %f)\n", i_cl,j_cl,mass) ;
  737. priors[i_cl] = mass/2 ;
  738. priors[j_cl] = mass/2 ;
  739. for (d = 0 ; d < dimension ; ++d) {
  740. TYPE sigma2 = covariances[j_cl*dimension + d] ;
  741. TYPE sigma = VL_XCAT(vl_sqrt_,SFX)(sigma2) ;
  742. means[i_cl*dimension + d] = means[j_cl*dimension + d] + 0.001 * (vl_rand_real1(rand) - 0.5) * sigma ;
  743. covariances[i_cl*dimension + d] = sigma2 ;
  744. }
  745. }
  746. }
  747. #endif
  748. /* search for cluster with negligible weight and reassign them to fat clusters */
  749. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  750. double size = - VL_INFINITY_D ;
  751. vl_index best = -1 ;
  752. if (mass[i_cl] >= VL_GMM_MIN_POSTERIOR *
  753. VL_MAX(1.0, (double) self->numData / self->numClusters))
  754. {
  755. continue ;
  756. }
  757. if (self->verbosity) {
  758. VL_PRINTF("gmm: mode %d is nearly empty (mass %f)\n", i_cl, mass[i_cl]) ;
  759. }
  760. /*
  761. Search for the Gaussian components that (approximately)
  762. maximally contribute to make the negative log-likelihood of the data
  763. large. Then split the worst offender.
  764. To do so, we approximate the exptected log-likelihood of the GMM:
  765. E[-log(f(x))] = H(f) = - log \int f(x) log f(x)
  766. where the density f(x) = sum_k pk gk(x) is a GMM. This is intractable
  767. but it is easy to approximate if we suppose that supp gk is disjoint with
  768. supp gq for all components k ~= q. In this canse
  769. H(f) ~= sum_k [ - pk log(pk) + pk H(gk) ]
  770. where H(gk) is the entropy of component k taken alone. The entropy of
  771. the latter is given by:
  772. H(gk) = D/2 (1 + log(2pi) + 1/2 sum_{i=0}^D log sigma_i^2
  773. */
  774. for (j_cl = 0 ; j_cl < (signed)numClusters ; ++j_cl) {
  775. double size_ ;
  776. if (priors[j_cl] < VL_GMM_MIN_PRIOR) { continue ; }
  777. size_ = + 0.5 * dimension * (1.0 + log(2*VL_PI)) ;
  778. for(d = 0 ; d < (signed)dimension ; d++) {
  779. double sigma2 = covariances[j_cl * dimension + d] ;
  780. size_ += 0.5 * log(sigma2) ;
  781. }
  782. size_ = priors[j_cl] * (size_ - log(priors[j_cl])) ;
  783. if (self->verbosity > 1) {
  784. VL_PRINTF("gmm: mode %d: prior %f, mass %f, entropy contribution %f\n",
  785. j_cl, priors[j_cl], mass[j_cl], size_) ;
  786. }
  787. if (size_ > size) {
  788. size = size_ ;
  789. best = j_cl ;
  790. }
  791. }
  792. j_cl = best ;
  793. if (j_cl == i_cl || j_cl < 0) {
  794. if (self->verbosity) {
  795. VL_PRINTF("gmm: mode %d is empty, "
  796. "but no other mode to split could be found\n", i_cl) ;
  797. }
  798. continue ;
  799. }
  800. if (self->verbosity) {
  801. VL_PRINTF("gmm: reinitializing empty mode %d with mode %d (prior %f, mass %f, score %f)\n",
  802. i_cl, j_cl, priors[j_cl], mass[j_cl], size) ;
  803. }
  804. /*
  805. Search for the dimension with maximum variance.
  806. */
  807. size = - VL_INFINITY_D ;
  808. best = - 1 ;
  809. for(d = 0; d < (signed)dimension; d++) {
  810. double sigma2 = covariances[j_cl * dimension + d] ;
  811. if (sigma2 > size) {
  812. size = sigma2 ;
  813. best = d ;
  814. }
  815. }
  816. /*
  817. Reassign points j_cl (mode to split) to i_cl (empty mode).
  818. */
  819. {
  820. TYPE mu = means[best + j_cl * self->dimension] ;
  821. for(i_d = 0 ; i_d < (signed)self->numData ; ++ i_d) {
  822. TYPE p = posteriors[j_cl + self->numClusters * i_d] ;
  823. TYPE q = posteriors[i_cl + self->numClusters * i_d] ; /* ~= 0 */
  824. if (data[best + i_d * self->dimension] < mu) {
  825. /* assign this point to i_cl */
  826. posteriors[i_cl + self->numClusters * i_d] = p + q ;
  827. posteriors[j_cl + self->numClusters * i_d] = 0 ;
  828. } else {
  829. /* assign this point to j_cl */
  830. posteriors[i_cl + self->numClusters * i_d] = 0 ;
  831. posteriors[j_cl + self->numClusters * i_d] = p + q ;
  832. }
  833. }
  834. }
  835. /*
  836. Re-estimate.
  837. */
  838. VL_XCAT(_vl_gmm_maximization_, SFX)
  839. (self,posteriors,priors,covariances,means,data,self->numData) ;
  840. }
  841. return zeroWNum;
  842. }
  843. /* ---------------------------------------------------------------- */
  844. /* Helpers */
  845. /* ---------------------------------------------------------------- */
  846. static void
  847. VL_XCAT(_vl_gmm_apply_bounds_, SFX)(VlGMM * self)
  848. {
  849. vl_uindex dim ;
  850. vl_uindex k ;
  851. vl_size numAdjusted = 0 ;
  852. TYPE * cov = (TYPE*)self->covariances ;
  853. double const * lbs = self->sigmaLowBound ;
  854. for (k = 0 ; k < self->numClusters ; ++k) {
  855. vl_bool adjusted = VL_FALSE ;
  856. for (dim = 0 ; dim < self->dimension ; ++dim) {
  857. if (cov[k * self->dimension + dim] < lbs[dim] ) {
  858. cov[k * self->dimension + dim] = lbs[dim] ;
  859. adjusted = VL_TRUE ;
  860. }
  861. }
  862. if (adjusted) { numAdjusted ++ ; }
  863. }
  864. if (numAdjusted > 0 && self->verbosity > 0) {
  865. VL_PRINT("gmm: detected %d of %d modes with at least one dimension "
  866. "with covariance too small (set to lower bound)\n",
  867. numAdjusted, self->numClusters) ;
  868. }
  869. }
  870. /* ---------------------------------------------------------------- */
  871. /* EM - Maximization step */
  872. /* ---------------------------------------------------------------- */
  873. static void
  874. VL_XCAT(_vl_gmm_maximization_, SFX)
  875. (VlGMM * self,
  876. TYPE * posteriors,
  877. TYPE * priors,
  878. TYPE * covariances,
  879. TYPE * means,
  880. TYPE const * data,
  881. vl_size numData)
  882. {
  883. vl_size numClusters = self->numClusters;
  884. vl_index i_d, i_cl;
  885. vl_size dim ;
  886. TYPE * oldMeans ;
  887. double time = 0 ;
  888. if (self->verbosity > 1) {
  889. VL_PRINTF("gmm: em: entering maximization step\n") ;
  890. time = vl_get_cpu_time() ;
  891. }
  892. oldMeans = (TYPE*) vl_malloc(sizeof(TYPE) * self->dimension * numClusters) ;
  893. memcpy(oldMeans, means, sizeof(TYPE) * self->dimension * numClusters) ;
  894. memset(priors, 0, sizeof(TYPE) * numClusters) ;
  895. memset(means, 0, sizeof(TYPE) * self->dimension * numClusters) ;
  896. memset(covariances, 0, sizeof(TYPE) * self->dimension * numClusters) ;
  897. #if defined(_OPENMP)
  898. #pragma omp parallel default(shared) private(i_d, i_cl, dim) \
  899. num_threads(vl_get_max_threads())
  900. #endif
  901. {
  902. TYPE * clusterPosteriorSum_, * means_, * covariances_ ;
  903. #if defined(_OPENMP)
  904. #pragma omp critical
  905. #endif
  906. {
  907. clusterPosteriorSum_ = (TYPE*)vl_calloc(sizeof(TYPE), numClusters) ;
  908. means_ = (TYPE*)vl_calloc(sizeof(TYPE), self->dimension * numClusters) ;
  909. covariances_ = (TYPE*)vl_calloc(sizeof(TYPE), self->dimension * numClusters) ;
  910. }
  911. /*
  912. Accumulate weighted sums and sum of square differences. Once normalized,
  913. these become the means and covariances of each Gaussian mode.
  914. The squared differences will be taken w.r.t. the old means however. In this manner,
  915. one avoids doing two passes across the data. Eventually, these are corrected to account
  916. for the new means properly. In principle, one could set the old means to zero, but
  917. this may cause numerical instabilities (by accumulating large squares).
  918. */
  919. #if defined(_OPENMP)
  920. #pragma omp for
  921. #endif
  922. for (i_d = 0 ; i_d < (signed)numData ; ++i_d) {
  923. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  924. TYPE p = posteriors[i_cl + i_d * self->numClusters] ;
  925. vl_bool calculated = VL_FALSE ;
  926. /* skip very small associations for speed */
  927. if (p < VL_GMM_MIN_POSTERIOR / numClusters) { continue ; }
  928. clusterPosteriorSum_ [i_cl] += p ;
  929. #ifndef VL_DISABLE_AVX
  930. if (vl_get_simd_enabled() && vl_cpu_has_avx()) {
  931. VL_XCAT(_vl_weighted_mean_sse2_, SFX)
  932. (self->dimension,
  933. means_+ i_cl * self->dimension,
  934. data + i_d * self->dimension,
  935. p) ;
  936. VL_XCAT(_vl_weighted_sigma_sse2_, SFX)
  937. (self->dimension,
  938. covariances_ + i_cl * self->dimension,
  939. data + i_d * self->dimension,
  940. oldMeans + i_cl * self->dimension,
  941. p) ;
  942. calculated = VL_TRUE;
  943. }
  944. #endif
  945. #ifndef VL_DISABLE_SSE2
  946. if (vl_get_simd_enabled() && vl_cpu_has_sse2() && !calculated) {
  947. VL_XCAT(_vl_weighted_mean_sse2_, SFX)
  948. (self->dimension,
  949. means_+ i_cl * self->dimension,
  950. data + i_d * self->dimension,
  951. p) ;
  952. VL_XCAT(_vl_weighted_sigma_sse2_, SFX)
  953. (self->dimension,
  954. covariances_ + i_cl * self->dimension,
  955. data + i_d * self->dimension,
  956. oldMeans + i_cl * self->dimension,
  957. p) ;
  958. calculated = VL_TRUE;
  959. }
  960. #endif
  961. if(!calculated) {
  962. for (dim = 0 ; dim < self->dimension ; ++dim) {
  963. TYPE x = data[i_d * self->dimension + dim] ;
  964. TYPE mu = oldMeans[i_cl * self->dimension + dim] ;
  965. TYPE diff = x - mu ;
  966. means_ [i_cl * self->dimension + dim] += p * x ;
  967. covariances_ [i_cl * self->dimension + dim] += p * (diff*diff) ;
  968. }
  969. }
  970. }
  971. }
  972. /* accumulate */
  973. #if defined(_OPENMP)
  974. #pragma omp critical
  975. #endif
  976. {
  977. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  978. priors [i_cl] += clusterPosteriorSum_ [i_cl];
  979. for (dim = 0 ; dim < self->dimension ; ++dim) {
  980. means [i_cl * self->dimension + dim] += means_ [i_cl * self->dimension + dim] ;
  981. covariances [i_cl * self->dimension + dim] += covariances_ [i_cl * self->dimension + dim] ;
  982. }
  983. }
  984. vl_free(means_);
  985. vl_free(covariances_);
  986. vl_free(clusterPosteriorSum_);
  987. }
  988. } /* parallel section */
  989. /* at this stage priors[] contains the total mass of each cluster */
  990. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
  991. TYPE mass = priors[i_cl] ;
  992. /* do not update modes that do not recieve mass */
  993. if (mass >= 1e-6 / numClusters) {
  994. for (dim = 0 ; dim < self->dimension ; ++dim) {
  995. means[i_cl * self->dimension + dim] /= mass ;
  996. covariances[i_cl * self->dimension + dim] /= mass ;
  997. }
  998. }
  999. }
  1000. /* apply old to new means correction */
  1001. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
  1002. TYPE mass = priors[i_cl] ;
  1003. if (mass >= 1e-6 / numClusters) {
  1004. for (dim = 0 ; dim < self->dimension ; ++dim) {
  1005. TYPE mu = means[i_cl * self->dimension + dim] ;
  1006. TYPE oldMu = oldMeans[i_cl * self->dimension + dim] ;
  1007. TYPE diff = mu - oldMu ;
  1008. covariances[i_cl * self->dimension + dim] -= diff * diff ;
  1009. }
  1010. }
  1011. }
  1012. VL_XCAT(_vl_gmm_apply_bounds_,SFX)(self) ;
  1013. {
  1014. TYPE sum = 0;
  1015. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  1016. sum += priors[i_cl] ;
  1017. }
  1018. sum = VL_MAX(sum, 1e-12) ;
  1019. for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
  1020. priors[i_cl] /= sum ;
  1021. }
  1022. }
  1023. if (self->verbosity > 1) {
  1024. VL_PRINTF("gmm: em: maximization step completed in %.2f s\n",
  1025. vl_get_cpu_time() - time) ;
  1026. }
  1027. vl_free(oldMeans);
  1028. }
  1029. /* ---------------------------------------------------------------- */
  1030. /* EM iterations */
  1031. /* ---------------------------------------------------------------- */
  1032. static double
  1033. VL_XCAT(_vl_gmm_em_, SFX)
  1034. (VlGMM * self,
  1035. TYPE const * data,
  1036. vl_size numData)
  1037. {
  1038. vl_size iteration, restarted ;
  1039. double previousLL = (TYPE)(-VL_INFINITY_D) ;
  1040. double LL = (TYPE)(-VL_INFINITY_D) ;
  1041. double time = 0 ;
  1042. _vl_gmm_prepare_for_data (self, numData) ;
  1043. VL_XCAT(_vl_gmm_apply_bounds_,SFX)(self) ;
  1044. for (iteration = 0 ; 1 ; ++ iteration) {
  1045. double eps ;
  1046. /*
  1047. Expectation: assign data to Gaussian modes
  1048. and compute log-likelihood.
  1049. */
  1050. if (self->verbosity > 1) {
  1051. VL_PRINTF("gmm: em: entering expectation step\n") ;
  1052. time = vl_get_cpu_time() ;
  1053. }
  1054. LL = VL_XCAT(vl_get_gmm_data_posteriors_,SFX)
  1055. ((TYPE*)self->posteriors,
  1056. self->numClusters,
  1057. numData,
  1058. (TYPE*)self->priors,
  1059. (TYPE*)self->means,
  1060. self->dimension,
  1061. (TYPE*)self->covariances,
  1062. data) ;
  1063. if (self->verbosity > 1) {
  1064. VL_PRINTF("gmm: em: expectation step completed in %.2f s\n",
  1065. vl_get_cpu_time() - time) ;
  1066. }
  1067. /*
  1068. Check the termination conditions.
  1069. */
  1070. if (self->verbosity) {
  1071. VL_PRINTF("gmm: em: iteration %d: loglikelihood = %f (variation = %f)\n",
  1072. iteration, LL, LL - previousLL) ;
  1073. }
  1074. if (iteration >= self->maxNumIterations) {
  1075. if (self->verbosity) {
  1076. VL_PRINTF("gmm: em: terminating because "
  1077. "the maximum number of iterations "
  1078. "(%d) has been reached.\n", self->maxNumIterations) ;
  1079. }
  1080. break ;
  1081. }
  1082. eps = vl_abs_d ((LL - previousLL) / (LL));
  1083. if ((iteration > 0) && (eps < 0.00001)) {
  1084. if (self->verbosity) {
  1085. VL_PRINTF("gmm: em: terminating because the algorithm "
  1086. "fully converged (log-likelihood variation = %f).\n", eps) ;
  1087. }
  1088. break ;
  1089. }
  1090. previousLL = LL ;
  1091. /*
  1092. Restart empty modes.
  1093. */
  1094. if (iteration > 1) {
  1095. restarted = VL_XCAT(_vl_gmm_restart_empty_modes_, SFX)
  1096. (self, data);
  1097. if ((restarted > 0) & (self->verbosity > 0)) {
  1098. VL_PRINTF("gmm: em: %d Gaussian modes restarted because "
  1099. "they had become empty.\n", restarted);
  1100. }
  1101. }
  1102. /*
  1103. Maximization: reestimate the GMM parameters.
  1104. */
  1105. VL_XCAT(_vl_gmm_maximization_, SFX)
  1106. (self,(TYPE*)self->posteriors,(TYPE*)self->priors,(TYPE*)self->covariances,(TYPE*)self->means,data,numData) ;
  1107. }
  1108. return LL;
  1109. }
  1110. /* ---------------------------------------------------------------- */
  1111. /* Kmeans initialization of mixtures */
  1112. /* ---------------------------------------------------------------- */
  1113. static void
  1114. VL_XCAT(_vl_gmm_init_with_kmeans_, SFX)
  1115. (VlGMM * self,
  1116. TYPE const * data,
  1117. vl_size numData,
  1118. VlKMeans * kmeansInit)
  1119. {
  1120. vl_size i_d ;
  1121. vl_uint32 * assignments = (vl_uint32*)vl_malloc(sizeof(vl_uint32) * numData);
  1122. _vl_gmm_prepare_for_data (self, numData) ;
  1123. memset(self->means,0,sizeof(TYPE) * self->numClusters * self->dimension) ;
  1124. memset(self->priors,0,sizeof(TYPE) * self->numClusters) ;
  1125. memset(self->covariances,0,sizeof(TYPE) * self->numClusters * self->dimension) ;
  1126. memset(self->posteriors,0,sizeof(TYPE) * self->numClusters * numData) ;
  1127. /* setup speified KMeans initialization object if any */
  1128. if (kmeansInit) { vl_gmm_set_kmeans_init_object (self, kmeansInit) ; }
  1129. /* if a KMeans initalization object is still unavailable, create one */
  1130. if(self->kmeansInit == NULL) {
  1131. vl_size ncomparisons = VL_MAX(numData / 4, 10) ;
  1132. vl_size niter = 5 ;
  1133. vl_size ntrees = 1 ;
  1134. vl_size nrepetitions = 1 ;
  1135. VlKMeansAlgorithm algorithm = VlKMeansANN ;
  1136. VlKMeansInitialization initialization = VlKMeansRandomSelection ;
  1137. VlKMeans * kmeansInitDefault = vl_kmeans_new(self->dataType,VlDistanceL2) ;
  1138. vl_kmeans_set_initialization(kmeansInitDefault, initialization);
  1139. vl_kmeans_set_max_num_iterations (kmeansInitDefault, niter) ;
  1140. vl_kmeans_set_max_num_comparisons (kmeansInitDefault, ncomparisons) ;
  1141. vl_kmeans_set_num_trees (kmeansInitDefault, ntrees);
  1142. vl_kmeans_set_algorithm (kmeansInitDefault, algorithm);
  1143. vl_kmeans_set_num_repetitions(kmeansInitDefault, nrepetitions);
  1144. vl_kmeans_set_verbosity (kmeansInitDefault, self->verbosity);
  1145. self->kmeansInit = kmeansInitDefault;
  1146. self->kmeansInitIsOwner = VL_TRUE ;
  1147. }
  1148. /* Use k-means to assign data to clusters */
  1149. vl_kmeans_cluster (self->kmeansInit, data, self->dimension, numData, self->numClusters);
  1150. vl_kmeans_quantize (self->kmeansInit, assignments, NULL, data, numData) ;
  1151. /* Transform the k-means assignments in posteriors and estimates the mode parameters */
  1152. for(i_d = 0; i_d < numData; i_d++) {
  1153. ((TYPE*)self->posteriors)[assignments[i_d] + i_d * self->numClusters] = (TYPE) 1.0 ;
  1154. }
  1155. /* Update cluster parameters */
  1156. VL_XCAT(_vl_gmm_maximization_, SFX)
  1157. (self,(TYPE*)self->posteriors,(TYPE*)self->priors,(TYPE*)self->covariances,(TYPE*)self->means,data,numData);
  1158. vl_free(assignments) ;
  1159. }
  1160. /* ---------------------------------------------------------------- */
  1161. /* Random initialization of mixtures */
  1162. /* ---------------------------------------------------------------- */
  1163. static void
  1164. VL_XCAT(_vl_gmm_compute_init_sigma_, SFX)
  1165. (VlGMM * self,
  1166. TYPE const * data,
  1167. TYPE * initSigma,
  1168. vl_size dimension,
  1169. vl_size numData)
  1170. {
  1171. vl_size dim;
  1172. vl_uindex i;
  1173. TYPE * dataMean ;
  1174. memset(initSigma,0,sizeof(TYPE)*dimension) ;
  1175. if (numData <= 1) return ;
  1176. dataMean = (TYPE*)vl_malloc(sizeof(TYPE)*dimension);
  1177. memset(dataMean,0,sizeof(TYPE)*dimension) ;
  1178. /* find mean of the whole dataset */
  1179. for(dim = 0 ; dim < dimension ; dim++) {
  1180. for(i = 0 ; i < numData ; i++) {
  1181. dataMean[dim] += data[i*dimension + dim];
  1182. }
  1183. dataMean[dim] /= numData;
  1184. }
  1185. /* compute variance of the whole dataset */
  1186. for(dim = 0; dim < dimension; dim++) {
  1187. for(i = 0; i < numData; i++) {
  1188. TYPE diff = (data[i*self->dimension + dim] - dataMean[dim]) ;
  1189. initSigma[dim] += diff*diff ;
  1190. }
  1191. initSigma[dim] /= numData - 1 ;
  1192. }
  1193. vl_free(dataMean) ;
  1194. }
  1195. static void
  1196. VL_XCAT(_vl_gmm_init_with_rand_data_, SFX)
  1197. (VlGMM * self,
  1198. TYPE const * data,
  1199. vl_size numData)
  1200. {
  1201. vl_uindex i, k, dim ;
  1202. VlKMeans * kmeans ;
  1203. _vl_gmm_prepare_for_data(self, numData) ;
  1204. /* initilaize priors of gaussians so they are equal and sum to one */
  1205. for (i = 0 ; i < self->numClusters ; ++i) { ((TYPE*)self->priors)[i] = (TYPE) (1.0 / self->numClusters) ; }
  1206. /* initialize diagonals of covariance matrices to data covariance */
  1207. VL_XCAT(_vl_gmm_compute_init_sigma_, SFX) (self, data, (TYPE*)self->covariances, self->dimension, numData);
  1208. for (k = 1 ; k < self->numClusters ; ++ k) {
  1209. for(dim = 0; dim < self->dimension; dim++) {
  1210. *((TYPE*)self->covariances + k * self->dimension + dim) =
  1211. *((TYPE*)self->covariances + dim) ;
  1212. }
  1213. }
  1214. /* use kmeans++ initialization to pick points at random */
  1215. kmeans = vl_kmeans_new(self->dataType,VlDistanceL2) ;
  1216. vl_kmeans_init_centers_plus_plus(kmeans, data, self->dimension, numData, self->numClusters) ;
  1217. memcpy(self->means, vl_kmeans_get_centers(kmeans), sizeof(TYPE) * self->dimension * self->numClusters) ;
  1218. vl_kmeans_delete(kmeans) ;
  1219. }
  1220. /* ---------------------------------------------------------------- */
  1221. #else /* VL_GMM_INSTANTIATING */
  1222. /* ---------------------------------------------------------------- */
  1223. #ifndef __DOXYGEN__
  1224. #define FLT VL_TYPE_FLOAT
  1225. #define TYPE float
  1226. #define SFX f
  1227. #define VL_GMM_INSTANTIATING
  1228. #include "gmm.c"
  1229. #define FLT VL_TYPE_DOUBLE
  1230. #define TYPE double
  1231. #define SFX d
  1232. #define VL_GMM_INSTANTIATING
  1233. #include "gmm.c"
  1234. #endif
  1235. /* VL_GMM_INSTANTIATING */
  1236. #endif
  1237. /* ---------------------------------------------------------------- */
  1238. #ifndef VL_GMM_INSTANTIATING
  1239. /* ---------------------------------------------------------------- */
  1240. /** @brief Create a new GMM object by copy
  1241. ** @param self object.
  1242. ** @return new copy.
  1243. **
  1244. ** Most parameters, including the cluster priors, means, and
  1245. ** covariances are copied. Data posteriors (available after
  1246. ** initalization or EM) are not; nor is the KMeans object used for
  1247. ** initialization, if any.
  1248. **/
  1249. VlGMM *
  1250. vl_gmm_new_copy (VlGMM const * self)
  1251. {
  1252. vl_size size = vl_get_type_size(self->dataType) ;
  1253. VlGMM * gmm = vl_gmm_new(self->dataType, self->dimension, self->numClusters);
  1254. gmm->initialization = self->initialization;
  1255. gmm->maxNumIterations = self->maxNumIterations;
  1256. gmm->numRepetitions = self->numRepetitions;
  1257. gmm->verbosity = self->verbosity;
  1258. gmm->LL = self->LL;
  1259. memcpy(gmm->means, self->means, size*self->numClusters*self->dimension);
  1260. memcpy(gmm->covariances, self->covariances, size*self->numClusters*self->dimension);
  1261. memcpy(gmm->priors, self->priors, size*self->numClusters);
  1262. return gmm ;
  1263. }
  1264. /** @brief Initialize mixture before EM takes place using random initialization
  1265. ** @param self GMM object instance.
  1266. ** @param data data points which should be clustered.
  1267. ** @param numData number of data points.
  1268. **/
  1269. void
  1270. vl_gmm_init_with_rand_data
  1271. (VlGMM * self,
  1272. void const * data,
  1273. vl_size numData)
  1274. {
  1275. vl_gmm_reset (self) ;
  1276. switch (self->dataType) {
  1277. case VL_TYPE_FLOAT : _vl_gmm_init_with_rand_data_f (self, (float const *)data, numData) ; break ;
  1278. case VL_TYPE_DOUBLE : _vl_gmm_init_with_rand_data_d (self, (double const *)data, numData) ; break ;
  1279. default:
  1280. abort() ;
  1281. }
  1282. }
  1283. /** @brief Initializes the GMM using KMeans
  1284. ** @param self GMM object instance.
  1285. ** @param data data points which should be clustered.
  1286. ** @param numData number of data points.
  1287. ** @param kmeansInit KMeans object to use.
  1288. **/
  1289. void
  1290. vl_gmm_init_with_kmeans
  1291. (VlGMM * self,
  1292. void const * data,
  1293. vl_size numData,
  1294. VlKMeans * kmeansInit)
  1295. {
  1296. vl_gmm_reset (self) ;
  1297. switch (self->dataType) {
  1298. case VL_TYPE_FLOAT :
  1299. _vl_gmm_init_with_kmeans_f
  1300. (self, (float const *)data, numData, kmeansInit) ;
  1301. break ;
  1302. case VL_TYPE_DOUBLE :
  1303. _vl_gmm_init_with_kmeans_d
  1304. (self, (double const *)data, numData, kmeansInit) ;
  1305. break ;
  1306. default:
  1307. abort() ;
  1308. }
  1309. }
  1310. #if 0
  1311. #include<fenv.h>
  1312. #endif
  1313. /** @brief Run GMM clustering - includes initialization and EM
  1314. ** @param self GMM object instance.
  1315. ** @param data data points which should be clustered.
  1316. ** @param numData number of data points.
  1317. **/
  1318. double vl_gmm_cluster (VlGMM * self,
  1319. void const * data,
  1320. vl_size numData)
  1321. {
  1322. void * bestPriors = NULL ;
  1323. void * bestMeans = NULL;
  1324. void * bestCovariances = NULL;
  1325. void * bestPosteriors = NULL;
  1326. vl_size size = vl_get_type_size(self->dataType) ;
  1327. double bestLL = -VL_INFINITY_D;
  1328. vl_uindex repetition;
  1329. assert(self->numRepetitions >=1) ;
  1330. bestPriors = vl_malloc(size * self->numClusters) ;
  1331. bestMeans = vl_malloc(size * self->dimension * self->numClusters) ;
  1332. bestCovariances = vl_malloc(size * self->dimension * self->numClusters) ;
  1333. bestPosteriors = vl_malloc(size * self->numClusters * numData) ;
  1334. #if 0
  1335. feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
  1336. #endif
  1337. for (repetition = 0 ; repetition < self->numRepetitions ; ++ repetition) {
  1338. double LL ;
  1339. double timeRef ;
  1340. if (self->verbosity) {
  1341. VL_PRINTF("gmm: clustering: starting repetition %d of %d\n", repetition + 1, self->numRepetitions) ;
  1342. }
  1343. /* initialize a new mixture model */
  1344. timeRef = vl_get_cpu_time() ;
  1345. switch (self->initialization) {
  1346. case VlGMMKMeans : vl_gmm_init_with_kmeans (self, data, numData, NULL) ; break ;
  1347. case VlGMMRand : vl_gmm_init_with_rand_data (self, data, numData) ; break ;
  1348. case VlGMMCustom : break ;
  1349. default: abort() ;
  1350. }
  1351. if (self->verbosity) {
  1352. VL_PRINTF("gmm: model initialized in %.2f s\n",
  1353. vl_get_cpu_time() - timeRef) ;
  1354. }
  1355. /* fit the model to data by running EM */
  1356. timeRef = vl_get_cpu_time () ;
  1357. LL = vl_gmm_em (self, data, numData) ;
  1358. if (self->verbosity) {
  1359. VL_PRINTF("gmm: optimization terminated in %.2f s with loglikelihood %f\n",
  1360. vl_get_cpu_time() - timeRef, LL) ;
  1361. }
  1362. if (LL > bestLL || repetition == 0) {
  1363. void * temp ;
  1364. temp = bestPriors ;
  1365. bestPriors = self->priors ;
  1366. self->priors = temp ;
  1367. temp = bestMeans ;
  1368. bestMeans = self->means ;
  1369. self->means = temp ;
  1370. temp = bestCovariances ;
  1371. bestCovariances = self->covariances ;
  1372. self->covariances = temp ;
  1373. temp = bestPosteriors ;
  1374. bestPosteriors = self->posteriors ;
  1375. self->posteriors = temp ;
  1376. bestLL = LL;
  1377. }
  1378. }
  1379. vl_free (self->priors) ;
  1380. vl_free (self->means) ;
  1381. vl_free (self->covariances) ;
  1382. vl_free (self->posteriors) ;
  1383. self->priors = bestPriors ;
  1384. self->means = bestMeans ;
  1385. self->covariances = bestCovariances ;
  1386. self->posteriors = bestPosteriors ;
  1387. self->LL = bestLL;
  1388. if (self->verbosity) {
  1389. VL_PRINTF("gmm: all repetitions terminated with final loglikelihood %f\n", self->LL) ;
  1390. }
  1391. return bestLL ;
  1392. }
  1393. /** @brief Invoke the EM algorithm.
  1394. ** @param self GMM object instance.
  1395. ** @param data data points which should be clustered.
  1396. ** @param numData number of data points.
  1397. **/
  1398. double vl_gmm_em (VlGMM * self, void const * data, vl_size numData)
  1399. {
  1400. switch (self->dataType) {
  1401. case VL_TYPE_FLOAT:
  1402. return _vl_gmm_em_f (self, (float const *)data, numData) ; break ;
  1403. case VL_TYPE_DOUBLE:
  1404. return _vl_gmm_em_d (self, (double const *)data, numData) ; break ;
  1405. default:
  1406. abort() ;
  1407. }
  1408. return 0 ;
  1409. }
  1410. /** @brief Explicitly set the initial means for EM.
  1411. ** @param self GMM object instance.
  1412. ** @param means initial values of means.
  1413. **/
  1414. void
  1415. vl_gmm_set_means (VlGMM * self, void const * means)
  1416. {
  1417. memcpy(self->means,means,
  1418. self->dimension * self->numClusters * vl_get_type_size(self->dataType));
  1419. }
  1420. /** @brief Explicitly set the initial sigma diagonals for EM.
  1421. ** @param self GMM object instance.
  1422. ** @param covariances initial values of covariance matrix diagonals.
  1423. **/
  1424. void vl_gmm_set_covariances (VlGMM * self, void const * covariances)
  1425. {
  1426. memcpy(self->covariances,covariances,
  1427. self->dimension * self->numClusters * vl_get_type_size(self->dataType));
  1428. }
  1429. /** @brief Explicitly set the initial priors of the gaussians.
  1430. ** @param self GMM object instance.
  1431. ** @param priors initial values of the gaussian priors.
  1432. **/
  1433. void vl_gmm_set_priors (VlGMM * self, void const * priors)
  1434. {
  1435. memcpy(self->priors,priors,
  1436. self->numClusters * vl_get_type_size(self->dataType));
  1437. }
  1438. /* VL_GMM_INSTANTIATING */
  1439. #endif
  1440. #undef SFX
  1441. #undef TYPE
  1442. #undef FLT
  1443. #undef VL_GMM_INSTANTIATING