This repository was archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkMeans.js
More file actions
85 lines (73 loc) · 2.59 KB
/
Copy pathkMeans.js
File metadata and controls
85 lines (73 loc) · 2.59 KB
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
import equalish from './equalish.js';
/**
* Performs one-dimensional k-means clustering on an array of
* numbers. Useful for finding n groups of "similar values".
*
* @exports kMeans
* @kind function
*
* @example
* import kMeans from '@datawrapper/shared/kMeans';
*
* const values = [1, 1.1, 1.2, 2.1, 3, 3.1, 3.2, 3.3, 7, 7.1, 10];
* // returns [[1, 1.1, 1.2, 2.1], [3, 3.1, 3.2, 3.3], [7, 7.1, 10]]
* kMeans(values, 3)
*
* @param {number[]} values - sorted array of numbers
* @param {number} numCluster - the desired cluster count
* @returns {array.<number[]>} - array of clusters
*/
export default function kMeans(values, numClusters) {
const clusters = [];
const centroids = [];
let oldCentroids = [];
let changed = false;
// initialise group arrays
for (let initClusters = 0; initClusters < numClusters; initClusters++) {
clusters[initClusters] = [];
}
// pick initial centroids at evenly distributed values
const initialCentroids = Math.round(values.length / (numClusters + 1));
for (let i = 0; i < numClusters; i++) {
centroids[i] = values[initialCentroids * (i + 1)];
}
let maxIterations = 20;
do {
// reset clusters
for (let j = 0; j < numClusters; j++) {
clusters[j].length = 0;
}
changed = false;
let newCluster = -1;
for (let i = 0; i < values.length; i++) {
let minDistance = -1;
// compute distances to centroid for each cluster
// to find the "nearest" cluster for this value
for (let j = 0; j < numClusters; j++) {
const distance = Math.abs(centroids[j] - values[i]);
if (minDistance === -1 || distance <= minDistance) {
minDistance = distance;
newCluster = j;
}
}
// push value into "nearest" cluster
clusters[newCluster].push(values[i]);
}
oldCentroids = centroids.slice(0);
// set new cluster centroids at avg of values in cluster
for (let j = 0; j < numClusters; j++) {
let total = 0;
for (let i = 0; i < clusters[j].length; i++) {
total += clusters[j][i];
}
centroids[j] = total / clusters[j].length;
}
// check if centroids are stable
for (let j = 0; j < numClusters; j++) {
if (!equalish(centroids[j], oldCentroids[j])) {
changed = true;
}
}
} while (changed && maxIterations-- > 0);
return clusters.filter(c => c.length);
}