mlpack  master
positive_definite_constraint.hpp
Go to the documentation of this file.
1 
12 #ifndef MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP
13 #define MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP
14 
15 #include <mlpack/prereqs.hpp>
16 
17 namespace mlpack {
18 namespace gmm {
19 
28 {
29  public:
36  static void ApplyConstraint(arma::mat& covariance)
37  {
38  // What we want to do is make sure that the matrix is positive definite and
39  // that the condition number isn't too large. We also need to ensure that
40  // the covariance matrix is not too close to zero (hence, we ensure that all
41  // eigenvalues are at least 1e-50).
42  arma::vec eigval;
43  arma::mat eigvec;
44  arma::eig_sym(eigval, eigvec, covariance);
45 
46  // If the matrix is not positive definite or if the condition number is
47  // large, we must project it back onto the cone of positive definite
48  // matrices with reasonable condition number (I'm picking 1e5 here, not for
49  // any particular reason).
50  if ((eigval[0] < 0.0) || ((eigval[eigval.n_elem - 1] / eigval[0]) > 1e5) ||
51  (eigval[eigval.n_elem - 1] < 1e-50))
52  {
53  // Project any negative eigenvalues back to non-negative, and project any
54  // too-small eigenvalues to a large enough value. Make them as small as
55  // possible to satisfy our constraint on the condition number.
56  const double minEigval = std::max(eigval[eigval.n_elem - 1] / 1e5, 1e-50);
57  for (size_t i = 0; i < eigval.n_elem; ++i)
58  eigval[i] = std::max(eigval[i], minEigval);
59 
60  // Now reassemble the covariance matrix.
61  covariance = eigvec * arma::diagmat(eigval) * eigvec.t();
62  }
63  }
64 
66  template<typename Archive>
67  static void Serialize(Archive& /* ar */, const unsigned int /* version */) { }
68 };
69 
70 } // namespace gmm
71 } // namespace mlpack
72 
73 #endif
74 
Linear algebra utility functions, generally performed on matrices or vectors.
Definition: binarize.hpp:18
The core includes that mlpack expects; standard C++ includes and Armadillo.
static void ApplyConstraint(arma::mat &covariance)
Apply the positive definiteness constraint to the given covariance matrix, and ensure each value on t...
static void Serialize(Archive &, const unsigned int)
Serialize the constraint (which stores nothing, so, nothing to do).
Given a covariance matrix, force the matrix to be positive definite.