PDFParzen.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * @file PDFParzen.cpp
  3. * @brief Normal Distribution / Gaussian PDF
  4. * @author Erik Rodner
  5. * @date 01/29/2008
  6. */
  7. #include <iostream>
  8. #include "vislearning/math/pdf/PDFParzen.h"
  9. using namespace OBJREC;
  10. const double sqrt_2_m_pi = sqrt(2*M_PI);
  11. using namespace std;
  12. // refactor-nice.pl: check this substitution
  13. // old: using namespace ice;
  14. using namespace NICE;
  15. // refactor-nice.pl: check this substitution
  16. // old: PDFParzen::PDFParzen( const Vector & _samples, double _kernel_h )
  17. PDFParzen::PDFParzen( const NICE::Vector & _samples, double _kernel_h )
  18. : samples(_samples), kernel_h(_kernel_h)
  19. {
  20. }
  21. PDFParzen::~PDFParzen()
  22. {
  23. }
  24. double PDFParzen::kernel ( double val ) const
  25. {
  26. return exp( - 0.5*val*val ) / sqrt_2_m_pi;
  27. }
  28. // refactor-nice.pl: check this substitution
  29. // old: double PDFParzen::getNLogDensity ( const Vector & x ) const
  30. double PDFParzen::getNLogDensity ( const NICE::Vector & x ) const
  31. {
  32. if ( x.size() != 1 )
  33. {
  34. fprintf (stderr, "PDFParzen::getNLogDensity: one dimensional distribution !\n");
  35. exit(-1);
  36. }
  37. double result = 0.0;
  38. double val = x[0];
  39. for ( size_t k = 0 ; k < samples.size() ; k++ )
  40. {
  41. result += kernel((samples[k] - val) / kernel_h);
  42. }
  43. result /= (samples.size() * kernel_h);
  44. return - log(result);
  45. }
  46. int PDFParzen::getDimension () const
  47. {
  48. return 1;
  49. }
  50. void PDFParzen::vis ( Gnuplot & gnuplot ) const
  51. {
  52. // building histogram
  53. map<double, double> hist;
  54. for ( size_t k = 0 ; k < samples.size() ; k++ )
  55. {
  56. double val = samples[k];
  57. if ( hist.find(val) == hist.end() )
  58. hist[val] = 1.0;
  59. else
  60. hist[val]++;
  61. }
  62. // refactor-nice.pl: check this substitution
  63. // old: ostringstream osfkt;
  64. std::ostringstream osfkt;
  65. osfkt << "f(y,x) = (1.0/(" << sqrt_2_m_pi << "))*(";
  66. osfkt << "exp(-((x - y)/" << kernel_h << ")**2));";
  67. // refactor-nice.pl: check this substitution
  68. // old: ostringstream os;
  69. std::ostringstream os;
  70. for ( size_t k = 0 ; k < samples.size() ; k++ )
  71. {
  72. os << "f(" << samples[k] << "," << "x)";
  73. if ( k != samples.size()-1 )
  74. os << "+";
  75. }
  76. gnuplot.cmd( osfkt.str().c_str() );
  77. gnuplot.set_style("lines");
  78. gnuplot.plot_equation ( os.str(), "parzen" );
  79. gnuplot.set_style("lines");
  80. gnuplot.plot_xy ( hist, "histogram" );
  81. }