-
Notifications
You must be signed in to change notification settings - Fork 23
/
ckMeanCluster.cls
1455 lines (1317 loc) · 51.3 KB
/
ckMeanCluster.cls
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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "ckMeanCluster"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
'========================================
'Requires: modMath, ckdTree
'========================================
'Perform k-Means clustering when distance type is "EUCLIDEAN". k-Medians will be
'used if distance type is set to "MANHATTAN". When "CORREL" is used, mean is used
'to calculate cluster centers and correlation is used to evalulate distance between
'datapoints to clusters.
'When number of k is large, one may set usekdTree to TRUE to speed up NN search.
'========================================
'=== Major input and output data format
'Input: x(1:N,1:D), N observations of D-dimensional data
' k, number of desired clusters
' iter_max, maximum number of iterations to try
' strType, distance metric "EUCLIDEAN", "MANHATTAN", "CORREL"
'Output: x_cluster(1:N), cluster index of each data point, integer vector
' cluster_mean(1:k, 1:D), storing centers of each cluster, real array
' cluster_size(1:k),number of points assigned to each cluster, integer vector
'========================================
'=== Training methods
'.kMean_Brute(x,k,iter_max,strType)
'.kMean_Clustering(x,k,iter_max,strType,usekdtree)
'.kMean_Filtering(x,k,iter_max,strType,usekdtree)
'.kMean_Elkan(x,k,iter_max,strType)
'.kMean_Hamerly(x,k,iter_max,strType)
'.kMean_Annular(x,k,iter_max,strType)
'========================================
Private pk As Long, pn_dimension As Long 'number of clusters and dimensions
Private px_cluster() As Long 'cluster index of each data point
Private pcluster_mean() As Double 'center of each cluster
Private pcluster_size() As Long 'number of points assigned to each cluster
Private pDistType As String 'Metric used in current model
Private Const pINFINITY As Double = 2.5E+30
Private px2() As Double, pc2() As Double, pxavg() As Double, pxsd() As Double, pcavg() As Double, pcsd() As Double
'========================================
'Access Properties
'========================================
Public Property Get k_cluster() As Long
k_cluster = pk
End Property
Public Property Get n_dimension() As Long
n_dimension = pn_dimension
End Property
Public Property Get cluster_mean() As Double()
cluster_mean = pcluster_mean
End Property
Public Property Get cluster_size() As Long()
cluster_size = pcluster_size
End Property
Public Property Get x_cluster() As Long()
x_cluster = px_cluster
End Property
Public Property Get DistType() As String
DistType = pDistType
End Property
Sub Reset()
pk = 0
Erase pcluster_mean, pcluster_size, px_cluster
Erase px2, pc2, pxavg, pxsd, pcavg, pcsd
End Sub
'Output trained model to Excel
Sub Print_Model(vRng As Range)
With vRng
.Value = pk 'Number of centroids
.Offset(1, 0).Value = pn_dimension 'dimension of data
.Offset(2, 0).Value = pDistType 'Metric used
.Offset(3, 0).Resize(pk, pn_dimension).Value = pcluster_mean 'Centroid vectors
End With
End Sub
'Read trained model from Excel
Sub Read_Model(vRng As Range)
Dim j As Long, k As Long
Dim vArr As Variant
With vRng
pk = .Value 'Number of centroids
pn_dimension = .Offset(1, 0).Value 'dimension of data
pDistType = .Offset(2, 0).Value 'Metric used
vArr = .Offset(3, 0).Resize(pk, pn_dimension).Value
ReDim pcluster_mean(1 To pk, 1 To pn_dimension)
For j = 1 To pn_dimension
For k = 1 To pk
pcluster_mean(k, j) = vArr(k, j)
Next k
Next j
Erase vArr
End With
End Sub
'Assign un-trained data to centroid, use upper bound of Elkan's algorithm to speed up search
'Input: x(1:N,1:D), N observations of D-dimensional data
'Output: x_idx(1:N), cluster index of each data point, integer vector
Sub Assign_Data(x_idx() As Long, x)
Dim i As Long, j As Long, k As Long, m As Long, n As Long
Dim c_dist() As Double, s_dist() As Double, xi() As Double
Dim tmp_x As Double, tmp_y As Double
n = UBound(x, 1)
ReDim x_idx(1 To n)
ReDim xi(1 To pn_dimension)
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(pcluster_mean, pc2, pcavg, pcsd)
End If
Call Compute_Centroid_Centroid_Distance(c_dist, s_dist)
For i = 1 To n
For j = 1 To pn_dimension
xi(j) = x(i, j)
Next j
m = 1
tmp_y = Dist2Center_2(xi, 1)
For k = 2 To pk
If tmp_y > (c_dist(k, m) / 2) Then
tmp_x = Dist2Center_2(xi, k)
If tmp_x < tmp_y Then
tmp_y = tmp_x
m = k
End If
End If
Next k
x_idx(i) = m
Next i
Erase c_dist, s_dist, xi
End Sub
'Initialization with k-means++ scheme
Private Sub Init_kplus(x() As Double)
Dim i As Long, j As Long, k As Long, m As Long, n As Long
Dim tmp_x As Double
Dim x_d2() As Double, xi() As Double
Dim x_seeds() As Long
n = UBound(x, 1)
Randomize
ReDim x_seeds(1 To pk) 'mark datapoints chosen as seeds
ReDim x_d2(1 To n) 'distances from datapoints to closest seed
ReDim xi(1 To n) 'cumulative probability of datapoints to be chosen
For i = 1 To n
x_d2(i) = pINFINITY
Next i
x_seeds(1) = Int(Rnd() * n) + 1 'First seed randomly picked
For k = 2 To pk 'Select next seed base on distances from existing seeds
tmp_x = 0
For i = 1 To n
Call Dist2Seeds(i, x_seeds, x, k - 1, x_d2(i))
tmp_x = tmp_x + x_d2(i)
Next i
xi(1) = x_d2(1) / tmp_x
For i = 2 To n
xi(i) = xi(i - 1) + x_d2(i) / tmp_x
Next i
x_seeds(k) = Random_Integer_Prob(xi)
Next k
'*****Fix initialization for testing purpose*****
' For k = 1 To pk
' x_seeds(k) = (k - 1) * Int(n / pk) + 1
' Next k
'*******************************************************
ReDim pcluster_mean(1 To pk, 1 To pn_dimension)
For m = 1 To pn_dimension
For k = 1 To pk
pcluster_mean(k, m) = x(x_seeds(k), m)
Next k
Next m
Erase xi, x_d2, x_seeds
End Sub
'===========================================================
'Main Algorithm, cache distances in a N x k array, only
'calculate its k-th column when the k-th centroid is moved.
'===========================================================
'Input: x(1:N,1:D), N observations of D-dimensional data
' k, number of desired clusters
'Output: x_cluster(1:N), cluster index of each data point, integer vector
' cluster_mean(1:k, 1:D), storing centers of each cluster, real array
' cluster_size(1:k),number of points assigned to each cluster, integer vector
Sub kMean_Clustering(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN", _
Optional usekdtree As Boolean = False)
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long
Dim tmp_x As Double, tmp_y As Double, tmp_min As Double
Dim n_raw As Long, n_chg As Long, cluster_reset As Long
Dim xi() As Double, x_dist() As Double
Dim isChg() As Long, isChg_Prev() As Long
Dim k1 As ckdTree
Dim tree_type As String
pk = k
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
pDistType = VBA.UCase$(strType)
If pDistType = "EUCLIDEAN" Then
tree_type = "EUCLIDEAN"
ElseIf pDistType = "MANHATTAN" Then
tree_type = "MANHATTAN"
ElseIf pDistType = "CORREL" Then
If usekdtree = True Then
Debug.Print "k-d Tree speedup not compatible with CORREL metric."
End
End If
Else
Debug.Print "ckMeanCluster:Invalid distance type."
End
End If
'=== Initialization with k-means++ scheme
Call Init_kplus(x)
'=== Pre-calculate data to centroid distance
ReDim isChg_Prev(0 To pk)
ReDim x_dist(1 To n_raw, 1 To pk)
If usekdtree = False Then
ReDim xi(1 To pn_dimension)
For i = 1 To n_raw
For m = 1 To pn_dimension
xi(m) = x(i, m)
Next m
For j = 1 To pk
x_dist(i, j) = Dist2Center(xi, j)
Next j
Next i
Else
'if k-d tree is used, negative value flags
'distance that needs to be recalculated
For j = 1 To pk
For i = 1 To n_raw
x_dist(i, j) = -1
Next i
Next j
End If
'=== For euclidean pre-calculate norm of centroid
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(pcluster_mean, pc2, pcavg, pcsd)
End If
'=== Iterate until convergence
ReDim px_cluster(1 To n_raw)
ReDim xi(1 To pn_dimension)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Clustering: " & iterate & "/" & iter_max
End If
'Update auxiliary varaibles for moved centroids
If pDistType = "EUCLIDEAN" Then
For i = 1 To pk
If isChg_Prev(i) > 0 Then
pc2(i) = 0
For j = 1 To pn_dimension
pc2(i) = pc2(i) + pcluster_mean(i, j) ^ 2
Next j
End If
Next i
ElseIf pDistType = "CORREL" Then
For i = 1 To pk
If isChg_Prev(i) > 0 Then
pcavg(i) = 0: pcsd(i) = 0
For j = 1 To pn_dimension
pcavg(i) = pcavg(i) + pcluster_mean(i, j)
pcsd(i) = pcsd(i) + pcluster_mean(i, j) ^ 2
Next j
pcavg(i) = pcavg(i) / pn_dimension
pcsd(i) = Sqr(pcsd(i) / pn_dimension - pcavg ^ 2)
End If
Next i
End If
If usekdtree = False Then
'Update distance
Call Batch_Dist_Update(x_dist, x, isChg_Prev)
Else
'Prepare k-d Tree to speed up search
Set k1 = New ckdTree
Call k1.Build_Tree(pcluster_mean)
End If
'Assign each point to the closest center
n_chg = 0
ReDim isChg(0 To pk)
ReDim pcluster_size(1 To pk)
For i = 1 To n_raw
If usekdtree = True Then
For m = 1 To pn_dimension
xi(m) = x(i, m)
Next m
n = k1.NN_Search_Speed(xi, pcluster_mean, i, x_dist, tree_type)
Else
n = 1: tmp_min = x_dist(i, 1)
For j = 2 To pk
tmp_x = x_dist(i, j)
If tmp_x < tmp_min Then
tmp_min = tmp_x
n = j
End If
Next j
End If
'Record if any centroid needs to be moved
If n <> px_cluster(i) Then
n_chg = n_chg + 1
isChg(n) = isChg(n) + 1
isChg(px_cluster(i)) = isChg(px_cluster(i)) + 1
End If
px_cluster(i) = n
pcluster_size(n) = pcluster_size(n) + 1
Next i
'If there are centroids without any members, set them to be
'datapoints that are furthest from existing clusters.
cluster_reset = Fill_Empty_Cluster(x, n_chg, isChg)
'Clear k-d Tree if used
If usekdtree = True Then
Call k1.Reset
Set k1 = Nothing
'if any centroid is changed then reset their distances
For j = 1 To pk
If isChg(j) > 0 Then
For i = 1 To n_raw
x_dist(i, j) = -1
Next i
End If
Next j
End If
isChg_Prev = isChg 'Record centroids that were moved
If cluster_reset = 0 Then
If n_chg = 0 Then Exit For
End If
'Re-estimate centroid vector base on new cluster membership
Call ReCalculate_Centroids(x)
Next iterate
'=========================================
If iterate >= iter_max Then
Debug.Print "ckMeanCluster: Fail to converge in " & iter_max & " steps."
End If
Erase xi, x_dist, isChg, isChg_Prev
If pDistType = "EUCLIDEAN" Then
Erase px2, pc2
ElseIf pDistType = "CORREL" Then
Erase pxavg, pxsd, pcavg, pcsd
End If
Application.StatusBar = False
End Sub
'=========================================================================
'Brute Force Approach, no caching of distances, no nothing
'=========================================================================
Sub kMean_Brute(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN")
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long
Dim tmp_x As Double, tmp_y As Double, tmp_min As Double
Dim n_raw As Long, n_chg As Long, cluster_reset As Long
Dim xi() As Double
pk = k
pDistType = VBA.UCase$(strType)
If pDistType <> "EUCLIDEAN" And pDistType <> "MANHATTAN" And pDistType <> "CORREL" Then
Debug.Print "ckMeanCluster: Brute: Invalid distance type."
End
End If
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
'=== Initialization with k-means++ scheme
Call Init_kplus(x)
'=== Iterate until convergence
ReDim px_cluster(1 To n_raw)
ReDim xi(1 To pn_dimension)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Clustering: " & iterate & "/" & iter_max
End If
'Assign each point to the closest center
n_chg = 0
ReDim pcluster_size(1 To pk)
For i = 1 To n_raw
For m = 1 To pn_dimension
xi(m) = x(i, m)
Next m
tmp_min = pINFINITY
For j = 1 To pk
tmp_x = Dist2Center(xi, j)
If tmp_x < tmp_min Then
tmp_min = tmp_x
n = j
End If
Next j
If px_cluster(i) <> n Then n_chg = n_chg + 1
px_cluster(i) = n
pcluster_size(n) = pcluster_size(n) + 1
Next i
'If there are centroids without any members, set them to be
'datapoints that are furthest from existing clusters.
cluster_reset = Fill_Empty_Cluster(x, n_chg)
If cluster_reset = 0 Then
If n_chg = 0 Then Exit For
End If
'Re-estimate centroid vector base on new cluster membership
Call ReCalculate_Centroids(x)
Next iterate
'=========================================
If iterate >= iter_max Then
Debug.Print "ckMeanCluster: Brute: Fail to converge in " & iter_max & " steps."
End If
Erase xi
Application.StatusBar = False
End Sub
'===========================================================
'Speed up k-Means clustering with filtering algorithm
'===========================================================
'"An Efficientk-Means Clustering Algorithm:Analysis and Implementation", Tapas Kanungo (2002)
Sub kMean_Filtering(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN", Optional use_kdTree As Boolean = False)
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long
Dim n_raw As Long, n_chg As Long, cluster_reset As Long
Dim prev_idx() As Long
Dim node_size() As Long, node_wgtcenter As Variant, node_min() As Double, node_max() As Double, node_idx As Variant
Dim k1 As ckdTree
Dim tree_type As String
Dim x_dist() As Double, isChg() As Long
pk = k
pDistType = VBA.UCase$(strType)
If pDistType = "EUCLIDEAN" Then
tree_type = "EUCLIDEAN"
ElseIf pDistType = "MANHATTAN" Then
tree_type = "MANHATTAN"
Else
Debug.Print "ckMeanCluster: Filtering: Invalid distance type."
End
End If
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
'Initialization with k-means++ scheme
Call Init_kplus(x)
'Build k-d Tree for data points
Set k1 = New ckdTree
Call k1.kMean_Build_Tree(x, node_size, node_wgtcenter, node_min, node_max, pDistType)
'Array holding pairwise distance between data and centroids
', use -1 to indicate values that are not calculated yet
ReDim x_dist(1 To n_raw, 1 To pk)
For j = 1 To pk
For i = 1 To n_raw
x_dist(i, j) = -1
Next i
Next j
'Iterate until convergence
ReDim px_cluster(1 To n_raw)
ReDim prev_idx(1 To n_raw)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Clustering: " & iterate & "/" & iter_max
End If
'Use filtering algorithm to assign data to centroids
Call k1.kMean_Assign_Center(x, node_size, node_wgtcenter, node_min, node_max, _
pcluster_mean, pcluster_size, px_cluster, x_dist, pDistType, use_kdTree)
'check if any cluster assignment has changed
n_chg = 0: ReDim isChg(0 To pk)
For i = 1 To n_raw
If px_cluster(i) <> prev_idx(i) Then
n_chg = n_chg + 1
isChg(px_cluster(i)) = isChg(px_cluster(i)) + 1
isChg(prev_idx(i)) = isChg(prev_idx(i)) + 1
End If
Next i
'Reset empty centroids
cluster_reset = Fill_Empty_Cluster(x, n_chg, isChg)
If cluster_reset = 0 Then
If n_chg = 0 Then Exit For
Else
Call ReCalculate_Centroids(x)
End If
'If any centroid has moved reset its distance to data
For j = 1 To pk
If isChg(j) > 0 Then
For i = 1 To n_raw
x_dist(i, j) = -1
Next i
End If
Next j
prev_idx = px_cluster
Next iterate
If iterate >= iter_max Then
Debug.Print "ckMeanCluster: Filtering: Fail to converge in " & iter_max & " steps."
End If
Call k1.Reset: Set k1 = Nothing
Erase node_size, node_wgtcenter, node_min, node_max, prev_idx, x_dist, isChg
Application.StatusBar = False
End Sub
'===========================================================
'Speed up k-Means clustering with triangle inequality
'===========================================================
'"Using the Triangle Inequality to Accelerate k-Means", Charlkes Elkan (2003)
'Note that since triangle inequalit is used, square root needs to to be taken on Euclidean distance
Sub kMean_Elkan(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN")
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long
Dim n_raw As Long, n_chg As Long, cluster_reset As Long, c_cur As Long
Dim prev_idx() As Long
Dim c_dist() As Double, s_dist() As Double, prev_c() As Double, c_chg() As Double
Dim ub() As Double, lb() As Double, xi() As Double
Dim tmp_x As Double, tmp_y As Double, tmp_z As Double
Dim r_chk As Boolean
pDistType = VBA.UCase$(strType)
If pDistType <> "EUCLIDEAN" And pDistType <> "MANHATTAN" And pDistType <> "CORREL" Then
Debug.Print "ckMeanCluster: Elkan: Invalid distance type."
End
End If
pk = k
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
'Initialization with k-means++ scheme
Call Init_kplus(x)
'Assign all points to same cluster, initialize invalid bounds
ReDim px_cluster(1 To n_raw)
ReDim ub(1 To n_raw)
ReDim lb(1 To n_raw, 1 To pk)
For i = 1 To n_raw
px_cluster(i) = 1
ub(i) = pINFINITY
Next i
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(x, px2, pxavg, pxsd)
End If
'Iterate until convergence
prev_idx = px_cluster
ReDim xi(1 To pn_dimension)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Elkan: " & iterate & "/" & iter_max
End If
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(pcluster_mean, pc2, pcavg, pcsd)
End If
'Compute centroid-centroid distances
Call Compute_Centroid_Centroid_Distance(c_dist, s_dist)
'Assign data to nearest centroid
For i = 1 To n_raw
c_cur = px_cluster(i): tmp_x = ub(i)
If tmp_x > s_dist(c_cur) Then
r_chk = True 'Boolean to check if upper bound needs tightening
For p = 1 To pn_dimension
xi(p) = x(i, p)
Next p
For n = 1 To pk
If n <> c_cur Then
tmp_z = (0.5 * c_dist(n, c_cur)): If lb(i, n) > tmp_z Then tmp_z = lb(i, n)
If tmp_x > tmp_z Then
If r_chk = True Then
ub(i) = Dist2Center_2_Fast(xi, i, c_cur)
tmp_x = ub(i)
r_chk = False
End If
If tmp_x > tmp_z Then
tmp_y = Dist2Center_2_Fast(xi, i, n)
lb(i, n) = tmp_y
If tmp_y < tmp_x Then
px_cluster(i) = n: c_cur = n
ub(i) = tmp_y: tmp_x = tmp_y
End If
End If
End If
End If
Next n
End If
Next i
'Re-estimate cluster size
ReDim pcluster_size(1 To pk)
For i = 1 To n_raw
j = px_cluster(i)
pcluster_size(j) = pcluster_size(j) + 1
Next i
n_chg = 0
cluster_reset = Fill_Empty_Cluster(x, n_chg)
If cluster_reset = 0 Then
'Re-estimate centroid positions and record distance moved
prev_c = pcluster_mean
ReDim c_chg(1 To pk)
Call ReCalculate_Centroids(x)
For j = 1 To pk
For p = 1 To pn_dimension
xi(p) = prev_c(j, p)
Next p
c_chg(j) = Dist2Center_2(xi, j)
Next j
'Update lower and upper bound
For i = 1 To n_raw
ub(i) = ub(i) + c_chg(px_cluster(i))
Next i
For j = 1 To pk
tmp_x = c_chg(j)
For i = 1 To n_raw
lb(i, j) = lb(i, j) - tmp_x
If lb(i, j) < 0 Then lb(i, j) = 0
Next i
Next j
'check if any cluster assignment has changed
n_chg = 0
For i = 1 To n_raw
If px_cluster(i) <> prev_idx(i) Then
n_chg = n_chg + 1
Exit For
End If
Next i
If n_chg = 0 Then Exit For
prev_idx = px_cluster
End If
Next iterate
If iterate >= iter_max Then
Debug.Print "ckMeanCluster: Elkan: Fail to converge in " & iter_max & " steps."
End If
Erase c_dist, s_dist, ub, lb, prev_idx, xi, c_chg
If pDistType = "EUCLIDEAN" Then
Erase px2, pc2
ElseIf pDistType = "CORREL" Then
Erase pxavg, pxsd, pcavg, pcsd
End If
Application.StatusBar = False
End Sub
'=================================================================================
'Speed up k-Means clustering with triangle inequality and only one lower bound
'=================================================================================
'"Making k-means even faster", Greg Hamerly (2010)
Sub kMean_Hamerly(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN")
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long
Dim n_raw As Long, n_chg As Long, cluster_reset As Long, c_cur As Long
Dim prev_idx() As Long
Dim c_dist() As Double, s_dist() As Double, prev_c() As Double
Dim c_chg() As Double, c_chg_max As Double, c_chg_max2 As Double
Dim ub() As Double, lb() As Double, xi() As Double
Dim tmp_x As Double, tmp_y As Double, z As Double
Dim h1 As cHeap
pDistType = VBA.UCase(strType)
If pDistType <> "EUCLIDEAN" And pDistType <> "MANHATTAN" And pDistType <> "CORREL" Then
Debug.Print "ckMeanCluster: Hamerly: Invalid distance type."
End
End If
pk = k
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
'Initialization with k-means++ scheme
Call Init_kplus(x)
'Assign all points to same cluster, initialize invalid bounds
ReDim px_cluster(1 To n_raw) 'index to nearest centroid
ReDim ub(1 To n_raw) 'upper bound nearest centroid
ReDim lb(1 To n_raw) 'lower bound 2nd nearest centroid
For i = 1 To n_raw
px_cluster(i) = 1
ub(i) = pINFINITY
Next i
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(x, px2, pxavg, pxsd)
End If
'Iterate until convergence
Set h1 = New cHeap 'Heap is used to find closest and 2nd closest centroids
prev_idx = px_cluster
ReDim xi(1 To pn_dimension)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Hamerly: " & iterate & "/" & iter_max
End If
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(pcluster_mean, pc2, pcavg, pcsd)
End If
'Compute centroid-centroid distances
Call Compute_Centroid_Centroid_Distance(c_dist, s_dist)
'Assign data to nearest centroid
For i = 1 To n_raw
c_cur = px_cluster(i)
z = s_dist(c_cur): If lb(i) > z Then z = lb(i)
If ub(i) > z Then
For p = 1 To pn_dimension
xi(p) = x(i, p)
Next p
ub(i) = Dist2Center_2_Fast(xi, i, c_cur)
If ub(i) > z Then
With h1
Call .Init("MIN")
Call .Add(ub(i), c_cur)
For j = 1 To pk
If j <> c_cur Then Call .Add(Dist2Center_2_Fast(xi, i, j), j)
Next j
Call .Pop_Min(tmp_x, j)
If j <> c_cur Then
ub(i) = tmp_x
px_cluster(i) = j
End If
Call .Pop_Min(tmp_x, j)
lb(i) = tmp_x
End With
End If
End If
Next i
'Re-estimate cluster size
ReDim pcluster_size(1 To pk)
For i = 1 To n_raw
j = px_cluster(i)
pcluster_size(j) = pcluster_size(j) + 1
Next i
n_chg = 0
cluster_reset = Fill_Empty_Cluster(x, n_chg)
If cluster_reset = 0 Then
'Re-estimate centroid positions and record distance moved
prev_c = pcluster_mean
Call ReCalculate_Centroids(x)
ReDim c_chg(1 To pk)
Call h1.Init("MAX")
For j = 1 To pk
For p = 1 To pn_dimension
xi(p) = prev_c(j, p)
Next p
c_chg(j) = Dist2Center_2(xi, j)
Call h1.Add(c_chg(j), j)
Next j
Call h1.Pop_Max(c_chg_max, n)
Call h1.Pop_Max(c_chg_max2, m)
'Update lower and upper bound
For i = 1 To n_raw
ub(i) = ub(i) + c_chg(px_cluster(i))
If px_cluster(i) = n Then
lb(i) = lb(i) - c_chg_max2
Else
lb(i) = lb(i) - c_chg_max
End If
Next i
'check if any cluster assignment has changed
n_chg = 0
For i = 1 To n_raw
If px_cluster(i) <> prev_idx(i) Then
n_chg = n_chg + 1
Exit For
End If
Next i
If n_chg = 0 Then Exit For
prev_idx = px_cluster
End If
Next iterate
If iterate >= iter_max Then
Debug.Print "ckMeanCluster: Hamerly: Fail to converge in " & iter_max & " steps."
End If
Call h1.Reset
Set h1 = Nothing
Erase c_dist, s_dist, ub, lb, prev_idx
If pDistType = "EUCLIDEAN" Then
Erase px2, pc2
ElseIf pDistType = "CORREL" Then
Erase pxavg, pxsd, pcavg, pcsd
End If
Application.StatusBar = False
End Sub
'=================================================================================
'Speed up k-Means clustering with triangle inequality and annular search constraint
'=================================================================================
'"Accelerating Lloyd's Algorithm for k-Means Clsutering", Greg Hamerly and Jonathan Drake (2014)
'Note that since triangle inequality is used, square root needs to to be taken on Euclidean distance
Sub kMean_Annular(x() As Double, k As Long, Optional iter_max As Long = 100, _
Optional strType As String = "EUCLIDEAN")
Dim i As Long, j As Long, m As Long, n As Long, p As Long, iterate As Long, jj As Long, j_start As Long
Dim n_raw As Long, n_chg As Long, cluster_reset As Long, c_cur As Long, c_cur2 As Long
Dim prev_idx() As Long
Dim c_dist() As Double, s_dist() As Double, prev_c() As Double
Dim c_chg() As Double, c_chg_max As Double, c_chg_max2 As Double
Dim ub() As Double, lb() As Double, xi() As Double
Dim tmp_x As Double, tmp_y As Double, z As Double
Dim x_norm() As Double, c_norm() As Double, sort_idx() As Long, c_sort() As Long, x_idx2() As Long
Dim h1 As cHeap
Dim c_max As Double, c_min As Double
pDistType = VBA.UCase(strType)
If pDistType <> "EUCLIDEAN" And pDistType <> "MANHATTAN" And pDistType <> "CORREL" Then
Debug.Print "ckMeanCluster: Elkan: Invalid distance type."
End
End If
pk = k
n_raw = UBound(x, 1)
pn_dimension = UBound(x, 2)
'Initialization with k-means++ scheme
Call Init_kplus(x)
'Find norm of x()
Call Calc_Vec_Norm(x, x_norm, strType)
'Assign all points to same cluster, initialize invalid bounds
ReDim px_cluster(1 To n_raw) 'index to nearest centroid
ReDim x_idx2(1 To n_raw) 'index to 2nd nearest centroid
ReDim ub(1 To n_raw) 'upper bound nearest centroid
ReDim lb(1 To n_raw) 'lower bound on 2nd nearest centroid
For i = 1 To n_raw
px_cluster(i) = 1
x_idx2(i) = 2
ub(i) = pINFINITY
Next i
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(x, px2, pxavg, pxsd)
End If
'Iterate until convergence
Set h1 = New cHeap 'Heap is used to find closest and 2nd closest centroids
prev_idx = px_cluster
ReDim xi(1 To pn_dimension)
For iterate = 1 To iter_max
If iterate Mod 20 = 0 Then
DoEvents: Application.StatusBar = "k-Means Annular: " & iterate & "/" & iter_max
End If
If pDistType = "EUCLIDEAN" Or pDistType = "CORREL" Then
Call Calc_Aux(pcluster_mean, pc2, pcavg, pcsd)
End If
'Compute centroid-centroid distances
Call Compute_Centroid_Centroid_Distance(c_dist, s_dist)
'Find norm of centroids and sort in ascending order
Call Calc_Vec_Norm(pcluster_mean, c_norm, strType)
Call modMath.Sort_Quick_A(c_norm, 1, pk, c_sort)
'Assign data to nearest centroid
For i = 1 To n_raw
c_cur = px_cluster(i)
z = s_dist(c_cur): If lb(i) > z Then z = lb(i)
If ub(i) > z Then
For p = 1 To pn_dimension
xi(p) = x(i, p)
Next p
ub(i) = Dist2Center_2_Fast(xi, i, c_cur)
If ub(i) > z Then
c_cur2 = x_idx2(i)
lb(i) = Dist2Center_2_Fast(xi, i, c_cur2)
z = ub(i): If lb(i) > z Then z = lb(i)
c_max = x_norm(i) + z 'Outer ring of annulus
c_min = x_norm(i) - z 'Inner ring of annulus
j_start = Binary_Search(c_norm, c_min)
If j_start = 0 Then j_start = 1
With h1
Call .Init("MIN")
Call .Add(ub(i), c_cur)
Call .Add(lb(i), c_cur2)
For j = j_start To pk
If c_norm(j) > c_max Then Exit For
jj = c_sort(j)
If jj <> c_cur And jj <> c_cur2 Then
Call .Add(Dist2Center_2_Fast(xi, i, jj), jj)
End If
Next j
Call .Pop_Min(tmp_x, j)
If tmp_x < ub(i) Then
ub(i) = tmp_x
px_cluster(i) = j
End If
Call .Pop_Min(tmp_x, j)
If tmp_x < lb(i) Then
lb(i) = tmp_x
x_idx2(i) = j
End If
End With
End If
End If
Next i
'Re-estimate cluster size
ReDim pcluster_size(1 To pk)
For i = 1 To n_raw
j = px_cluster(i)
pcluster_size(j) = pcluster_size(j) + 1
Next i
n_chg = 0
cluster_reset = Fill_Empty_Cluster(x, n_chg)
If cluster_reset = 0 Then
'Re-estimate centroid positions and record distance moved
prev_c = pcluster_mean
Call ReCalculate_Centroids(x)
ReDim c_chg(1 To pk)
Call h1.Init("MAX")
For j = 1 To pk
For p = 1 To pn_dimension
xi(p) = prev_c(j, p)
Next p
c_chg(j) = Dist2Center_2(xi, j)
Call h1.Add(c_chg(j), j)
Next j
Call h1.Pop_Max(c_chg_max, n)
Call h1.Pop_Max(c_chg_max2, m)
'Update lower and upper bound
For i = 1 To n_raw
ub(i) = ub(i) + c_chg(px_cluster(i))
If px_cluster(i) = n Then
lb(i) = lb(i) - c_chg_max2
Else
lb(i) = lb(i) - c_chg_max
End If
Next i
'check if any cluster assignment has changed
n_chg = 0
For i = 1 To n_raw
If px_cluster(i) <> prev_idx(i) Then
n_chg = n_chg + 1
Exit For
End If
Next i
If n_chg = 0 Then Exit For
prev_idx = px_cluster
End If
Next iterate
If iterate >= iter_max Then