-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialization.cpp
82 lines (63 loc) · 2.18 KB
/
initialization.cpp
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
#include <iostream>
#include <cstdlib>
#include "cluster.h"
#include "curve.h"
#include "distances.h"
#include "help_functions.h"
#include "initialization.h"
void k_random_selection(vector<const Curve*> ¢roids, int len) {
vector<int> all_random_points(len);
for (int i = 0; i < len; ++i) {
all_random_points[i] = i;
}
for (int i = 0; i < num_of_clusters; ++i) {
int pos = rand() % (len - i) + i;
swap(all_random_points[pos], all_random_points[i]);
centroids.push_back(&input_curves[all_random_points[i]]);
}
}
void k_means_pp(vector<const Curve*> ¢roids, int len, const char *metric) {
vector<double> min_distance(len, -1);
vector<bool> is_centroid(len, false);
int pos;
double max_sum = 0;
centroids.reserve(num_of_clusters);
for (int t = 0; ; ++t) {
if (!t) {
pos = rand() % len;
is_centroid[pos] = true;
centroids.push_back(&input_curves[pos]);
}
if (t == num_of_clusters - 1) {
break;
}
for (int i = 0; i < len; ++i) {
if (is_centroid[i]) {
continue;
}
double dist = compute_distance(input_curves[i], input_curves[pos], metric);
if (min_distance[i] == -1 || dist < min_distance[i]) {
if (min_distance[i] != -1) {
max_sum -= min_distance[i] * min_distance[i];
}
max_sum += dist * dist;
min_distance[i] = dist;
}
}
double value = uniform_distribution(0, max_sum);
double curr = 0;
for (int i = 0; i < len; ++i) {
if (is_centroid[i]) {
continue;
}
curr += min_distance[i] * min_distance[i];
if (curr >= value) {
pos = i;
break;
}
}
is_centroid[pos] = true;
centroids.push_back(&input_curves[pos]);
max_sum -= min_distance[pos] * min_distance[pos];
}
}