forked from simple-statistics/simple-statistics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk_means_cluster.test.js
98 lines (88 loc) · 2.86 KB
/
k_means_cluster.test.js
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
/* eslint no-shadow: 0 */
const test = require("tap").test;
const ss = require("../dist/simple-statistics.js");
// Force shuffling to return the first points in the array to ensure
// reproducibility of tests. This works because of the way the Fisher-Yates
// shuffle selects array elements via multiplication and flooring.
function nonRNG() {
return 1.0 - ss.epsilon;
}
test("k-means clustering test", function (t) {
t.test(
"Single cluster of one point contains only that point",
function (t) {
const points = [[0.5]];
const { labels, centroids } = ss.kMeansCluster(points, 1, nonRNG);
t.same(labels, [0]);
t.same(centroids, [[0.5]]);
t.end();
}
);
t.test("Single cluster of two points contains both points", function (t) {
const points = [[0.0], [1.0]];
const { labels, centroids } = ss.kMeansCluster(points, 1, nonRNG);
t.same(labels, [0, 0]);
t.same(centroids, [[0.5]]);
t.end();
});
t.test(
"Two clusters of two points puts each point in its own cluster",
function (t) {
const points = [[0.0], [1.0]];
const { labels, centroids } = ss.kMeansCluster(points, 2, nonRNG);
t.same(labels, [0, 1]);
t.same(centroids, [[0.0], [1.0]]);
t.end();
}
);
t.test(
"Two clusters of four paired points puts each pair in a cluster",
function (t) {
const points = [[0.0], [1.0], [0.0], [1.0]];
const { labels, centroids } = ss.kMeansCluster(points, 2, nonRNG);
t.same(labels, [0, 1, 0, 1]);
t.same(centroids, [[0.0], [1.0]]);
t.end();
}
);
t.test(
"Two clusters of two 2D points puts each point in its own cluster",
function (t) {
const points = [
[0.0, 0.5],
[1.0, 0.5]
];
const { labels, centroids } = ss.kMeansCluster(points, 2, nonRNG);
t.same(labels, [0, 1]);
t.same(centroids, [
[0.0, 0.5],
[1.0, 0.5]
]);
t.end();
}
);
t.test("Base case of one value", function (t) {
t.throws(() => {
ss.kMeansCluster([1], 2, nonRNG);
});
t.end();
});
t.test(
"Two clusters of three 2D points puts two points in one cluster and one in the other",
function (t) {
const points = [
[0.0, 0.5],
[1.0, 0.5],
[0.1, 0.0]
];
const { labels, centroids } = ss.kMeansCluster(points, 2, nonRNG);
t.same(labels, [0, 1, 0]);
t.same(centroids, [
[0.05, 0.25],
[1.0, 0.5]
]);
t.end();
}
);
t.end();
});