the k-means example implements the k-means clustering algorithm
| 31 | |
| 32 | // the k-means example implements the k-means clustering algorithm |
| 33 | int main() |
| 34 | { |
| 35 | // number of clusters |
| 36 | size_t k = 6; |
| 37 | |
| 38 | // number of points |
| 39 | size_t n_points = 4500; |
| 40 | |
| 41 | // height and width of image |
| 42 | size_t height = 800; |
| 43 | size_t width = 800; |
| 44 | |
| 45 | // get default device and setup context |
| 46 | compute::device gpu = compute::system::default_device(); |
| 47 | compute::context context(gpu); |
| 48 | compute::command_queue queue(context, gpu); |
| 49 | |
| 50 | // generate random, uniformily-distributed points |
| 51 | compute::default_random_engine random_engine(queue); |
| 52 | compute::uniform_real_distribution<float_> uniform_distribution(0, 800); |
| 53 | |
| 54 | compute::vector<float2_> points(n_points, context); |
| 55 | uniform_distribution.generate( |
| 56 | compute::make_buffer_iterator<float_>(points.get_buffer(), 0), |
| 57 | compute::make_buffer_iterator<float_>(points.get_buffer(), n_points * 2), |
| 58 | random_engine, |
| 59 | queue |
| 60 | ); |
| 61 | |
| 62 | // initialize all points to cluster 0 |
| 63 | compute::vector<int_> clusters(n_points, context); |
| 64 | compute::fill(clusters.begin(), clusters.end(), 0, queue); |
| 65 | |
| 66 | // create initial means with the first k points |
| 67 | compute::vector<float2_> means(k, context); |
| 68 | compute::copy_n(points.begin(), k, means.begin(), queue); |
| 69 | |
| 70 | // k-means clustering program source |
| 71 | const char k_means_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE( |
| 72 | __kernel void assign_clusters(__global const float2 *points, |
| 73 | __global const float2 *means, |
| 74 | const int k, |
| 75 | __global int *clusters) |
| 76 | { |
| 77 | const uint gid = get_global_id(0); |
| 78 | |
| 79 | const float2 point = points[gid]; |
| 80 | |
| 81 | // find the closest cluster |
| 82 | float current_distance = 0; |
| 83 | int closest_cluster = -1; |
| 84 | |
| 85 | // find closest cluster mean to the point |
| 86 | for(int i = 0; i < k; i++){ |
| 87 | const float2 mean = means[i]; |
| 88 | |
| 89 | int distance_to_mean = distance(point, mean); |
| 90 | if(closest_cluster == -1 || distance_to_mean < current_distance){ |
nothing calls this directly
no test coverage detected