Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
clustering/kmeans.cpp
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
67 lines (55 sloc)
1.75 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <assert.h> | |
#include <iomanip> | |
#include <iostream> | |
#include <ostream> | |
#include <random> | |
#include <sstream> | |
#include <vector> | |
#include "points.h" | |
#include "draw.h" | |
#define K 3 | |
#define POINTS 100 | |
#define RANGE 640 | |
int main( int argc, char* argv[] ) | |
{ | |
std::array<Point,POINTS> points; | |
std::array<Centroid,K> centroids; | |
const int maxIterations = 10; | |
/* random initial positions | |
generate K initial points and then position the rest of the | |
points around the initial K */ | |
assert( points.size() >= centroids.size() ); | |
const auto jt = std::next( points.begin(), centroids.size() ); | |
for( auto it=points.begin(); it!=jt; it=std::next(it) ) | |
it->randomise( RANGE ); | |
for( auto it=jt; it!=points.end(); it=std::next(it) ) | |
{ | |
const auto cluster = std::distance(it, points.begin()) % centroids.size(); | |
it->randomise( *std::next(points.begin(),cluster), RANGE ); | |
} | |
/* random starting positions for the initial centroids */ | |
for( Centroid& c : centroids ) | |
{ | |
c.randomise( RANGE ); | |
std::cout << c << std::endl; | |
} | |
// do the clustering | |
bool updated = true; | |
for( int i=0; updated && i<maxIterations; ++i ) | |
{ | |
// k means | |
// display centroid positions | |
std::cout << "Iteration " << i << std::endl; | |
for( auto& c : centroids ) | |
std::cout << c << std::endl; | |
// save current state to file | |
std::stringstream ss; | |
ss << std::setfill('0') << std::setw(log10(maxIterations)+1) << i << "_clusters.bmp"; | |
draw( points.begin(), points.end(), | |
centroids.begin(), centroids.end(), | |
RANGE+1, RANGE+1, | |
ss.str() ); | |
} | |
return 0; | |
} |