TestPDF.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. #include <time.h>
  25. using namespace std;
  26. using namespace NICE;
  27. using namespace OBJREC;
  28. Matrix computeCovariance ( const VVector & vecs )
  29. {
  30. Vector mean ( vecs[0].size(), 0.0 );
  31. for ( unsigned int i = 0; i < vecs.size(); ++i )
  32. mean += vecs[i];
  33. mean *= 1.0 / vecs.size();
  34. Matrix cov ( vecs[0].size(), vecs[0].size(), 0.0 );
  35. for ( unsigned int i = 0; i < vecs.size(); ++i )
  36. {
  37. Vector diff = vecs[i] - mean;
  38. cov.addTensorProduct ( 1.0, diff, diff );
  39. }
  40. cov *= 1.0 / ( vecs.size() );
  41. return cov;
  42. }
  43. CPPUNIT_TEST_SUITE_REGISTRATION ( TestPDF );
  44. void TestPDF::setUp()
  45. {
  46. }
  47. void TestPDF::tearDown()
  48. {
  49. }
  50. void TestPDF::TestPDFComputation()
  51. {
  52. uint dim = 3;
  53. bool init_random = true ;
  54. uint samples = dim * 500;
  55. NICE::Matrix C ( dim, dim );
  56. NICE::Vector mean ( dim, 0.0 );
  57. VVector samplevectors;
  58. C.set ( 0.0 );
  59. cerr << "Sample from Gaussian" << endl;
  60. //init random
  61. if ( init_random )
  62. #ifdef WIN32
  63. srand ( time ( NULL ) );
  64. #else
  65. srand48 ( time ( NULL ) );
  66. #endif
  67. // generate random symmetric matrix
  68. for ( uint i = 0 ; i < dim ; i++ )
  69. for ( uint j = i ; j < dim ; j++ )
  70. {
  71. C ( i, j ) = drand48();
  72. C ( j, i ) = C ( i, j );
  73. }
  74. C = C * C.transpose();
  75. cerr << "Ground-Truth covariance" << endl;
  76. cerr << C << endl;
  77. //initialize GaussPDF
  78. PDFGaussian pdf_gauss ( C, mean );
  79. //draw samples
  80. pdf_gauss.sample ( samplevectors, samples );
  81. Matrix Cov_test = computeCovariance ( samplevectors );
  82. cerr << "Estimated covariance" << endl;
  83. cerr << Cov_test << endl;
  84. NICE::Matrix diff = C - Cov_test;
  85. double frobNorm = diff.frobeniusNorm();
  86. cerr << "Frobenius norm: " << frobNorm << endl;
  87. CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN ( 0.0, frobNorm, 0.1 );
  88. }