-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmeans.js
212 lines (181 loc) · 5.8 KB
/
kmeans.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* kmeans.js
* Visualizes the k-Means clustering algorithm.
*
*
* @author: Hugo Janssen
* @date: 6/22/2015
*/
"use strict";
function kMeans(elt, w, h, numPoints, numClusters, maxIter) {
// the current iteration
var iter = 1,
centroids = [],
points = [];
var margin = {top: 30, right: 20, bottom: 20, left: 30},
width = w - margin.left - margin.right,
height = h - margin.top - margin.bottom;
var colors = d3.scale.category20().range();
var svg = d3.select(elt).append("svg")
.style("width", width + margin.left + margin.right)
.style("height", height + margin.top + margin.bottom);
var group = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.append("text")
.attr("class", "label")
.attr("transform", "translate(" + (width - margin.left - margin.right) +
"," + (height + margin.top + margin.bottom) + ")")
.text("");
/**
* Computes the euclidian distance between two points.
*/
function getEuclidianDistance(a, b) {
var dx = b.x - a.x,
dy = b.y - a.y;
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
/**
* Returns a point with the specified type and fill color and with random
* x,y-coordinates.
*/
function getRandomPoint(type, fill) {
return {
x: Math.round(Math.random() * width),
y: Math.round(Math.random() * height),
type: type,
fill: fill
};
}
/**
* Generates a specified number of random points of the specified type.
*/
function initializePoints(num, type) {
var result = [];
for (var i = 0; i < num; i++) {
var color = colors[i];
if (type !== "centroid") {
color = "#ccc";
}
var point = getRandomPoint(type, color);
point.id = point.type + "-" + i;
result.push(point);
}
return result;
}
/**
* Find the centroid that is closest to the specified point.
*/
function findClosestCentroid(point) {
var closest = {i: -1, distance: width * 2};
centroids.forEach(function(d, i) {
var distance = getEuclidianDistance(d, point);
// Only update when the centroid is closer
if (distance < closest.distance) {
closest.i = i;
closest.distance = distance;
}
});
return (centroids[closest.i]);
}
/**
* All points assume the color of the closest centroid.
*/
function colorizePoints() {
points.forEach(function(d) {
var closest = findClosestCentroid(d);
d.fill = closest.fill;
});
}
/**
* Computes the center of the cluster by taking the mean of the x and y
* coordinates.
*/
function computeClusterCenter(cluster) {
return [
d3.mean(cluster, function(d) { return d.x; }),
d3.mean(cluster, function(d) { return d.y; })
];
}
/**
* Moves the centroids to the center of their cluster.
*/
function moveCentroids() {
centroids.forEach(function(d) {
// Get clusters based on their fill color
var cluster = points.filter(function(e) {
return e.fill === d.fill;
});
// Compute the cluster centers
var center = computeClusterCenter(cluster);
// Move the centroid
d.x = center[0];
d.y = center[1];
});
}
/**
* Updates the chart.
*/
function update() {
var data = points.concat(centroids);
// The data join
var circle = group.selectAll("circle")
.data(data);
// Create new elements as needed
circle.enter().append("circle")
.attr("id", function(d) { return d.id; })
.attr("class", function(d) { return d.type; })
.attr("r", 5);
// Update old elements as needed
circle.transition().delay(100).duration(1000)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.style("fill", function(d) { return d.fill; });
// Remove old nodes
circle.exit().remove();
}
/**
* Updates the text in the label.
*/
function setText(text) {
svg.selectAll(".label").text(text);
}
/**
* Executes one iteration of the algorithm:
* - Fill the points with the color of the closest centroid (this makes it
* part of its cluster)
* - Move the centroids to the center of their cluster.
*/
function iterate() {
// Update label
setText("Iteration " + iter + " of " + maxIter);
// Colorize the points
colorizePoints();
// Move the centroids
moveCentroids();
// Update the chart
update();
}
/**
* The main function initializes the algorithm and calls an iteration every
* two seconds.
*/
function initialize() {
// Initialize random points and centroids
centroids = initializePoints(numClusters, "centroid");
points = initializePoints(numPoints, "point");
// initial drawing
update();
var interval = setInterval(function() {
if(iter < maxIter + 1) {
iterate();
iter++;
} else {
clearInterval(interval);
setText("Done");
}
}, 2 * 1000);
}
// Call the main function
initialize();
}