diff options
author | Paul Duncan <pabs@pablotron.org> | 2019-02-02 03:25:32 -0500 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2019-02-02 03:25:32 -0500 |
commit | bf8f5126a6d621be4996df842c70d60297f87706 (patch) | |
tree | a35277fc9f317fdb880d35cb4f9fbf3c6fa0f970 | |
parent | 6155d919c78a767ea4e503c48fd60d5186c2c546 (diff) | |
download | kmeans-bf8f5126a6d621be4996df842c70d60297f87706.tar.bz2 kmeans-bf8f5126a6d621be4996df842c70d60297f87706.zip |
add km_search(), main.c
-rw-r--r-- | main.c | 91 |
1 files changed, 91 insertions, 0 deletions
@@ -0,0 +1,91 @@ +#include <stdio.h> // fprintf() +#include <unistd.h> // EXIT_{FAILURE,SUCCESS} +#include <stdlib.h> // exit() +#include "km.h" + +#define UNUSED(a) ((void) (a)) + +// >> puts [[-1, -1], [-1, 1], [1, 1], [1, -1]].reduce([]) { |r, c| 5.times { r << [0.5 + 0.25 * c[0] + 0.4 * rand - 0.2, 0.5 + 0.25 * c[1] + 0.4 * rand - 0.2] }; r }.map { |row| '%1.3f, %1.3f,' % row } +static const float +DATA[] = { + 0.132, 0.190, + 0.313, 0.187, + 0.076, 0.276, + 0.443, 0.414, + 0.136, 0.060, + 0.344, 0.815, + 0.259, 0.760, + 0.211, 0.949, + 0.103, 0.903, + 0.173, 0.818, + 0.873, 0.735, + 0.783, 0.593, + 0.845, 0.674, + 0.808, 0.868, + 0.871, 0.947, + 0.917, 0.090, + 0.691, 0.058, + 0.840, 0.357, + 0.783, 0.275, + 0.807, 0.336, +}; + +#define die(...) do { \ + fputs("FATAL: ", stderr); \ + fprintf(stderr, __VA_ARGS__); \ + fputs("\n", stderr); \ + exit(EXIT_FAILURE); \ +} while (0) + +#define MAX_CLUSTERS 10 +#define NUM_TESTS 10 + +static const km_shape_t +SHAPE = { + .num_floats = 2, + .num_ints = 0, +}; + +static void +on_search_row( + const km_search_row_t * const row, + void *cb_data +) { + UNUSED(cb_data); + + printf("%zu,%0.5f,%zu\n", + row->num_clusters, + row->mean_distance, + row->num_empty_clusters + ); +} + +int main(int argc, char *argv[]) { + km_set_t set; + UNUSED(argc); + UNUSED(argv); + + // init data set + if (!km_set_init(&set, &SHAPE, 20)) { + die("km_set_init() failed"); + } + + // push rows + if (!km_set_push_rows(&set, 20, DATA, NULL)) { + die("km_set_push_rows() failed"); + } + + // print headers + printf("num_clusters,mean_distance,num_empty_clusters\n"); + + // search for best solution + if (!km_search(&set, MAX_CLUSTERS, NUM_TESTS, on_search_row, NULL)) { + die("km_search()"); + } + + // finalize data set + km_set_fini(&set); + + // return success + return 0; +} |