123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582 |
- #ifdef NICE_USELIB_OPENMP
- #include <omp.h>
- #endif
- #include <iostream>
- #include <map>
- #include <algorithm> //to easily find the smallest value in a map
- #include "vislearning/math/cluster/KMedian.h"
- #include "vislearning/math/distances/genericDistance.h"
- #include <set>
- using namespace OBJREC;
- using namespace std;
- using namespace NICE;
- typedef std::pair<int, double> MyPairType;
- struct CompareSecond
- {
- bool operator()(const MyPairType& left, const MyPairType& right) const
- {
- return left.second < right.second;
- }
- };
- #undef DEBUG_KMEDIAN_ASSIGNMENTS
- #undef DEBUG_KMEDIAN_PROTOCOMP
- KMedian::KMedian() : ClusterAlgorithm()
- {
- this->noClusters = 20;
- this->distanceType = "euclidean";
- this->distancefunction = NULL;
- this->d_minDelta = 1e-5;
- this->i_maxIterations = 200;
- }
- KMedian::KMedian(const int & _noClusters, const std::string & _distanceType) :
- noClusters(_noClusters), distanceType(_distanceType)
- {
-
- this->distancefunction = GenericDistanceSelection::selectDistance( this->distanceType );
-
- this->d_minDelta = 1e-5;
- this->i_maxIterations = 200;
- }
- KMedian::KMedian( const NICE::Config * _conf, const std::string & _confSection)
- {
- this->initFromConfig( _conf, _confSection );
- }
- KMedian::~KMedian()
- {
- if ( this->distancefunction != NULL )
- {
- delete this->distancefunction;
- this->distancefunction = NULL ;
- }
- }
- void KMedian::initFromConfig( const NICE::Config* _conf, const std::string& _confSection )
- {
- this->noClusters = _conf->gI( _confSection, "noClusters", 20);
- this->distanceType = _conf->gS( _confSection, "distanceType", "euclidean" );
- this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
- this->d_minDelta = _conf->gD( _confSection, "minDelta", 1e-5 );
- this->i_maxIterations = _conf->gI( _confSection, "maxIterations", 200);
- }
- void KMedian::initial_guess(const VVector & features, VVector & prototypes)
- {
- int j = 0;
- std::set<int, std::greater<int> > mark;
- for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
- {
- int k;
- do
- {
- k = rand() % features.size();
- } while (mark.find(k) != mark.end());
- mark.insert(mark.begin(), k);
- *i = features[k];
- }
- }
- int KMedian::compute_prototypes(const VVector & features, VVector & prototypes,
- std::vector<double> & weights, const std::vector<int> & assignment)
- {
-
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << "initial assignments: ";
- for (std::vector<int>::const_iterator assignIt = assignment.begin(); assignIt != assignment.end(); assignIt++)
- {
- std::cerr << " " << *assignIt;
- }
- std::cerr << std::endl;
- #endif
-
-
- for (int k = 0; k < noClusters; k++)
- {
- prototypes[k].set(0);
- weights[k] = 0;
- }
-
- NICE::VectorT<int> numberOfCurrentAssignments ( noClusters ) ;
- numberOfCurrentAssignments.set ( 0 );
-
- int exCnt = 0;
-
- for (VVector::const_iterator i = features.begin(); i != features.end(); i++, exCnt++)
- {
- int k = assignment[exCnt];
-
- numberOfCurrentAssignments[ k ] ++;
- }
-
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << "k-median -- current assignmens: " << numberOfCurrentAssignments << std::endl << "noClusters: " << noClusters << std::endl;
- #endif
-
-
- #pragma omp parallel for
- for (int clusterCnt = 0; clusterCnt < noClusters; clusterCnt++)
- {
- NICE::Vector overallDistances ( numberOfCurrentAssignments[ clusterCnt ] );
- VVector::const_iterator lastExampleWorkedOn = features.begin();
- int i_idxOfLastExampleWorkedOn ( 0 );
- uint i_exCntInt ( 0 );
-
-
- std::map<int,double> distancesWithinCluster;
- for (VVector::const_iterator featIt = features.begin(); featIt != features.end(); featIt++, i_exCntInt++)
- {
- int k = assignment[i_exCntInt];
-
-
- if ( k != clusterCnt)
- {
- continue;
- }
-
- uint exCntIntTmp ( i_idxOfLastExampleWorkedOn );
- for (VVector::const_iterator j = lastExampleWorkedOn ; j != features.end(); j++, exCntIntTmp++)
- {
- int kTmp;
- if ( exCntIntTmp < assignment.size() )
- kTmp = assignment[exCntIntTmp];
- else
- {
-
- std::cerr << "ERROR: exCntIntTmp >= assignment.size() " << exCntIntTmp << " " << assignment.size() << std::endl;
- }
-
-
- if ( kTmp != clusterCnt)
- continue;
-
-
- double dist ( distancefunction->calculate( *featIt, *j) );
- if ( i_exCntInt < features.size() )
- {
- distancesWithinCluster[ i_exCntInt ] += dist;
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << "increase " << i_exCntInt << " by " << dist << " for " <<*featIt << " and " << *j << std::endl;
- #endif
- }
- else
- {
-
- std::cerr << "ERROR: i_exCntInt >= features.size() " << i_exCntInt << " " << features.size() << std::endl;
- }
- if ( i_exCntInt != exCntIntTmp )
- {
- if (exCntIntTmp < features.size() )
- {
- distancesWithinCluster[ exCntIntTmp ] += dist;
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << "increase also " << exCntIntTmp << " by " << dist << std::endl;
- #endif
- }
- else
- std::cerr << "ERROR: exCntIntTmp >= features.size() " << exCntIntTmp << " " << features.size() << std::endl;
- }
-
- }
-
-
- if ( ( featIt != features.end()) && ( (featIt +1 ) != features.end()) )
- {
- lastExampleWorkedOn = ( featIt + 1 );
- i_idxOfLastExampleWorkedOn = i_exCntInt+1;
- }
- }
-
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << "distances for cluster " << clusterCnt << " ";
- for(std::map<int,double>::const_iterator distIt = distancesWithinCluster.begin(); distIt != distancesWithinCluster.end(); distIt++)
- {
- std::cerr << distIt->first << " " << distIt->second << " ";
- }
- std::cerr << std::endl;
- #endif
-
-
- int idxOfClusterMedian ( (min_element(distancesWithinCluster.begin(), distancesWithinCluster.end(), CompareSecond()))->first );
-
- #pragma omp critical
- prototypes[clusterCnt] = features[idxOfClusterMedian];
-
-
- }
-
- #ifdef DEBUG_KMEDIAN_PROTOCOMP
- std::cerr << " ---- prototypes after current iteration: --- " << std::endl;
- for (NICE::VVector::const_iterator protoIt = prototypes.begin(); protoIt != prototypes.end(); protoIt++)
- {
- std::cerr << *protoIt << " ";
- }
-
- std::cerr << std::endl;
- #endif
- return 0;
- }
- double KMedian::compute_delta(const VVector & oldprototypes,
- const VVector & prototypes)
- {
- double distance = 0;
- for (uint k = 0; k < oldprototypes.size(); k++)
- {
- distance += distancefunction->calculate(oldprototypes[k], prototypes[k]);
-
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "KMedian::compute_delta: Distance:",
- distancefunction->calculate(oldprototypes[k], prototypes[k]));
- #endif
- }
- return distance;
- }
- double KMedian::compute_assignments(const VVector & features,
- const VVector & prototypes,
- std::vector<int> & assignment)
- {
- int index = 0;
- for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
- {
- const NICE::Vector & x = *i;
- double mindist = std::numeric_limits<double>::max();
- int minclass = 0;
- int c = 0;
-
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "computing nearest prototype for std::vector %d\n",
- index);
- #endif
-
- for (VVector::const_iterator j = prototypes.begin(); j
- != prototypes.end(); j++, c++)
- {
- const NICE::Vector & p = *j;
- double distance = distancefunction->calculate(p, x);
-
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "KMedian::compute_delta: Distance: %f\n",
- distancefunction->calculate(p, x));
- #endif
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- cerr << p << endl;
- cerr << x << endl;
- fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
- #endif
- if (distance < mindist)
- {
- minclass = c;
- mindist = distance;
- }
- }
- assignment[index] = minclass;
- }
- return 0.0;
- }
- double KMedian::compute_weights(const VVector & features,
- std::vector<double> & weights,
- std::vector<int> & assignment)
- {
- for (int k = 0; k < noClusters; k++)
- weights[k] = 0;
- int j = 0;
- for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
- {
- int k = assignment[j];
- weights[k]++;
- }
- for (int k = 0; k < noClusters; k++)
- weights[k] = weights[k] / features.size();
- return 0.0;
- }
- void KMedian::cluster(const NICE::VVector & features,
- NICE::VVector & prototypes,
- std::vector<double> & weights,
- std::vector<int> & assignment)
- {
- NICE::VVector oldprototypes;
- prototypes.clear();
- weights.clear();
- assignment.clear();
- weights.resize(noClusters, 0);
- assignment.resize(features.size(), 0);
- int dimension;
- if ((int) features.size() >= noClusters)
- dimension = features[0].size();
- else
- {
- fprintf(stderr,
- "FATAL ERROR: Not enough feature vectors provided for kMedians -- number of Features: %i - number of clusters: %i\n", (int) features.size(), noClusters);
- exit(-1);
- }
- for (int k = 0; k < noClusters; k++)
- {
- prototypes.push_back( NICE::Vector(dimension) );
- prototypes[k].set(0);
- }
-
- bool successKMedian ( false );
- int iterations ( 0 );
- double delta ( std::numeric_limits<double>::max() );
-
- while ( !successKMedian )
- {
-
- successKMedian = true;
-
- this->initial_guess(features, prototypes);
- iterations = 0;
- delta = std::numeric_limits<double>::max();
-
- do
- {
- iterations++;
-
- std::cerr << "k-median iteration " << iterations << std::endl;
-
- this->compute_assignments( features, prototypes, assignment );
- if (iterations > 1)
- oldprototypes = prototypes;
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "KMedian::cluster compute_prototypes\n");
- #endif
-
- if ( this->compute_prototypes( features, prototypes, weights, assignment ) < 0 )
- {
- fprintf(stderr, "KMedian::cluster restart\n");
- successKMedian = false;
- break;
- }
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "KMedian::cluster compute_delta\n");
- #endif
-
- if (iterations > 1)
- delta = this->compute_delta( oldprototypes, prototypes );
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- this->print_iteration( iterations, prototypes, delta );
- #endif
- } while ((delta > d_minDelta) && (iterations < i_maxIterations));
-
- }
- std::cerr << "ended optimization -- delta: " << delta << " of d_minDelta: " << d_minDelta << " --- and iterations: " << iterations << " of i_maxIterations: " << i_maxIterations << std::endl;
-
- #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
- fprintf(stderr, "KMedian::cluster: iterations = %d, delta = %f\n",
- iterations, delta);
- #endif
- this->compute_weights( features, weights, assignment );
- }
- void KMedian::print_iteration( int iterations, VVector & prototypes, double delta )
- {
- if (iterations > 1)
- fprintf(stderr, "KMedian::cluster: iteration=%d delta=%f\n", iterations,
- delta);
- else
- fprintf(stderr, "KMedian::cluster: iteration=%d\n", iterations);
- int k = 0;
- for (VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
- {
- fprintf(stderr, "class (%d)\n", k);
- cerr << "prototype = " << (*i) << endl;
- }
- }
- void KMedian::restore ( std::istream & is, int format )
- {
-
- this->clear();
-
-
- if ( is.good() )
- {
-
- std::string tmp;
- is >> tmp;
-
- if ( ! this->isStartTag( tmp, "KMedian" ) )
- {
- std::cerr << " WARNING - attempt to restore KMedian, but start flag " << tmp << " does not match! Aborting... " << std::endl;
- throw;
- }
-
- bool b_endOfBlock ( false ) ;
-
- while ( !b_endOfBlock )
- {
- is >> tmp;
-
- if ( this->isEndTag( tmp, "KMedian" ) )
- {
- b_endOfBlock = true;
- continue;
- }
-
- tmp = this->removeStartTag ( tmp );
-
- if ( tmp.compare("noClusters") == 0 )
- {
- is >> this->noClusters;
- is >> tmp;
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("distanceType") == 0 )
- {
- is >> this->distanceType;
-
- this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
- is >> tmp;
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("distancefunction") == 0 )
- {
-
- is >> tmp;
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("d_minDelta") == 0 )
- {
- is >> this->d_minDelta;
- is >> tmp;
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("i_maxIterations") == 0 )
- {
- is >> this->i_maxIterations;
- is >> tmp;
- tmp = this->removeEndTag ( tmp );
- }
- else
- {
- std::cerr << "WARNING -- unexpected KMedian object -- " << tmp << " -- for restoration... aborting" << std::endl;
- throw;
- }
- }
- }
- else
- {
- std::cerr << "KMedian::restore -- InStream not initialized - restoring not possible!" << std::endl;
- throw;
- }
- }
- void KMedian::store ( std::ostream & os, int format ) const
- {
- if (os.good())
- {
-
- os << this->createStartTag( "KMedian" ) << std::endl;
-
- os << this->createStartTag( "noClusters" ) << std::endl;
- os << this->noClusters << std::endl;
- os << this->createEndTag( "noClusters" ) << std::endl;
- os << this->createStartTag( "distanceType" ) << std::endl;
- os << this->distanceType << std::endl;
- os << this->createEndTag( "distanceType" ) << std::endl;
-
- os << this->createStartTag( "distancefunction" ) << std::endl;
-
- os << this->createEndTag( "distancefunction" ) << std::endl;
- os << this->createStartTag( "d_minDelta" ) << std::endl;
- os << this->d_minDelta << std::endl;
- os << this->createEndTag( "d_minDelta" ) << std::endl;
-
- os << this->createStartTag( "i_maxIterations" ) << std::endl;
- os << this->i_maxIterations << std::endl;
- os << this->createEndTag( "i_maxIterations" ) << std::endl;
-
-
- os << this->createEndTag( "KMedian" ) << std::endl;
- }
- else
- {
- std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
- }
- }
- void KMedian::clear ()
- {
- if ( this->distancefunction != NULL )
- {
- delete this->distancefunction;
- this->distancefunction = NULL ;
- }
- }
|