TestKMedian.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifdef NICE_USELIB_CPPUNIT
  2. #include <string>
  3. #include <exception>
  4. #include "TestKMedian.h"
  5. #include "vislearning/math/distances/genericDistance.h"
  6. const bool verboseStartEnd = true;
  7. const bool verbose = false;
  8. const std::string distanceType = "euclidean";
  9. using namespace OBJREC;
  10. using namespace NICE;
  11. using namespace std;
  12. CPPUNIT_TEST_SUITE_REGISTRATION( TestKMedian );
  13. void TestKMedian::setUp() {
  14. }
  15. void TestKMedian::tearDown() {
  16. }
  17. void TestKMedian::testKMedianClustering()
  18. {
  19. if (verboseStartEnd)
  20. std::cerr << "================== TestKMedian::testKMedianClustering ===================== " << std::endl;
  21. OBJREC::KMedian kMedian ( 2 /* noClasses */, "euclidean" /*distanceMode*/ );
  22. //create some artificial data
  23. NICE::VVector features;
  24. NICE::Vector x1 (2); x1[0] = 1; x1[1] = 1; features.push_back(x1);
  25. NICE::Vector x2 (2); x2[0] = 4; x2[1] = 1; features.push_back(x2);
  26. NICE::Vector x3 (2); x3[0] = 2; x3[1] = 4; features.push_back(x3);
  27. NICE::Vector x4 (2); x4[0] = 10; x4[1] = 3; features.push_back(x4);
  28. NICE::Vector x5 (2); x5[0] = 8; x5[1] = 3; features.push_back(x5);
  29. NICE::Vector x6 (2); x6[0] = 4; x6[1] = 3; features.push_back(x6);
  30. NICE::Vector x7 (2); x7[0] = 3; x7[1] = 2; features.push_back(x7);
  31. NICE::Vector x8 (2); x8[0] = 1; x8[1] = 3; features.push_back(x8);
  32. NICE::Vector x9 (2); x9[0] = 9; x9[1] = 2; features.push_back(x9);
  33. //cluster data
  34. NICE::VVector prototypes;
  35. std::vector<double> weights;
  36. std::vector<int> assignment;
  37. kMedian.cluster ( features, prototypes, weights, assignment );
  38. //check whether the results fits the ground truth
  39. //NOTE
  40. // If no random initialization is activated, we initially grab x2 and x8.
  41. // After 3 iterations, we should have converged and obtain x5 and x7.
  42. NICE::VectorDistance<double> * distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  43. if ( verbose )
  44. {
  45. std::cerr << " x9: " << x9 << " cl1: " << prototypes[0] << std::endl;
  46. std::cerr << " x7: " << x7 << " cl2: " << prototypes[1] << std::endl;
  47. }
  48. double distX9Cl1 ( distancefunction->calculate( x9, prototypes[0] ) );
  49. double distX7Cl2 ( distancefunction->calculate( x7, prototypes[1] ) );
  50. CPPUNIT_ASSERT_DOUBLES_EQUAL( distX9Cl1, 0.0, 1e-8);
  51. CPPUNIT_ASSERT_DOUBLES_EQUAL( distX7Cl2, 0.0, 1e-8);
  52. std::cerr << " successfull " << std::endl;
  53. if (verboseStartEnd)
  54. std::cerr << "================== TestKMedian::testKMedianClustering done ===================== " << std::endl;
  55. }
  56. #endif