TestPDF.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // C++ Implementation: TestPDF
  3. //
  4. // Description:
  5. //
  6. //
  7. // Author: Michael Koch <Koch.Michael@uni-jena.de>, (C) 2009
  8. //
  9. // Copyright: See COPYING file that comes with this distribution
  10. //
  11. /**
  12. * @file TestPDF.cpp
  13. * @brief TestPDF
  14. * @author Michael Koch
  15. * @date Di Aug 4 2009
  16. */
  17. #include "TestPDF.h"
  18. #include <string>
  19. #include "core/basics/cppunitex.h"
  20. #include "core/basics/numerictools.h"
  21. #include "core/vector/Distance.h"
  22. #include "core/vector/VVector.h"
  23. #include "vislearning/math/pdf/PDFGaussian.h"
  24. using namespace std;
  25. using namespace NICE;
  26. using namespace OBJREC;
  27. Matrix computeCovariance ( const VVector & vecs )
  28. {
  29. Vector mean ( vecs[0].size(), 0.0 );
  30. for ( unsigned int i = 0; i < vecs.size(); ++i )
  31. mean += vecs[i];
  32. mean *= 1.0 / vecs.size();
  33. Matrix cov ( vecs[0].size(), vecs[0].size(), 0.0 );
  34. for ( unsigned int i = 0; i < vecs.size(); ++i )
  35. {
  36. Vector diff = vecs[i] - mean;
  37. cov.addTensorProduct ( 1.0, diff, diff );
  38. }
  39. cov *= 1.0 / ( vecs.size() );
  40. return cov;
  41. }
  42. CPPUNIT_TEST_SUITE_REGISTRATION ( TestPDF );
  43. void TestPDF::setUp()
  44. {
  45. }
  46. void TestPDF::tearDown()
  47. {
  48. }
  49. void TestPDF::TestPDFComputation()
  50. {
  51. uint dim = 3;
  52. bool init_random = true ;
  53. uint samples = dim * 500;
  54. NICE::Matrix C ( dim, dim );
  55. NICE::Vector mean ( dim, 0.0 );
  56. VVector samplevectors;
  57. C.set ( 0.0 );
  58. cerr << "Sample from Gaussian" << endl;
  59. //init random
  60. if ( init_random )
  61. srand48 ( time ( NULL ) );
  62. // generate random symmetric matrix
  63. for ( uint i = 0 ; i < dim ; i++ )
  64. for ( uint j = i ; j < dim ; j++ )
  65. {
  66. C ( i, j ) = drand48();
  67. C ( j, i ) = C ( i, j );
  68. }
  69. C = C * C.transpose();
  70. cerr << "Ground-Truth covariance" << endl;
  71. cerr << C << endl;
  72. //initialize GaussPDF
  73. PDFGaussian pdf_gauss ( C, mean );
  74. //draw samples
  75. pdf_gauss.sample ( samplevectors, samples );
  76. Matrix Cov_test = computeCovariance ( samplevectors );
  77. cerr << "Estimated covariance" << endl;
  78. cerr << Cov_test << endl;
  79. NICE::Matrix diff = C - Cov_test;
  80. double frobNorm = diff.frobeniusNorm();
  81. cerr << "Frobenius norm: " << frobNorm << endl;
  82. CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN ( 0.0, frobNorm, 0.1 );
  83. }