-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclustering.html
1627 lines (1465 loc) · 73.9 KB
/
clustering.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smile - Clustering</title>
<meta name="description" content="Statistical Machine Intelligence and Learning Engine">
<!-- prettify js and CSS -->
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?lang=scala&lang=kotlin&lang=clj"></script>
<style>
.prettyprint ol.linenums > li { list-style-type: decimal; }
</style>
<!-- Bootstrap core CSS -->
<link href="css/cerulean.min.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- slider -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.css" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.transitions.css" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css" type="text/css" />
<!-- table of contents auto generator -->
<script src="js/toc.js" type="text/javascript"></script>
<!-- styles for pager and table of contents -->
<link rel="stylesheet" href="css/pager.css" type="text/css" />
<link rel="stylesheet" href="css/toc.css" type="text/css" />
<!-- Vega-Lite Embed -->
<script src="https://cdn.jsdelivr.net/npm/vega@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
<script src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-57GD08QCML"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-57GD08QCML');
</script>
<!-- Sidebar and testimonial-slider -->
<script type="text/javascript">
$(document).ready(function(){
// scroll/follow sidebar
// #sidebar is defined in the content snippet
// This script has to be executed after the snippet loaded.
// $.getScript("js/follow-sidebar.js");
$("#testimonial-slider").owlCarousel({
items: 1,
singleItem: true,
pagination: true,
navigation: false,
loop: true,
autoPlay: 10000,
stopOnHover: true,
transitionStyle: "backSlide",
touchDrag: true
});
});
</script>
</head>
<body>
<div class="container" style="max-width: 1200px;">
<header>
<div class="masthead">
<p class="lead">
<a href="index.html">
<img src="images/smile.jpg" style="height:100px; width:auto; vertical-align: bottom; margin-top: 20px; margin-right: 20px;">
<span class="tagline">Smile — Statistical Machine Intelligence and Learning Engine</span>
</a>
</p>
</div>
<nav class="navbar navbar-default" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Overview <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="quickstart.html">Quick Start</a></li>
<li><a href="overview.html">What's Machine Learning</a></li>
<li><a href="data.html">Data Processing</a></li>
<li><a href="visualization.html">Data Visualization</a></li>
<li><a href="vegalite.html">Declarative Visualization</a></li>
<li><a href="gallery.html">Gallery</a></li>
<li><a href="faq.html">FAQ</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Supervised Learning <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="classification.html">Classification</a></li>
<li><a href="regression.html">Regression</a></li>
<li><a href="deep-learning.html">Deep Learning</a></li>
<li><a href="feature.html">Feature Engineering</a></li>
<li><a href="validation.html">Model Validation</a></li>
<li><a href="missing-value-imputation.html">Missing Value Imputation</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Unsupervised Learning <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="clustering.html">Clustering</a></li>
<li><a href="vector-quantization.html">Vector Quantization</a></li>
<li><a href="association-rule.html">Association Rule Mining</a></li>
<li><a href="mds.html">Multi-Dimensional Scaling</a></li>
<li><a href="manifold.html">Manifold Learning</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">LLM & NLP <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="llm.html">Large Language Model (LLM)</a></li>
<li><a href="nlp.html">Natural Language Processing (NLP)</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Math <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="linear-algebra.html">Linear Algebra</a></li>
<li><a href="statistics.html">Statistics</a></li>
<li><a href="wavelet.html">Wavelet</a></li>
<li><a href="interpolation.html">Interpolation</a></li>
<li><a href="graph.html">Graph Data Structure</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="api/java/index.html" target="_blank">Java</a></li>
<li><a href="api/scala/index.html" target="_blank">Scala</a></li>
<li><a href="api/kotlin/index.html" target="_blank">Kotlin</a></li>
<li><a href="api/clojure/index.html" target="_blank">Clojure</a></li>
<li><a href="api/json/index.html" target="_blank">JSON</a></li>
</ul>
</li>
<li><a href="https://mybinder.org/v2/gh/haifengl/smile/notebook?urlpath=lab%2Ftree%2Fshell%2Fsrc%2Funiversal%2Fnotebooks%2Findex.ipynb" target="_blank">Try It Online</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
</header>
<div id="content" class="row">
<div class="col-md-3 col-md-push-9 hidden-xs hidden-sm">
<div id="sidebar">
<div class="sidebar-toc" style="margin-bottom: 20px;">
<p class="toc-header">Contents</p>
<div id="toc"></div>
</div>
<div id="search">
<script>
(function() {
var cx = '010264411143030149390:ajvee_ckdzs';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only></gcse:searchbox-only>
</div>
</div>
</div>
<div class="col-md-9 col-md-pull-3">
<h1 id="clustering-top" class="title">Clustering</h1>
<p>Clustering is the assignment of a set of observations
into subsets (called clusters) so that observations in the same cluster are
similar in some sense. Clustering is a method of unsupervised learning,
and a common technique for statistical data analysis used in many fields.</p>
<p>Hierarchical algorithms find successive clusters using previously
established clusters. These algorithms usually are either agglomerative
("bottom-up") or divisive ("top-down"). Agglomerative algorithms begin
with each element as a separate cluster and merge them into successively
larger clusters. Divisive algorithms begin with the whole set and proceed
to divide it into successively smaller clusters.</p>
<p>Partitional algorithms typically determine all clusters at once, but can
also be used as divisive algorithms in the hierarchical clustering.
Many partitional clustering algorithms require the specification of
the number of clusters to produce in the input data set, prior to
execution of the algorithm. Barring knowledge of the proper value
beforehand, the appropriate value must be determined, a problem on
its own for which a number of techniques have been developed.</p>
<p>Density-based clustering algorithms are devised to discover
arbitrary-shaped clusters. In this approach, a cluster is regarded as
a region in which the density of data objects exceeds a threshold.</p>
<p>Subspace clustering methods look for clusters that can only be seen in
a particular projection (subspace, manifold) of the data. These methods
thus can ignore irrelevant attributes. The general problem is also known
as Correlation clustering while the special case of axis-parallel subspaces
is also known as two-way clustering, co-clustering or biclustering in
bioinformatics: in these methods not only the objects are clustered but
also the features of the objects, i.e., if the data is represented in
a data matrix, the rows and columns are clustered simultaneously. They
usually do not however work with arbitrary feature combinations as in general
subspace methods.</p>
<h2 id="hierarchical">Agglomerative Hierarchical Clustering</h2>
<p>Agglomerative hierarchical clustering
seeks to build a hierarchy of clusters in a bottom up approach: each
observation starts in its own cluster, and pairs of clusters are merged as
one moves up the hierarchy. The results of hierarchical clustering are
usually presented in a dendrogram.</p>
<p>In general, the merges are determined in a greedy manner. In order to decide
which clusters should be combined, a measure of dissimilarity between sets
of observations is required. In most methods of hierarchical clustering,
this is achieved by use of an appropriate metric, and a linkage criteria
which specifies the dissimilarity of sets as a function of the pairwise
distances of observations in the sets. Hierarchical clustering has the
distinct advantage that any valid measure of distance can be used.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_1" data-toggle="tab">Java</a></li>
<li><a href="#scala_1" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_1" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_1">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def hclust(data: Array[Array[Double]], method: String): HierarchicalClustering
def hclust[T](data: Array[T], distance: Distance[T], method: String): HierarchicalClustering
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_1">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class HierarchicalClustering {
public static HierarchicalClustering fit(Linkage linkage);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_1">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun hclust(data: Array<DoubleArray>, method: String): HierarchicalClustering
fun <T> hclust(data: Array<T>, distance: Distance<T>, method: String): HierarchicalClustering
</code></pre>
</div>
</div>
</div>
<p>The parameter <code>method</code> specifies the agglomeration method to
merge clusters. This should be one of "single", "complete",
"upgma"/"average", "upgmc"/"centroid", "wpgma", "wpgmc"/"median",
and "ward".</p>
<p>The single linkage defines the distance between groups as the distance
between the closest pair of objects, one from each group.
A drawback of this method is the so-called chaining phenomenon: clusters
may be forced together due to single elements being close to each other,
even though many of the elements in each cluster may be very distant to
each other.</p>
<p>Single linkage clustering is essentially the same as Kruskal's algorithm
for minimum spanning trees. However, in single linkage clustering, the
order in which clusters are formed is important, while for minimum spanning
trees what matters is the set of pairs of points that form distances chosen
by the algorithm.</p>
<p>The complete linkage is the opposite of single linkage. Distance between
groups is now defined as the distance between the most distant pair of
objects, one from each group.</p>
<p>UPGMA (Unweighted Pair Group Method with Arithmetic mean, also known as average linkage)
defines the distance between two clusters as the mean distance between all possible
pairs of nodes in the two clusters.</p>
<p>In bioinformatics, UPGMA is used for the creation of phenetic trees
(phenograms). UPGMA assumes a constant rate of evolution (molecular
clock hypothesis), and is not a well-regarded method for inferring
relationships unless this assumption has been tested and justified
for the data set being used.</p>
<p>UPGMC (Unweighted Pair Group Method using Centroids, also known as centroid linkage)
defines the distance between two clusters as the Euclidean distance between their
centroids, as calculated by arithmetic mean. Only valid for Euclidean
distance based proximity matrix.</p>
<p>WPGMA (Weighted Pair Group Method with Arithmetic mean) down-weights the
largest group by giving equal weights to the two branches of the dendrogram
that are about to fuse.</p>
<p>Note that the terms weighted and unweighted refer to the final result,
not the math by which it is achieved. Thus, the simple averaging in WPGMA
produces a weighted result, and the proportional averaging in UPGMA produces
an unweighted result.</p>
<p>WPGMC (Weighted Pair Group Method using Centroids, also known as median linkage)
defines the distance between two clusters as the Euclidean distance between their
weighted centroids. Only valid for Euclidean distance based proximity matrix.</p>
<p>Ward's linkage. Ward's linkage follows the analysis of variance approach
The dissimilarity between two clusters is computed as the
increase in the "error sum of squares" (ESS) after fusing two clusters
into a single cluster. Ward's Method seeks to choose the successive
clustering steps to minimize the increase in ESS at each step.
Note that it is only valid for Euclidean distance based proximity matrix.</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/six.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">Mixture of Six Gaussians</div>
</div>
<p>To visualize the clustering results, we apply hierarchical clustering
to 2d data in the following. The data is generated from six Gaussian
distributions, each 300 samples.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_2" data-toggle="tab">Java</a></li>
<li><a href="#scala_2" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_2" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_2">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val x = read.csv("data/clustering/rem.txt", header=false, delimiter=" ").toArray()
val clusters = hclust(x, "complete")
show(dendrogram(clusters))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_2">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
import smile.clustering.*;
import smile.clustering.linkage.*;
var x = Read.csv("data/clustering/rem.txt", CSVFormat.DEFAULT.withDelimiter(' ')).toArray();
var clusters = HierarchicalClustering.fit(CompleteLinkage.of(x));
var plot = new Dendrogram(clusters.tree(), clusters.height());
plot.canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_2">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
import smile.*;
import smile.clustering.*;
import smile.plot.swing.*;
import java.awt.Color;
val x = read.csv("data/clustering/rem.txt", header=false, delimiter=' ').toArray();
val clusters = hclust(x, "complete");
val plot = Dendrogram(clusters.tree(), clusters.height());
plot.canvas().window();
</code></pre>
</div>
</div>
</div>
<p>The clustering results can be visualized by a hendroagram, which
is a tree diagram to illustrate the arrangement
of the clusters produced by hierarchical clustering.</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/hclust-dendrogram.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">Dendrogram</div>
</div>
<p>If a hard partition is need, we can cut a hierarchical clustering tree
into several groups by specifying the desired number or the cut height.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_3" data-toggle="tab">Java</a></li>
<li><a href="#scala_3" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_3" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_3">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val y = clusters.partition(6)
show(plot(x, y, '.'))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_3">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
var y = clusters.partition(6);
ScatterPlot.of(x, y, '.').canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_3">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
val y = clusters.partition(6)
ScatterPlot.of(x, y, '.').canvas().window();
</code></pre>
</div>
</div>
</div>
<p>The partitioning of six clusters is shown as</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/hclust-six.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">Hierarchical Clustering</div>
</div>
<h2 id="k-means">K-Means</h2>
<p>K-Means clustering partitions <code>n</code> observations into <code>k</code> clusters in which
each observation belongs to the cluster with the nearest mean.
Although finding an exact solution to the K-Means problem for arbitrary
input is NP-hard, the standard approach to finding an approximate solution
(often called Lloyd's algorithm or the K-Means algorithm) is used widely
and frequently finds reasonable solutions quickly.</p>
<p>K-Means is a hard clustering method, i.e. each sample is assigned to
a specific cluster. In contrast, soft clustering, e.g. the
Expectation-Maximization algorithm for Gaussian mixtures, assign samples
to different clusters with different probabilities.</p>
<p>The K-Means algorithm has at least two major theoretic shortcomings:</p>
<ul>
<li>First, it has been shown that the worst case running time of the
algorithm is super-polynomial in the input size.</li>
<li>Second, the approximation found can be arbitrarily bad with respect
to the objective function compared to the optimal learn.</li>
</ul>
<p>In Smile, we use K-Means++ which addresses the second of these
obstacles by specifying a procedure to initialize the cluster centers before
proceeding with the standard K-Means optimization iterations. With the
K-Means++ initialization, the algorithm is guaranteed to find a solution
that is O(log k) competitive to the optimal K-Means solution.</p>
<p>We also use K-D trees to speed up each K-Means step as described in the filter
algorithm by Kanungo, et al.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_4" data-toggle="tab">Java</a></li>
<li><a href="#scala_4" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_4" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_4">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def kmeans(data: Array[Array[Double]], k: Int, maxIter: Int = 100, tol: Double = 1E-4, runs: Int = 10): KMeans
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_4">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class KMeans {
public static KMeans fit(double[][] data, Options options);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_4">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun kmeans(data: Array<DoubleArray>, k: Int, maxIter: Int = 100, tol: Double = 1E-4, runs: Int = 10): KMeans
</code></pre>
</div>
</div>
</div>
<p>The parameter <code>maxIter</code> specifies the maximum number of iterations.
If the output of K-Means is used to initialize other algorithms, a small number (says 20)
is usually sufficient. In practice, we often run the K-Means multiple times
and choose the best one. To do that, set the parameter <code>runs > 1</code>
(e.g. 10 ~ 20).</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_5" data-toggle="tab">Java</a></li>
<li><a href="#scala_5" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_5" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_5">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val clusters = kmeans(x, 6, runs = 20)
show(plot(x, clusters.y, '.'))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_5">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
var clusters = Clustering.run(20, () -> KMeans.fit(x, 6));
ScatterPlot.of(x, clusters.y, '.').canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_5">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
val clusters = kmeans(x, 6, runs = 20)
ScatterPlot.of(x, clusters.y, '.').canvas().window()
</code></pre>
</div>
</div>
</div>
<p>K-Means works very well on Gaussian mixtures.</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/kmeans-six.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">K-Means on Gaussian Mixture</div>
</div>
<p>If the clusters are elongated, however, the results may be far from optimal.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_6" data-toggle="tab">Java</a></li>
<li><a href="#scala_6" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_6" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_6">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val x = read.csv("data/clustering/elongate.txt", header=false, delimiter="\t").toArray()
val clusters = kmeans(x, 2, runs = 20)
show(plot(x, clusters.y, '.'))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_6">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
var x = Read.csv("data/clustering/elongate.txt", CSVFormat.DEFAULT.withDelimiter('\t')).toArray();
var clusters = Clustering.run(20, () -> KMeans.fit(x, 2));
ScatterPlot.of(x, clusters.y, '.').canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_6">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
val x = read.csv("data/clustering/elongate.txt", header=false, delimiter='\t').toArray()
val clusters = kmeans(x, 2, runs = 20)
ScatterPlot.of(x, clusters.y, '.').canvas().window()
</code></pre>
</div>
</div>
</div>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/kmeans-elongate.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">K-Means on 2 Elongate Clusters</div>
</div>
<p>In K-Means, the number of clusters <code>K</code> has to be supplied by the user.
However, the appropriate number of clusters is often unknown in practice.
Several approaches (e.g. X-Means, G-Means, deterministic annealing, etc.)
have been proposed to handle this challenge.</p>
<h2 id="x-means">X-Means</h2>
<p>X-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters based on BIC scores.
Starting with only one cluster, the X-Means algorithm goes into action
after each run of K-Means, making local decisions about which subset of the
current centroids should split themselves in order to better fit the data.
The splitting decision is done by computing the Bayesian Information
Criterion (BIC).</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_7" data-toggle="tab">Java</a></li>
<li><a href="#scala_7" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_7" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_7">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def xmeans(data: Array[Array[Double]], k: Int = 100): XMeans
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_7">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class XMeans {
public static XMeans fit(double[][] data, Options options);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_7">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun xmeans(data: Array<DoubleArray>, k: Int = 100): XMeans
</code></pre>
</div>
</div>
</div>
<p>where the parameter <code>k</code> is the maximum number of clusters</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_8" data-toggle="tab">Java</a></li>
<li><a href="#scala_8" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_8" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_8">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val x = read.csv("data/clustering/rem.txt", header=false, delimiter=" ").toArray()
val clusters = xmeans(x, 50)
show(plot(x, clusters.y, '.'))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_8">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
var x = Read.csv("data/clustering/rem.txt", CSVFormat.DEFAULT.withDelimiter(' ')).toArray();
var clusters = XMeans.fit(x, 50);
ScatterPlot.of(x, clusters.y, '.').canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_8">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
val x = read.csv("data/clustering/rem.txt", header=false, delimiter=' ').toArray()
val clusters = xmeans(x, 50)
ScatterPlot.of(x, clusters.y, '.').canvas().window()
</code></pre>
</div>
</div>
</div>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/xmeans-six.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">X-Means</div>
</div>
<h2 id="g-means">G-Means</h2>
<p>G-Means clustering algorithm is another extended K-Means which tries to
automatically determine the number of clusters by normality test.
The G-Means algorithm is based on a statistical test for the hypothesis
that a subset of data follows a Gaussian distribution. G-Means runs
K-Means with increasing k in a hierarchical fashion until the test accepts
the hypothesis that the data assigned to each K-Means center are Gaussian.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_9" data-toggle="tab">Java</a></li>
<li><a href="#scala_9" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_9" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_9">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def gmeans(data: Array[Array[Double]], k: Int = 100): GMeans
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_9">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class GMeans {
public static GMeans fit(double[][] data, Options options);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_9">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun gmeans(data: Array<DoubleArray>, k: Int = 100): GMeans
</code></pre>
</div>
</div>
</div>
<p>where the parameter <code>k</code> is the maximum number of clusters</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/gmeans-six.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">G-Means</div>
</div>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_10" data-toggle="tab">Java</a></li>
<li><a href="#scala_10" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_10" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_10">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
val clusters = gmeans(x, 50)
show(plot(x, clusters.y, '.'))
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_10">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
var clusters = GMeans.fit(x, 50);
ScatterPlot.of(x, clusters.y, '.').canvas().window();
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_10">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
val clusters = gmeans(x, 50)
ScatterPlot.of(x, clusters.y, '.').canvas().window()
</code></pre>
</div>
</div>
</div>
<p>Neither X-Means nor G-Means works well on the elongate data. Both report only
one cluster.</p>
<h2 id="deterministic-annealing">Deterministic Annealing Clustering</h2>
<p>The observation of annealing processes in physical chemistry motivated
the use of similar concepts to avoid local minima of the optimization cost.
Certain chemical systems can be driven to their low-energy states
by annealing, which is a gradual reduction of temperature,
spending a long time at the vicinity of the phase transition points.
In the corresponding probabilistic framework, a Gibbs distribution
is defined over the set of all possible configurations which assigns
higher probability to configurations of lower energy. This distribution
is parameterized by the temperature, and as the temperature is lowered
it becomes more discriminating (concentrating most of the probability
in a smaller subset of low-energy configurations). At the limit of
low temperature it assigns nonzero probability only to global minimum
configurations.</p>
<p>A known technique for nonconvex optimization that
capitalizes on this physical analogy is simulated annealing based on
the Metropolis algorithm. A sequence of random
moves is generated and the random decision to accept a move depends
on the cost of the resulting configuration relative to that of the
current state. However, one must be very careful with the annealing
schedule, i.e., the rate at which the temperature is lowered.
In theory, the global minimum can be achieved if the schedule obeys
<code>T ∝ 1 / log n</code>, where <code>n</code> is the number
of the current iteration. Such schedules are not realistic in many applications.
It was shown that perturbations of infinite variance (e.g., the Cauchy distribution)
provide better ability to escape from minima and allow, in principle,
the use of faster schedules.</p>
<p>Deterministic annealing tries to enjoy the best of both worlds.
On the one hand it is deterministic, meaning that we do not want
to be wandering randomly on the energy surface while making
incremental progress on the average, as is the case for simulated annealing.
On the other hand, it is still an annealing method and aims at the global
minimum, instead of getting greedily attracted to a nearby local minimum.
One can view deterministic annealing as replacing stochastic simulations by the use of expectation.
An effective energy function, which is parameterized by a (pseudo) temperature,
is derived through expectation and is deterministically optimized at successively
reduced temperatures.</p>
<p>Deterministic annealing clustering is based on principles of information theory
and probability theory, and it consists of minimizing the clustering cost
at prescribed levels of randomness.
The method provides soft clustering solutions at different scales,
where the scale is directly related to the temperature parameter.
For each temperature value, the algorithm iterates between the calculation
of all posteriori probabilities and the update of the centroids vectors,
until convergence is reached.
There are "phase transitions" in the design process, where phases
correspond to the number of effective clusters in the solution,
which grows via splits as the temperature is lowered.
The annealing starts with a high temperature.
Here, all centroids vectors converge to the center of the pattern
distribution (independent of their initial positions). Below a critical
temperature the vectors start to split. Further decreasing the temperature
leads to more splittings until all centroids vectors are separate. The
annealing can therefore avoid (if it is sufficiently slow) the convergence
to local minima. If a limitation on the number of clusters is imposed,
then at zero temperature a hard clustering solution is obtained.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_11" data-toggle="tab">Java</a></li>
<li><a href="#scala_11" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_11" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_11">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def dac(data: Array[Array[Double]], k: Int, alpha: Double): DeterministicAnnealing
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_11">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class DeterministicAnnealing {
public static DeterministicAnnealing fit(double[][] data, Options options);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_11">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun dac(data: Array<DoubleArray>, k: Int, alpha: Double): DeterministicAnnealing
</code></pre>
</div>
</div>
</div>
<p>where <code>k</code> is the maximum number of clusters, and <code>alpha</code>
is the annealing control parameter in (0, 1). The temperature <code>T</code>
is decreasing as <code>T<sub>i+1</sub> = alpha * T<sub>i</sub></code>.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_12" data-toggle="tab">Java</a></li>
<li><a href="#scala_12" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_12" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_12">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
smile> dac(x, 12, 0.9)
res58: DeterministicAnnealing = Cluster distortion: 17904.72351
Cluster size of 300 data points:
Cluster 1 157 (52.3%)
Cluster 2 42 (14.0%)
Cluster 3 3 ( 1.0%)
Cluster 4 2 ( 0.7%)
Cluster 5 3 ( 1.0%)
Cluster 6 0 ( 0.0%)
Cluster 7 0 ( 0.0%)
Cluster 8 0 ( 0.0%)
Cluster 9 84 (28.0%)
Cluster 10 2 ( 0.7%)
Cluster 11 2 ( 0.7%)
Cluster 12 5 ( 1.7%)
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_12">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
smile> DeterministicAnnealing.fit(x, 12, 0.9, 100, 1E-4, 1E-2)
$126 ==> Cluster distortion: 2862.52100
Cluster size of 1800 data points:
Cluster 1 297 (16.5%)
Cluster 2 105 ( 5.8%)
Cluster 3 159 ( 8.8%)
Cluster 4 137 ( 7.6%)
Cluster 5 139 ( 7.7%)
Cluster 6 21 ( 1.2%)
Cluster 7 292 (16.2%)
Cluster 8 149 ( 8.3%)
Cluster 9 140 ( 7.8%)
Cluster 10 59 ( 3.3%)
Cluster 11 143 ( 7.9%)
Cluster 12 159 ( 8.8%)
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_12">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
>>> dac(x, 12, 0.9)
res22: smile.clustering.DeterministicAnnealing = Cluster distortion: 2862.52100
Cluster size of 1800 data points:
Cluster 1 297 (16.5%)
Cluster 2 105 ( 5.8%)
Cluster 3 159 ( 8.8%)
Cluster 4 137 ( 7.6%)
Cluster 5 139 ( 7.7%)
Cluster 6 21 ( 1.2%)
Cluster 7 292 (16.2%)
Cluster 8 149 ( 8.3%)
Cluster 9 140 ( 7.8%)
Cluster 10 59 ( 3.3%)
Cluster 11 143 ( 7.9%)
Cluster 12 159 ( 8.8%)
</code></pre>
</div>
</div>
</div>
<p>Note that we set <code>k = 12</code> in the example although we know there are 6 clusters.
It is because we maintain two codevectors/centroids for each cluster for sake of split.
The algorithm correctly figures out that half of them are ghost clusters without samples.
In the output summary, the first column is the cluster id, the second column is the size
of clusters, and the third column is the percentage of samples.</p>
<div style="width: 100%; display: inline-block; text-align: center;">
<img src="images/deterministic-annealing.png" class="enlarge" style="width: 480px;" />
<div class="caption" style="min-width: 480px;">Deterministic Annealing</div>
</div>
<p>Although deterministic annealing is physical and mathematical sound, the results may
not reveal the correct structure of data as shown in the above.</p>
<h2 id="sib">Sequential Information Bottleneck</h2>
<p>The Sequential Information Bottleneck (SIB) algorithm clusters co-occurrence
data such as text documents vs words. SIB is guaranteed to converge to a local
maximum of the information. Moreover, the time and space complexity are
significantly improved in contrast to the agglomerative IB algorithm.</p>
<p>In analogy to K-Means, SIB's update formulas are essentially same as the
EM algorithm for estimating finite Gaussian mixture model by replacing
regular Euclidean distance with Kullback-Leibler divergence, which is
clearly a better dissimilarity measure for co-occurrence data. However,
the common batch updating rule (assigning all instances to nearest centroids
and then updating centroids) of K-Means won't work in SIB, which has
to work in a sequential way (reassigning (if better) each instance then
immediately update related centroids). It might be because K-L divergence
is very sensitive and the centroids may be significantly changed in each
iteration in batch updating rule.</p>
<p>Note that this implementation has a little difference from the original
paper, in which a weighted Jensen-Shannon divergence is employed as a
criterion to assign a randomly-picked sample to a different cluster.
However, this doesn't work well in some cases as we experienced probably
because the weighted JS divergence gives too much weight to clusters which
is much larger than a single sample. In this implementation, we instead
use the regular/unweighted Jensen-Shannon divergence.</p>
<ul class="nav nav-tabs">
<li class="active"><a href="#java_13" data-toggle="tab">Java</a></li>
<li><a href="#scala_13" data-toggle="tab">Scala</a></li>
<li><a href="#kotlin_13" data-toggle="tab">Kotlin</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="scala_13">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-scala"><code>
def sib(data: Array[SparseArray], k: Int, maxIter: Int = 100, runs: Int = 1): SIB
</code></pre>
</div>
</div>
<div class="tab-pane active" id="java_13">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-java"><code>
public class SIB {
public static SIB fit(SparseArray[] data, Options options);
}
</code></pre>
</div>
</div>
<div class="tab-pane" id="kotlin_13">
<div class="code" style="text-align: left;">
<pre class="prettyprint lang-kotlin"><code>
fun sib(data: Array<SparseArray>, k: Int, maxIter: Int = 100, runs: Int = 1): SIB