| 31 | // ---------------------------------------------------------------------------------------- |
| 32 | |
| 33 | void test_kkmeans_initial_assignments ( |
| 34 | ) |
| 35 | { |
| 36 | typedef matrix<double,1,1> sample_type; |
| 37 | typedef linear_kernel<sample_type> kernel_type; |
| 38 | kkmeans<kernel_type> kmeans(kcentroid<kernel_type>(kernel_type(), 1e-9)); |
| 39 | |
| 40 | const auto make_samples = [](std::initializer_list<double> values) |
| 41 | { |
| 42 | std::vector<sample_type> samples; |
| 43 | for (double value : values) |
| 44 | { |
| 45 | sample_type sample; |
| 46 | sample = value; |
| 47 | samples.push_back(sample); |
| 48 | } |
| 49 | return samples; |
| 50 | }; |
| 51 | const auto check_center = [&](unsigned long index, double value, unsigned long count) |
| 52 | { |
| 53 | sample_type expected; |
| 54 | expected = value; |
| 55 | const auto& center = kmeans.get_kcentroid(index); |
| 56 | DLIB_TEST(center.samples_trained() == count); |
| 57 | DLIB_TEST(center(expected) < 1e-6); |
| 58 | }; |
| 59 | |
| 60 | // A single cluster must be recomputed from the samples even though every |
| 61 | // assignment is zero. A zero iteration budget still leaves the seed intact. |
| 62 | const auto samples = make_samples({2,4}); |
| 63 | const auto seed = make_samples({10}); |
| 64 | kmeans.train(samples, seed, 0); |
| 65 | check_center(0, 10, 1); |
| 66 | kmeans.train(samples, seed, 1); |
| 67 | check_center(0, 3, 2); |
| 68 | kmeans.train(samples, seed); |
| 69 | check_center(0, 3, 2); |
| 70 | |
| 71 | // The same first-pass requirement applies when several centers are present |
| 72 | // but all samples initially choose the first one. |
| 73 | kmeans.set_number_of_centers(2); |
| 74 | kmeans.train(samples, make_samples({0,100}), 1); |
| 75 | check_center(0, 3, 2); |
| 76 | DLIB_TEST(kmeans.get_kcentroid(1).samples_trained() == 0); |
| 77 | |
| 78 | // Training starts from the supplied seeds each time, including after a |
| 79 | // change in the number of samples or a previous run with the same labels. |
| 80 | const auto two_clusters = make_samples({0,2,8,10}); |
| 81 | const auto two_seeds = make_samples({0,10}); |
| 82 | for (unsigned int i = 0; i < 2; ++i) |
| 83 | { |
| 84 | kmeans.train(two_clusters, two_seeds); |
| 85 | check_center(0, 1, 2); |
| 86 | check_center(1, 9, 2); |
| 87 | } |
| 88 | kmeans.train(make_samples({0,2,8,10,12}), two_seeds); |
| 89 | check_center(0, 1, 2); |
| 90 | check_center(1, 10, 3); |
no test coverage detected