-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
534 lines (491 loc) · 16.7 KB
/
index.html
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fuzzy C-Means Clustering: A Graphical Demonstration</title>
<script src="js/d3.v3.min.js" charset="utf-8"></script>
<script src="js/jquery.js"></script>
<script src="js/materialize.min.js"></script>
<style type="text/css">
/* Format X and Y Axis */
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: 'Roboto', sans-serif;
font-size: 11px;
}
.fixed {
[type="checkbox"],
[type="radio"] {
+label {
pointer-events: auto;
}
}
}
</style>
</head>
<body style="background-color:#fcfcfc">
<div class="container">
<h2>Fuzzy C-Means Clustering</h2>
<div class="row">
<div class="col m12 l6">
<div id="plot"></div>
<p id="lblStatus"></p>
<p id="objStat" style="display:block;">
<span id="Jval"> - </span>
</p>
</div>
<div class="col m12 l6">
<h5>Parameters:</h5>
<form>
<div class="row">
<div class="input-field col s6">
<input disabled id="noofc" type="text" class="validate" value=3>
<label for="noofc">No. of Clusters</label>
</div>
<div class="input-field col s6">
<input value=400 id="noofpoints" type="number" class="validate">
<label for="noofpoints">Data points</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input value=2 id="mValue" type="number" step="0.01" class="validate">
<label for="mValue">Fuzziness control parameter(m)</label>
</div>
<div class="input-field col s6">
<input value=0.5 id="threshold" type="number" step="0.001" class="validate">
<label for="threshold">Threshold</label>
</div>
</div>
<div class="row" style="margin-bottom:0;">
<div class="input-field col s6">
<select id="distFuncSel">
<option value="1" selected>Euclidean</option>
<option value="2">Phasor</option>
<option value="3">City Block</option>
<option value="4">Chromatic</option>
</select>
<label>Distance Function</label>
</div>
<div class="input-field col s6">
<label for="animspeed" style="margin-top: -20px;">Animation Speed</label>
<p class="range-field">
<input type="range" id="animspeed" min="0" max="100" value="90" />
</p>
</div>
</div>
<div class="row" style="margin-bottom:0;margin-top:0;">
<div class="file-field input-field col s4 m3 l4">
<div class="btn csbutt">
<span>Image</span>
<input id="fileUP" type="file" accept="image/*">
</div>
<div class="file-path-wrapper" style="display:none">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
<div class=" input-field col s8 m9 l8">
<img style="max-height:45px;max-width:45px;" id="resultImage" />
</div>
</div>
<div class="row" style="margin-bottom:0;margin-top:0;">
<div class="input-field col s12">
<a id="setparams" style="padding: 0 1rem" class="csbutt waves-effect waves-light btn">
<i class="material-icons right">check</i>Set Parameters</a>
</div>
</div>
<div class="row" style="margin-bottom:0;margin-top:0;">
<div class="input-field col s6">
<a id="iterate" style="padding: 0 1rem" class="csbutt waves-effect waves-light btn">
<i class="material-icons right">loop</i>Iterate</a>
</div>
<div class="col s6" style="margin-top: 1.5rem;">
<input type="checkbox" class="filled-in" value="true" id="checktimer" />
<label for="checktimer">Auto-Iterate</label>
</div>
</div>
</form>
<p style="font-size:12px;">To use an image, upload the image and update all parameters except
<b>Data points</b>, which is set automatically, and click on
<b>Set Parameters</b>. Next click on
<b>Iterate</b> to loop once at a time or set
<b>Auto iterate</b> ON to loop continuously.</p>
<p style="font-size:11px;">
<i style="font-size:11px" class="material-icons">copyright</i>
<span>Arindam Ray 2018</span>
</p>
</div>
</div>
</div>
<!-- Initial Setup -->
<script type="text/javascript">
// Setup data
var dataset = []; // Initialize empty array
var numDataPoints = 400; // Number of dummy data points
var maxRange = /*Math.random() * */ 1000; // Max range of new values
var xScale;
var yScale;
var svg;
var xAxis;
var yAxis;
var centroidRadius = 7;
var pointRadius = 2;
var m = 2; //fuziness control
var thresh = .5; //threshold
var distFunc = 1;
// Setup settings for graphic
var canvas_width = 420;
var canvas_height = 420;
var padding = 30; // for chart edges
var animspeed = 250;
// Setup C-means
var c = 3; //No. of clusters
var u = []; //Membership function
var V = []; //Cluster centres
var choosefile = 0;
function initCmeans() {
u = [];
V = [];
dataset = [];
if (choosefile == 0) {
//random dataset
for (var i = 0; i < numDataPoints; i++) {
var newNumber1 = Math.floor(Math.random() * maxRange); // New random integer
var newNumber2 = Math.floor(Math.random() * maxRange); // New random integer
dataset.push([newNumber1, newNumber2]); // Add new number to array
}
//Generate u
for (var i = 0; i < dataset.length; i++) {
var tempRandom = [];
var tempTotal = 0;
for (var noOfClusters = 0; noOfClusters < c; noOfClusters++) {
tempRandom[noOfClusters] = Math.random(); //Randomly assign u
tempTotal += tempRandom[noOfClusters]; //Keep a tab of the total sum
}
for (var noOfClusters = 0; noOfClusters < c; noOfClusters++) {
tempRandom[noOfClusters] /= tempTotal; //Normalize so that sum of all membership values = 1
}
u[i] = tempRandom; //push value to u
}
} else {
//getfromimage
for (var t = 0; t < picD.length; t++) {
u[t] = [picU[t][0], picU[t][1], picU[t][2]];
dataset[t] = [picD[t][0], picD[t][1]];
}
}
//Generate cluster centres
for (var i = 0; i < c; i++) {
V[i] = [Math.floor(Math.random() * maxRange), Math.floor(Math.random() * maxRange)]; //Randomly initialize cluster centers
}
}
function initGraph() {
document.getElementById("objStat").style.display = "none";
var graphdata = V.concat(dataset);
// Create scale functions
xScale = d3.scale.linear() // xScale is width of graphic
.domain([0, d3.max(graphdata, function (d) {
return d[0]; // input domain
})])
.range([padding, canvas_width - padding /** 2*/ ]); // output range
yScale = d3.scale.linear() // yScale is height of graphic
.domain([0, d3.max(graphdata, function (d) {
return d[1]; // input domain
})])
.range([canvas_height - padding, padding]); // remember y starts on top going down so we flip
// Define X axis
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(maxRange / 200 + 5);
// Define Y axis
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(maxRange / 200 + 5);
// Create SVG element
svg = d3.select("#plot") // This is where we put our vis
.append("svg")
.attr("width", canvas_width)
.attr("height", canvas_height)
// Create Circles
svg.selectAll("circle")
.data(graphdata)
.enter()
.append("circle") // Add circle svg
.attr("cx", function (d) {
return xScale(d[0]); // Circle's X
})
.attr("cy", function (d) { // Circle's Y
return yScale(d[1]);
})
.attr("r", function (d, i) {
return (i == 0 || i == 1 || i == 2) ? centroidRadius : pointRadius;
}) // radius
.attr("fill", function (d, i) {
return i == 0 ? "#f00" : (i == 1 ? "#0f0" : (i == 2 ? "#00f" : "rgb(" + Math.ceil(255 * u[i - 3][0]) + "," + Math
.ceil(255 * u[i - 3][1]) + "," + Math.ceil(255 * u[i - 3][2]) + ")"));
});
// Add to X axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (canvas_height - padding) + ")")
.call(xAxis);
// Add to Y axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
}
function dist(vec1, vec2, indexdata, indexcentroid, choice) {
if (choice == 1) {
//Euclidean distance
var N = vec1.length;
var d = 0;
for (var i = 0; i < N; i++)
d += Math.pow(vec1[i] - vec2[i], 2);
d = Math.sqrt(d);
return d;
} else if (choice == 2) {
//phasor difference
var r = Math.abs(Math.sqrt(Math.pow(vec1[0], 2) + Math.pow(vec1[1], 2)) - Math.sqrt(Math.pow(vec2[0], 2) + Math.pow(
vec2[1], 2)));
var theta = Math.abs(Math.atan(vec1[1] / vec1[0]) - Math.atan(vec2[1] / vec2[0]));
return r + theta;
} else if (choice == 3) {
//city block distance
return Math.abs(vec1[0] - vec2[0]) + Math.abs(vec1[1] - vec2[1]);
} else if (choice == 4) {
//chromatic
return 1 - u[indexdata][indexcentroid] + u[indexdata][(indexcentroid + 1) % 3] + u[indexdata][(indexcentroid + 2) %
3
];
/*var factor = 10;
if(indexcentroid==0)
if(Math.abs(1-u[indexdata][0]) > 0)
return factor*Math.abs(10*(1-u[indexdata][0] + u[indexdata][1] + u[indexdata][2]));
else return 0;
else if(indexcentroid==1)
if(Math.abs(1-u[indexdata][1]) > 0)
return factor*Math.abs((1-u[indexdata][1] + u[indexdata][0] + u[indexdata][2]));
else return 0;
else if(indexcentroid==2)
if(Math.abs(1-u[indexdata][2]) > 0)
return factor*Math.abs(1-u[indexdata][2] + u[indexdata][0] + u[indexdata][1]);
else return 0;
*/
}
}
function cmeansLoop() {
//update V - Cluster Centres
var num = 0.0;
var den = 0.0;
var oldV = [];
for (var t = 0; t < V.length; t++)
oldV[t] = [V[t][0], V[t][1]];
for (var i = 0; i < c; i++) {
num = 0.0;
den = 0.0;
for (var k = 0; k < dataset.length; k++) {
num += Math.pow(u[k][i], m) * dataset[k][0];
den += Math.pow(u[k][i], m);
}
//if(!isNan(num/den))
V[i][0] = num / den;
num = 0.0;
den = 0.0;
for (var k = 0; k < dataset.length; k++) {
num += Math.pow(u[k][i], m) * dataset[k][1];
den += Math.pow(u[k][i], m);
}
//if(!isNan(num/den))
V[i][1] = num / den;
}
//update u - membership values
for (var i = 0; i < c; i++) {
for (var k = 0; k < dataset.length; k++) {
num = 0.0;
den = 0.0;
num = Math.pow(dist(dataset[k], V[i], k, i, distFunc), 2 / (m - 1));
for (var j = 0; j < c; j++)
den += 1.0 / (Math.pow(dist(dataset[k], V[j], k, j, distFunc), 2 / (m - 1)));
if (!(isNaN(Math.pow(num * den, -1)))) u[k][i] = Math.pow(num * den, -1);
//if(isNaN(u[k][i])) u[k][i]=0;
}
}
// calculate obj. func. value
var J = 0;
for (var i = 0; i < c; i++)
for (var k = 0; k < dataset.length; k++) {
J += (Math.pow(u[k][i], m) * Math.pow(dist(dataset[k], V[i], k, i, distFunc), 2));
//console.log("d" + k +" c " + i + " " + dist(dataset[k],V[i],k,i,distFunc));
}
var tempT = 0;
for (var count = 0; count < c; count++)
tempT += dist(oldV[count], V[count], count, count, (distFunc == 4) ? 1 : distFunc);
if (tempT < thresh)
document.getElementById("Jval").innerHTML = "Objective function value: " + J +
"<br>Change in cluster location: <span style='color:red'>" + tempT +
"</span><br><span style='color:green'>Converged!</span>";
else
document.getElementById("Jval").innerHTML = "Objective function value: " + J +
"<br>Change in cluster location: <span style='color:red'>" + tempT + "</span>";
document.getElementById("objStat").style.display = "block";
/*
//addition
memNew = [];
//update membership loc
for(var i=0; i<numDataPoints; i++)
memNew.push([xMem(i), yMem(i)]);
//end of addition
//*/
}
function animate() {
// Update scale domain
//addition
//var graphdata = V.concat(memNew);
var graphdata = V.concat(dataset);
xScale.domain([0, d3.max(graphdata, function (d) {
return d[0];
})]);
yScale.domain([0, d3.max(graphdata, function (d) {
return d[1];
})]);
var temp = -1;
var temp2 = -1;
// Update circles
svg.selectAll("circle")
.data(graphdata) // Update with new data
.transition() // Transition from old to new
.duration(animspeed) // Length of animation
.each("start", function () { // Start animation
d3.select(this) // 'this' means the current element
//.attr("fill", "red") // Change color
.attr("r", function (d, i) {
++temp2;
return (temp2 == 0 || temp2 == 1 || temp2 == 2) ? centroidRadius + 1 : pointRadius
}); // Change size
})
.delay(function (d, i) {
return 0; /* i / graphdata.length * (animspeed/5); */ // Dynamic delay (i.e. each item delays a little longer)
})
//.ease("linear") // Transition easing - default 'variable' (i.e. has acceleration), also: 'circle', 'elastic', 'bounce', 'linear'
.attr("cx", function (d) {
return xScale(d[0]); // Circle's X
})
.attr("cy", function (d) {
return yScale(d[1]); // Circle's Y
})
.each("end", function () { // End animation
d3.select(this) // 'this' means the current element
.transition()
.duration(150)
.attr("fill", function (d, i) {
++temp;
if (isNaN(d3.select(this).attr("cx"))) return "rgba(0,0,0,0)";
//if(isNaN($(this).cx) || isNaN($(this).cy)) return "rgba(0,0,0,0)";
return (temp == 0) ? "#f00" : (temp == 1 ? "#0f0" : (temp == 2 ? "#00f" : "rgb(" + Math.ceil(255 * u[temp - 3]
[0]) + "," + Math.ceil(255 * u[temp - 3][1]) + "," + Math.ceil(255 * u[temp - 3][2]) + ")"));
}) // Change color
.attr("r", function (d, i) {
return (temp == 0 || temp == 1 || temp == 2) ? centroidRadius : pointRadius
}); // Change size
if (temp == numDataPoints + c - 1) {
document.getElementById("lblStatus").innerHTML = "Rendering complete";
setTimeout(function () {
document.getElementById("lblStatus").style.display = "none";
}, 100);
}
});
// Update X Axis
svg.select(".x.axis")
.transition()
.duration(animspeed)
.call(xAxis);
// Update Y Axis
svg.select(".y.axis")
.transition()
.duration(animspeed)
.call(yAxis);
}
</script>
<!--
<script>
//addition
function slope(oneortwo){
return (V[oneortwo-1][1]-V[oneortwo][1])/(V[oneortwo-1][0]-V[oneortwo][0]);
}
function constant(oneortwo, pointNo){
var point = u[pointNo];
return ((point[oneortwo]*V[oneortwo-1][1])+(point[oneortwo-1]*V[oneortwo][1])-((point[oneortwo]*Math.pow(V[oneortwo-1][0],2) - point[oneortwo-1]*Math.pow(V[oneortwo][0],2) + point[oneortwo-1]*V[oneortwo][0]*V[oneortwo-1][0] - point[oneortwo]*V[oneortwo][0]*V[oneortwo-1][0])/(V[oneortwo-1][1]-V[oneortwo][1])))/(point[oneortwo-1]+point[oneortwo]);
}
function xMem(pointNo){
return (constant(2,pointNo)-constant(1,pointNo))/(slope(1)-slope(2));
}
function yMem(pointNo){
return (slope(1)*constant(2,pointNo)-slope(2)*constant(1,pointNo))/(slope(1)-slope(2));
}
//end of addition
</script>
<!-- -->
<script src="js/fileup.js"></script>
<script type="text/javascript">
var counterContext;
$(function () {
$('select').material_select();
initCmeans();
initGraph();
$('#animspeed').on('change', function () {
animspeed = 100 + (100 - Number($("#animspeed").val())) * 15;
timerfuncs();
});
d3.select("#iterate")
.on("click", function () {
document.getElementById("lblStatus").style.display = "block";
document.getElementById("lblStatus").innerHTML = "Rendering plot...";
setTimeout(function () {
cmeansLoop();
animate();
}, 100);
});
d3.select("#setparams")
.on("click", function () {
c = Number($("#noofc").val());
m = Number($("#mValue").val());
thresh = Number($("#threshold").val());
numDataPoints = Number($("#noofpoints").val());
animspeed = 100 + (100 - Number($("#animspeed").val())) * 15;
distFunc = Number($("#distFuncSel").val());
$("#plot").empty();
initCmeans();
initGraph();
});
d3.select("#checktimer")
.on("click", function () {
timerfuncs();
});
});
function timerfuncs() {
clearInterval(counterContext);
if ($('#checktimer').is(':checked')) {
$('.csbutt').addClass('disabled');
document.getElementById("lblStatus").style.display = "none";
counterContext = setInterval(function () {
cmeansLoop();
animate();
}, animspeed + 150 + 10);
} else {
$('.csbutt').removeClass('disabled');
//clearInterval(counterContext);
}
}
</script>
</body>
</html>