TestPDF.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 "vislearning/nice_nonvis.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. srand48(time(NULL));
  63. // generate random symmetric matrix
  64. for (uint i = 0 ; i < dim ; i++)
  65. for (uint j = i ; j < dim ; j++)
  66. {
  67. C(i, j) = drand48();
  68. C(j, i) = C(i, j);
  69. }
  70. C=C*C.transpose();
  71. cerr << "Ground-Truth covariance" << endl;
  72. cerr << C << endl;
  73. //initialize GaussPDF
  74. PDFGaussian pdf_gauss(C, mean);
  75. //draw samples
  76. pdf_gauss.sample(samplevectors, samples);
  77. Matrix Cov_test = computeCovariance(samplevectors);
  78. cerr << "Estimated covariance" << endl;
  79. cerr<<Cov_test<<endl;
  80. NICE::Matrix diff = C-Cov_test;
  81. double frobNorm = diff.frobeniusNorm();
  82. cerr << "Frobenius norm: " << frobNorm << endl;
  83. CPPUNIT_ASSERT_DOUBLES_EQUAL_NOT_NAN(0.0, frobNorm, 0.1);
  84. }