PDFParzen.cpp 2.4 KB

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