1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
|
/*-------------------------------------------------------------------------
*
* kmeans.c
* Generic k-means implementation
*
* Copyright (c) 2016, Paul Ramsey <pramsey@cleverelephant.ca>
*
*------------------------------------------------------------------------*/
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "kmeans.h"
#ifdef KMEANS_THREADED
#include <pthread.h>
#endif
static void
update_r(kmeans_config *config)
{
int i;
for (i = 0; i < config->num_objs; i++)
{
double distance, curr_distance;
int cluster, curr_cluster;
Pointer obj;
assert(config->objs != NULL);
assert(config->num_objs > 0);
assert(config->centers);
assert(config->clusters);
obj = config->objs[i];
/*
* Don't try to cluster NULL objects, just add them
* to the "unclusterable cluster"
*/
if (!obj)
{
config->clusters[i] = KMEANS_NULL_CLUSTER;
continue;
}
/* Initialize with distance to first cluster */
curr_distance = (config->distance_method)(obj, config->centers[0]);
curr_cluster = 0;
/* Check all other cluster centers and find the nearest */
for (cluster = 1; cluster < config->k; cluster++)
{
distance = (config->distance_method)(obj, config->centers[cluster]);
if (distance < curr_distance)
{
curr_distance = distance;
curr_cluster = cluster;
}
}
/* Store the nearest cluster this object is in */
config->clusters[i] = curr_cluster;
}
}
static void
update_means(kmeans_config *config)
{
int i;
for (i = 0; i < config->k; i++)
{
/* Update the centroid for this cluster */
(config->centroid_method)(config->objs, config->clusters, config->num_objs, i, config->centers[i]);
}
}
#ifdef KMEANS_THREADED
static void * update_r_threaded_main(void *args)
{
kmeans_config *config = (kmeans_config*)args;
update_r(config);
pthread_exit(args);
}
static void update_r_threaded(kmeans_config *config)
{
/* Computational complexity is function of objs/clusters */
/* We only spin up threading infra if we need more than one core */
/* running. We keep the threshold high so the overhead of */
/* thread management is small compared to thread compute time */
int num_threads = config->num_objs * config->k / KMEANS_THR_THRESHOLD;
/* Can't run more threads than the maximum */
num_threads = (num_threads > KMEANS_THR_MAX ? KMEANS_THR_MAX : num_threads);
/* If the problem size is small, don't bother w/ threading */
if (num_threads < 1)
{
update_r(config);
}
else
{
pthread_t thread[KMEANS_THR_MAX];
pthread_attr_t thread_attr;
kmeans_config thread_config[KMEANS_THR_MAX];
int obs_per_thread = config->num_objs / num_threads;
int i, rc;
for (i = 0; i < num_threads; i++)
{
/*
* Each thread gets a copy of the config, but with the list pointers
* offest to the start of the batch the thread is responsible for, and the
* object count number adjusted similarly.
*/
memcpy(&(thread_config[i]), config, sizeof(kmeans_config));
thread_config[i].objs += i*obs_per_thread;
thread_config[i].clusters += i*obs_per_thread;
thread_config[i].num_objs = obs_per_thread;
if (i == num_threads-1)
{
thread_config[i].num_objs += config->num_objs - num_threads*obs_per_thread;
}
/* Initialize and set thread detached attribute */
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
/* Now we just run the thread, on its subset of the data */
rc = pthread_create(&thread[i], &thread_attr, update_r_threaded_main, (void *) &thread_config[i]);
if (rc)
{
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&thread_attr);
/* Wait for all calculations to complete */
for (i = 0; i < num_threads; i++)
{
void *status;
rc = pthread_join(thread[i], &status);
if (rc)
{
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
}
}
int update_means_k;
pthread_mutex_t update_means_k_mutex;
static void *
update_means_threaded_main(void *arg)
{
kmeans_config *config = (kmeans_config*)arg;
int i = 0;
do
{
pthread_mutex_lock (&update_means_k_mutex);
i = update_means_k;
update_means_k++;
pthread_mutex_unlock (&update_means_k_mutex);
if (i < config->k)
(config->centroid_method)(config->objs, config->clusters, config->num_objs, i, config->centers[i]);
}
while (i < config->k);
pthread_exit(arg);
}
static void
update_means_threaded(kmeans_config *config)
{
/* We only spin up threading infra if we need more than one core */
/* running. We keep the threshold high so the overhead of */
/* thread management is small compared to thread compute time */
int num_threads = config->num_objs / KMEANS_THR_THRESHOLD;
/* Can't run more threads than the maximum */
num_threads = (num_threads > KMEANS_THR_MAX ? KMEANS_THR_MAX : num_threads);
/* If the problem size is small, don't bother w/ threading */
if (num_threads < 1)
{
update_means(config);
}
else
{
/* Mutex protected counter to drive threads */
pthread_t thread[KMEANS_THR_MAX];
pthread_attr_t thread_attr;
int i, rc;
pthread_mutex_init(&update_means_k_mutex, NULL);
update_means_k = 0;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
/* Create threads to perform computation */
for (i = 0; i < num_threads; i++)
{
/* Now we just run the thread, on its subset of the data */
rc = pthread_create(&thread[i], &thread_attr, update_means_threaded_main, (void *) config);
if (rc)
{
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&thread_attr);
/* Watch until completion */
for (i = 0; i < num_threads; i++)
{
void *status;
rc = pthread_join(thread[i], &status);
if (rc)
{
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
pthread_mutex_destroy(&update_means_k_mutex);
}
}
#endif /* KMEANS_THREADED */
kmeans_result
kmeans(kmeans_config *config)
{
int iterations = 0;
int *clusters_last;
size_t clusters_sz = sizeof(int)*config->num_objs;
assert(config);
assert(config->objs);
assert(config->num_objs);
assert(config->distance_method);
assert(config->centroid_method);
assert(config->centers);
assert(config->k);
assert(config->clusters);
assert(config->k <= config->num_objs);
/* Zero out cluster numbers, just in case user forgets */
memset(config->clusters, 0, clusters_sz);
/* Set default max iterations if necessary */
if (!config->max_iterations)
config->max_iterations = KMEANS_MAX_ITERATIONS;
/*
* Previous cluster state array. At this time, r doesn't mean anything
* but it's ok
*/
clusters_last = kmeans_malloc(clusters_sz);
while (1)
{
LW_ON_INTERRUPT(kmeans_free(clusters_last); return KMEANS_ERROR);
/* Store the previous state of the clustering */
memcpy(clusters_last, config->clusters, clusters_sz);
#ifdef KMEANS_THREADED
update_r_threaded(config);
update_means_threaded(config);
#else
update_r(config);
update_means(config);
#endif
/*
* if all the cluster numbers are unchanged since last time,
* we are at a stable solution, so we can stop here
*/
if (memcmp(clusters_last, config->clusters, clusters_sz) == 0)
{
kmeans_free(clusters_last);
config->total_iterations = iterations;
return KMEANS_OK;
}
if (iterations++ > config->max_iterations)
{
kmeans_free(clusters_last);
config->total_iterations = iterations;
return KMEANS_EXCEEDED_MAX_ITERATIONS;
}
}
kmeans_free(clusters_last);
config->total_iterations = iterations;
return KMEANS_ERROR;
}
|