Debian Codegraph @

src/thirdparty/VLFeat/gmm.c

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