-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmodes.pas
1097 lines (919 loc) · 26.3 KB
/
kmodes.pas
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
// Adapted from https://github.com/nicodv/kmodes
unit kmodes;
//{$define GENERIC_DISSIM}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Types, Math, LazLogger, MTProcs, windows, extern;
const
cKModesFeatureCount = 80;
cDissimSubMatchingSize = 11;
cPhi = (1 + sqrt(5)) / 2;
cInvPhi = 1 / cPhi;
type
PInteger = ^Integer;
TCompareFunction=function(Item1,Item2,UserParameter:Pointer):Integer;
TIntegerDynArray2 = array of TIntegerDynArray;
TIntegerDynArray3 = array of TIntegerDynArray2;
TByteDynArray2 = array of TByteDynArray;
TByteDynArray3 = array of TByteDynArray2;
TUInt64DynArray = array of UInt64;
TUInt64DynArray2 = array of TUInt64DynArray;
TGMMD = record
clust: PInteger;
dis: PUInt64;
X, centroids: PPByte;
end;
TKmodesRun = packed record
Labels: TIntegerDynArray;
Centroids: TByteDynArray2;
Cost: UInt64;
NIter: Integer;
TotalMoves: Integer;
StartingPoint: Integer;
end;
{ TKModes }
TKModes = class
private
membship: TIntegerDynArray;
X: TByteDynArray2;
centroids: TByteDynArray2;
cl_attr_freq: TIntegerDynArray3;
MaxIter, NumClusters, NumThreads, NumAttrs, NumPoints: Integer;
Log: Integer;
LogLabel: String;
Concurrency: PInteger;
FGMMD: TGMMD;
FPTP: TProcThreadPool;
procedure DoGMMD(AIndex: PtrInt; AData: Pointer; AItem: TMultiThreadProcItem);
procedure FinishGMMD;
function GetConcurrentNumThreads: Integer;
function CountClusterMembers(cluster: Integer): Integer;
function GetMaxClusterMembers(out member_count: Integer): Integer;
function KModesIter(var Seed: Cardinal; out Cost: UInt64): Integer;
function InitFarthestFirst(InitPoint: Integer): TByteDynArray2; // negative init_point means randomly chosen
procedure MovePointCat(const point: TByteDynArray; ipoint, to_clust, from_clust: Integer);
public
constructor Create(aNumThreads: Integer = 0; aMaxIter: Integer = -1; aLog: Integer = 1; aLogLabel: String = ''; aConcurrency: PInteger = nil);
destructor Destroy; override;
function ComputeKModes(const ADataset: TByteDynArray2; ANumClusters, ANumInit, ANumModalities: Integer; out FinalLabels: TIntegerDynArray; out FinalCentroids: TByteDynArray2): Integer;
// negative n_init means use -n_init as starting point
// FinalLabels cluster indexes start at 1
end;
function RandInt(Range: Cardinal; var Seed: Cardinal): Cardinal;
procedure QuickSort(var AData;AFirstItem,ALastItem,AItemSize:Integer;ACompareFunction:TCompareFunction;AUserParameter:Pointer=nil);
function MatchingDissim(const a: TByteDynArray; const b: TByteDynArray): UInt64; inline; overload;
function MatchingDissim(a: PBYTE; b: PByte; count: Integer): UInt64; inline; overload;
function GetMinMatchingDissim(const a: TByteDynArray2; const b: TByteDynArray; count: Integer; out bestDissim: UInt64): Integer; overload;
implementation
{$PUSH}
{$RANGECHECKS OFF}
function RandInt(Range: Cardinal; var Seed: Cardinal): Cardinal;
begin
Seed := Integer(Seed * $08088405) + 1;
Result := (Seed * Range) shr 32;
end;
{$POP}
procedure QuickSort(var AData;AFirstItem,ALastItem,AItemSize:Integer;ACompareFunction:TCompareFunction;AUserParameter:Pointer=nil);
var I, J, P: Integer;
PData,P1,P2: PByte;
Tmp: array[0..4095] of Byte;
begin
if ALastItem <= AFirstItem then
Exit;
Assert(AItemSize < SizeOf(Tmp),'AItemSize too big!');
PData:=PByte(@AData);
repeat
I := AFirstItem;
J := ALastItem;
P := (AFirstItem + ALastItem) shr 1;
repeat
P1:=PData;Inc(P1,I*AItemSize);
P2:=PData;Inc(P2,P*AItemSize);
while ACompareFunction(P1, P2, AUserParameter) < 0 do
begin
Inc(I);
Inc(P1,AItemSize);
end;
P1:=PData;Inc(P1,J*AItemSize);
//P2:=PData;Inc(P2,P*AItemSize); already done
while ACompareFunction(P1, P2, AUserParameter) > 0 do
begin
Dec(J);
Dec(P1,AItemSize);
end;
if I <= J then
begin
P1:=PData;Inc(P1,I*AItemSize);
P2:=PData;Inc(P2,J*AItemSize);
Move(P2^, Tmp[0], AItemSize);
Move(P1^, P2^, AItemSize);
Move(Tmp[0], P1^, AItemSize);
if P = I then
P := J
else if P = J then
P := I;
Inc(I);
Dec(J);
end;
until I > J;
if AFirstItem < J then QuickSort(AData,AFirstItem,J,AItemSize,ACompareFunction,AUserParameter);
AFirstItem := I;
until I >= ALastItem;
end;
function CompareLines(Item1,Item2,UserParameter:Pointer): Integer;
begin
Result := CompareByte(PByteArray(Item1)^[0], PByteArray(Item2)^[0], SizeInt(UserParameter));
end;
function CompareDis(Item1,Item2,UserParameter:Pointer): Integer;
begin
Result := CompareValue(PByte(UserParameter)[PInteger(Item1)^], PByte(UserParameter)[PInteger(Item2)^]);
end;
function GetMaxValueIndex(const arr: TIntegerDynArray): Integer; overload;
var
best, ik: Integer;
begin
Result := -1;
best := Low(Integer);
for ik := 0 to High(arr) do
if arr[ik] > best then
begin
best := arr[ik];
Result := ik;
end;
end;
function GetMinValueIndex(const arr: TIntegerDynArray): Integer; overload;
var
best, ik: Integer;
begin
Result := -1;
best := High(Integer);
for ik := 0 to High(arr) do
if arr[ik] < best then
begin
best := arr[ik];
Result := ik;
end;
end;
function GetMinValueIndex(const arr: TByteDynArray): Integer; overload;
var
ik: Integer;
best: Byte;
begin
Result := -1;
best := High(Byte);
for ik := 0 to High(arr) do
if arr[ik] < best then
begin
best := arr[ik];
Result := ik;
end;
end;
function GetUniqueRows(const X: TByteDynArray2): TByteDynArray2;
var
i, j, Cnt: Integer;
begin
Result := Copy(X);
if Length(Result) <= 1 then
Exit;
QuickSort(Result[0], 0, High(Result), SizeOf(TByteDynArray), @CompareLines, Pointer(Length(Result[0])));
Cnt := Length(Result);
for i := High(Result) - 1 downto 0 do
if CompareByte(Result[i, 0], Result[i + 1, 0], Length(Result[0])) = 0 then
begin
for j := i + 1 to Cnt - 2 do
Result[j] := Result[j + 1];
Dec(Cnt);
end;
SetLength(Result, Cnt);
end;
function CountUniqueRows(const X: TByteDynArray2): Integer;
var
i, Cnt: Integer;
NumAttrs: Integer;
unique: TByteDynArray2;
begin
Result := 0;
if Length(X) < 1 then
Exit;
NumAttrs := Length(X[0]);
unique := Copy(X);
QuickSort(unique[0], 0, High(unique), SizeOf(TByteDynArray), @CompareLines, Pointer(NumAttrs));
Cnt := Length(unique);
for i := High(unique) - 1 downto 0 do
if CompareByte(unique[i, 0], unique[i + 1, 0], NumAttrs) = 0 then
Dec(Cnt);
Result := Cnt;
end;
function MatchingDissim(const a: TByteDynArray; const b: TByteDynArray): UInt64; inline; overload;
begin
Result := MatchingDissim(@a[0], @b[0], Length(a));
end;
function MatchingDissim(a: PByte; b: PByte; count: Integer): UInt64; inline; overload;
var
i: Integer;
begin
Result := 0;
for i := 0 to count - 1 do
begin
if a[i] <> b[i] then
Result += UInt64(1) shl cDissimSubMatchingSize;
Result += abs(Int64(a[i]) - Int64(b[i]));
end;
end;
{$if defined(GENERIC_DISSIM) or not defined(CPUX86_64)}
function GetMinMatchingDissim(const a: TByteDynArray2; const b: TByteDynArray; count: Integer; out bestDissim: UInt64): Integer; overload;
var
i: Integer;
dis, best: UInt64;
begin
Result := -1;
best := High(UInt64);
for i := 0 to count - 1 do
begin
dis := MatchingDissim(a[i], b);
if dis <= best then
begin
best := dis;
Result := i;
end;
end;
bestDissim := best;
end;
//function GetMatchingDissimSum(const a: TByteDynArray2; const b: TByteDynArray; count: Integer): UInt64;
//var
// i: Integer;
//begin
// Result := 0;
// for i := 0 to count - 1 do
// Result += MatchingDissim(a[i], b);
//end;
function GetMinMatchingDissim(a: PPByte; b: PByte; rowCount, colCount: Integer; out bestDissim: UInt64): Integer; overload;
var
i: Integer;
dis, best: UInt64;
begin
Result := -1;
best := High(UInt64);
for i := 0 to rowCount - 1 do
begin
dis := MatchingDissim(a[i], b, colCount);
if dis <= best then
begin
best := dis;
Result := i;
end;
end;
bestDissim := best;
end;
{$else}
function GetMinMatchingDissim_Asm(item_rcx: PByte; list_rdx: PPByte; count_r8: UInt64; pbest_r9: PUInt64): Int64; register; assembler; nostackframe;
label loop, worst;
asm
push rbx
push rcx
push rsi
push rdi
push r8
push r10
push rdx
sub rsp, 16 * 12
movdqu oword ptr [rsp], xmm0
movdqu oword ptr [rsp + $10], xmm1
movdqu oword ptr [rsp + $20], xmm2
movdqu oword ptr [rsp + $30], xmm3
movdqu oword ptr [rsp + $40], xmm4
movdqu oword ptr [rsp + $50], xmm5
movdqu oword ptr [rsp + $60], xmm6
movdqu oword ptr [rsp + $70], xmm7
movdqu oword ptr [rsp + $80], xmm8
movdqu oword ptr [rsp + $90], xmm9
movdqu oword ptr [rsp + $a0], xmm10
movdqu oword ptr [rsp + $b0], xmm11
movdqu xmm6, oword ptr [item_rcx]
movdqu xmm7, oword ptr [item_rcx + $10]
movdqu xmm8, oword ptr [item_rcx + $20]
movdqu xmm9, oword ptr [item_rcx + $30]
movdqu xmm10, oword ptr [item_rcx + $40]
lea rbx, [list_rdx + 8 * r8]
lea rax, [list_rdx - 8]
xor r8, r8
dec r8
loop:
mov rcx, qword ptr [list_rdx]
movdqu xmm0, oword ptr [rcx]
movdqu xmm1, oword ptr [rcx + $10]
movdqu xmm2, oword ptr [rcx + $20]
movdqu xmm3, oword ptr [rcx + $30]
movdqu xmm4, oword ptr [rcx + $40]
movdqa xmm11, xmm0
psadbw xmm11, xmm6
movdqa xmm5, xmm1
psadbw xmm5, xmm7
paddw xmm11, xmm5
movdqa xmm5, xmm2
psadbw xmm5, xmm8
paddw xmm11, xmm5
movdqa xmm5, xmm3
psadbw xmm5, xmm9
paddw xmm11, xmm5
movdqa xmm5, xmm4
psadbw xmm5, xmm10
paddw xmm11, xmm5
pcmpeqb xmm0, xmm6
pcmpeqb xmm1, xmm7
pcmpeqb xmm2, xmm8
pcmpeqb xmm3, xmm9
pcmpeqb xmm4, xmm10
pmovmskb edi, xmm0
mov rsi, rdi
pmovmskb edi, xmm1
rol rsi, 16
or rsi, rdi
pmovmskb edi, xmm2
rol rsi, 16
or rsi, rdi
pmovmskb edi, xmm3
rol rsi, 16
or rsi, rdi
not rsi
popcnt rsi, rsi
pmovmskb edi, xmm4
not di
popcnt di, di
add rsi, rdi
shl rsi, cDissimSubMatchingSize
pextrw r10d, xmm11, 0
add rsi, r10
pextrw r10d, xmm11, 4
add rsi, r10
cmp rsi, r8
ja worst
mov r8, rsi
mov rax, list_rdx
worst:
add list_rdx, 8
cmp list_rdx, rbx
jne loop
movdqu xmm0, oword ptr [rsp]
movdqu xmm1, oword ptr [rsp + $10]
movdqu xmm2, oword ptr [rsp + $20]
movdqu xmm3, oword ptr [rsp + $30]
movdqu xmm4, oword ptr [rsp + $40]
movdqu xmm5, oword ptr [rsp + $50]
movdqu xmm6, oword ptr [rsp + $60]
movdqu xmm7, oword ptr [rsp + $70]
movdqu xmm8, oword ptr [rsp + $80]
movdqu xmm9, oword ptr [rsp + $90]
movdqu xmm10, oword ptr [rsp + $a0]
movdqu xmm11, oword ptr [rsp + $b0]
add rsp, 16 * 12
mov qword ptr [pbest_r9], r8
pop rdx
sub rax, list_rdx
sar rax, 3
pop r10
pop r8
pop rdi
pop rsi
pop rcx
pop rbx
end;
procedure UpdateMinDistance_Asm(item_rcx: PByte; list_rdx: PPByte; used_r8: PBoolean; mindist_r9: PUInt64; count: Integer); register; assembler;
label loop, used, start;
asm
push rbx
push rcx
push rsi
push rdi
push rdx
push r8
push r9
push r10
sub rsp, 16 * 12
movdqu oword ptr [rsp], xmm0
movdqu oword ptr [rsp + $10], xmm1
movdqu oword ptr [rsp + $20], xmm2
movdqu oword ptr [rsp + $30], xmm3
movdqu oword ptr [rsp + $40], xmm4
movdqu oword ptr [rsp + $50], xmm5
movdqu oword ptr [rsp + $60], xmm6
movdqu oword ptr [rsp + $70], xmm7
movdqu oword ptr [rsp + $80], xmm8
movdqu oword ptr [rsp + $90], xmm9
movdqu oword ptr [rsp + $a0], xmm10
movdqu oword ptr [rsp + $b0], xmm11
movdqu xmm6, oword ptr [item_rcx]
movdqu xmm7, oword ptr [item_rcx + $10]
movdqu xmm8, oword ptr [item_rcx + $20]
movdqu xmm9, oword ptr [item_rcx + $30]
movdqu xmm10, oword ptr [item_rcx + $40]
mov eax, count
lea rbx, [list_rdx + 8 * rax]
xor eax, eax
jmp start
loop:
mov rcx, qword ptr [list_rdx]
add list_rdx, 8
movdqu xmm0, oword ptr [rcx]
movdqu xmm1, oword ptr [rcx + $10]
movdqu xmm2, oword ptr [rcx + $20]
movdqu xmm3, oword ptr [rcx + $30]
movdqu xmm4, oword ptr [rcx + $40]
movdqa xmm11, xmm0
psadbw xmm11, xmm6
movdqa xmm5, xmm1
psadbw xmm5, xmm7
paddw xmm11, xmm5
movdqa xmm5, xmm2
psadbw xmm5, xmm8
paddw xmm11, xmm5
movdqa xmm5, xmm3
psadbw xmm5, xmm9
paddw xmm11, xmm5
movdqa xmm5, xmm4
psadbw xmm5, xmm10
paddw xmm11, xmm5
pcmpeqb xmm0, xmm6
pcmpeqb xmm1, xmm7
pcmpeqb xmm2, xmm8
pcmpeqb xmm3, xmm9
pcmpeqb xmm4, xmm10
pmovmskb edi, xmm0
mov rsi, rdi
pmovmskb edi, xmm1
rol rsi, 16
or rsi, rdi
pmovmskb edi, xmm2
rol rsi, 16
or rsi, rdi
pmovmskb edi, xmm3
rol rsi, 16
or rsi, rdi
not rsi
popcnt rsi, rsi
pmovmskb edi, xmm4
not di
popcnt di, di
add rsi, rdi
shl rsi, cDissimSubMatchingSize
pextrw r10d, xmm11, 0
add rsi, r10
pextrw r10d, xmm11, 4
add rsi, r10
mov rax, qword ptr [mindist_r9]
cmp rsi, rax
cmovb rax, rsi
mov qword ptr [mindist_r9], rax
used:
inc used_r8
add mindist_r9, 8
start:
test byte ptr [used_r8], 0
jne used
cmp list_rdx, rbx
jne loop
movdqu xmm0, oword ptr [rsp]
movdqu xmm1, oword ptr [rsp + $10]
movdqu xmm2, oword ptr [rsp + $20]
movdqu xmm3, oword ptr [rsp + $30]
movdqu xmm4, oword ptr [rsp + $40]
movdqu xmm5, oword ptr [rsp + $50]
movdqu xmm6, oword ptr [rsp + $60]
movdqu xmm7, oword ptr [rsp + $70]
movdqu xmm8, oword ptr [rsp + $80]
movdqu xmm9, oword ptr [rsp + $90]
movdqu xmm10, oword ptr [rsp + $a0]
movdqu xmm11, oword ptr [rsp + $b0]
add rsp, 16 * 12
pop r10
pop r9
pop r8
pop rdx
pop rdi
pop rsi
pop rcx
pop rbx
end;
function GetMinMatchingDissim(const a: TByteDynArray2; const b: TByteDynArray; count: Integer; out bestDissim: UInt64): Integer; overload;
var
bd: UInt64;
begin
Result := GetMinMatchingDissim_Asm(@b[0], @a[0], count, @bd);
bestDissim := bd;
end;
function GetMinMatchingDissim(a: PPByte; b: PByte; rowCount, colCount: Integer; out bestDissim: UInt64): Integer; overload;
var
bd: UInt64;
begin
Result := GetMinMatchingDissim_Asm(b, a, rowCount, @bd);
bestDissim := bd;
end;
{$endif}
function TKModes.CountClusterMembers(cluster: Integer): Integer;
var
i: Integer;
pm: PInteger;
begin
Result := 0;
pm := @membship[0];
for i := 0 to High(membship) do
begin
Inc(Result, Ord(pm^ = cluster));
Inc(pm);
end;
end;
function TKModes.GetMaxClusterMembers(out member_count: Integer): Integer;
var
quantum, mc_loc, mc, cluster, i: Integer;
pm0, pm1, pm2, pm3: PInteger;
begin
Result := 0;
mc := 0;
quantum := Length(membship) shr 2;
for cluster := 0 to NumClusters - 1 do
begin
mc_loc := 0;
pm0 := @membship[quantum * 0];
pm1 := @membship[quantum * 1];
pm2 := @membship[quantum * 2];
pm3 := @membship[quantum * 3];
for i := 0 to quantum - 1 do
begin
Inc(mc_loc, Ord(pm0^ = cluster)); Inc(pm0);
Inc(mc_loc, Ord(pm1^ = cluster)); Inc(pm1);
Inc(mc_loc, Ord(pm2^ = cluster)); Inc(pm2);
Inc(mc_loc, Ord(pm3^ = cluster)); Inc(pm3);
end;
for i := (quantum shl 2) to Length(membship) - 1 do
begin
Inc(mc_loc, Ord(pm3^ = cluster)); Inc(pm3);
end;
if mc_loc >= mc then
begin
mc := mc_loc;
Result := cluster;
end;
end;
member_count := mc;
end;
{$if not(defined(GENERIC_DISSIM) or not defined(CPUX86_64))}
type
TUMD = record
NumBins, NumPoints, BinSize, icenter: Integer;
mindistance: TUInt64DynArray;
used: TBooleanDynArray;
X: TByteDynArray2;
end;
PUMD = ^TUMD;
procedure DoUMD(AIndex: PtrInt; AData: Pointer; AItem: TMultiThreadProcItem);
var
UMD: PUMD;
idx, cnt: Integer;
begin
UMD := PUMD(AData);
cnt := UMD^.BinSize;
idx := AIndex * cnt;
if idx >= UMD^.NumBins - 1 then
cnt := UMD^.NumPoints - idx;
UpdateMinDistance_Asm(@UMD^.X[UMD^.icenter, 0], @UMD^.X[idx], @UMD^.used[idx], @UMD^.mindistance[idx], cnt);
end;
{$endif}
function TKModes.InitFarthestFirst(InitPoint: Integer): TByteDynArray2;
var
icentroid, ifarthest, i: Integer;
max: UInt64;
used: TBooleanDynArray;
mindistance: TUInt64DynArray;
procedure UpdateMinDistance(icenter: Integer); inline;
{$if defined(GENERIC_DISSIM) or not defined(CPUX86_64)}
var
i: Integer;
dis: UInt64;
begin
for i := 0 to NumPoints - 1 do
if not used[i] then
begin
dis := MatchingDissim(X[icenter], X[i]);
if dis < mindistance[i] then
mindistance[i] := dis;
end;
end;
{$else}
const
cBinSize = 524288;
var
UMD: TUMD;
begin
if (NumThreads <= 1) and not Assigned(Concurrency) then
begin
UpdateMinDistance_Asm(@X[icenter, 0], @X[0], @used[0], @mindistance[0], NumPoints);
end
else
begin
UMD.NumBins := (NumPoints - 1) div cBinSize + 1;
UMD.NumPoints := NumPoints;
UMD.BinSize := min(NumPoints, cBinSize);
UMD.icenter := icenter;
UMD.mindistance := mindistance;
UMD.used := used;
UMD.X := X;
FPTP.DoParallel(@DoUMD, 0, UMD.NumBins - 1, @UMD, GetConcurrentNumThreads);
end;
end;
{$endif}
begin
SetLength(Result, NumClusters, NumAttrs);
SetLength(used, NumPoints);
SetLength(mindistance, NumPoints);
for icentroid := 0 to NumClusters - 1 do
FillByte(Result[icentroid, 0], NumAttrs, High(Byte));
FillChar(used[0], NumPoints, False);
FillQWord(mindistance[0], NumPoints, High(UInt64));
icentroid := 0;
ifarthest := InitPoint;
Move(X[ifarthest, 0], Result[icentroid, 0], NumAttrs);
used[ifarthest] := True;
UpdateMinDistance(ifarthest);
for icentroid := 1 to NumClusters - 1 do
begin
max := 0;
ifarthest := InitPoint;
for i := 0 to NumPoints - 1 do
if (MinDistance[i] >= max) and not Used[i] then
begin
max := MinDistance[i];
ifarthest := i;
end;
Move(X[ifarthest, 0], Result[icentroid, 0], NumAttrs);
used[ifarthest] := True;
UpdateMinDistance(ifarthest);
end;
end;
procedure TKModes.MovePointCat(const point: TByteDynArray; ipoint, to_clust, from_clust: Integer);
var
iattr, curattr, current_attribute_value_freq, current_centroid_value, current_centroid_freq, old_centroid_value: Integer;
to_attr_counts, from_attr_counts: TIntegerDynArray;
begin
membship[ipoint] := to_clust;
for iattr := 0 to High(point) do
begin
curattr := point[iattr];
to_attr_counts := cl_attr_freq[to_clust, iattr];
from_attr_counts := cl_attr_freq[from_clust, iattr];
Inc(to_attr_counts[curattr]);
current_attribute_value_freq := to_attr_counts[curattr];
current_centroid_value := centroids[to_clust, iattr];
current_centroid_freq := to_attr_counts[current_centroid_value];
if current_centroid_freq < current_attribute_value_freq then
centroids[to_clust, iattr] := curattr;
Dec(from_attr_counts[curattr]);
old_centroid_value := centroids[from_clust, iattr];
if old_centroid_value = curattr then
centroids[from_clust, iattr] := GetMaxValueIndex(from_attr_counts);
end;
end;
constructor TKModes.Create(aNumThreads: Integer; aMaxIter: Integer; aLog: Integer; aLogLabel: String;
aConcurrency: PInteger);
begin
inherited Create;
FPTP := TProcThreadPool.Create;
Self.MaxIter := aMaxIter;
Self.NumThreads := aNumThreads;
Self.Log := aLog;
Self.LogLabel := aLogLabel;
Self.Concurrency := aConcurrency;
end;
destructor TKModes.Destroy;
begin
inherited Destroy;
FPTP.Free;
end;
procedure TKModes.DoGMMD(AIndex: PtrInt; AData: Pointer; AItem: TMultiThreadProcItem);
var
dis: UInt64;
begin
if AIndex < NumPoints then
begin
FGMMD.clust[AIndex] := GetMinMatchingDissim(FGMMD.centroids, FGMMD.X[AIndex], NumClusters, NumAttrs, dis);
if Assigned(FGMMD.dis) then
FGMMD.dis[AIndex] := dis;
end;
end;
procedure TKModes.FinishGMMD;
begin
FGMMD.clust := nil;
FGMMD.dis := nil;
FGMMD.X := nil;
FGMMD.centroids := nil;
end;
function TKModes.GetConcurrentNumThreads: Integer;
begin
Result := NumThreads;
if Assigned(Concurrency) then
Result := max(Result, FPTP.MaxThreadCount - (Concurrency^ - 1) * NumThreads);
end;
function TKModes.KModesIter(var Seed: Cardinal; out Cost: UInt64): Integer;
const
cBinSize = 960;
var
ipoint, old_clust, from_clust, rindx, cnt, dummy, i, bin, last: Integer;
cost_acc: UInt64;
clust, choices: TIntegerDynArray;
dis: TUInt64DynArray;
begin
Result := 0;
cost_acc := 0;
SetLength(choices, NumPoints);
SetLength(clust, NumPoints);
SetLength(dis, NumPoints);
FGMMD.clust := @clust[0];
FGMMD.dis := @dis[0];
FGMMD.X := @X[0];
FGMMD.centroids := @centroids[0];
for bin := 0 to ((NumPoints - 1) div cBinSize + 1) - 1 do
begin
last := min((bin + 1) * cBinSize, NumPoints) - 1;
if (NumThreads <= 1) and not Assigned(Concurrency) then
begin
for ipoint := bin * cBinSize to last do
clust[ipoint] := GetMinMatchingDissim(centroids, X[ipoint], Length(centroids), dis[ipoint]);
end
else
begin
FPTP.DoParallel(@DoGMMD, bin * cBinSize, last, nil, GetConcurrentNumThreads);
end;
for ipoint := bin * cBinSize to last do
begin
Inc(cost_acc, dis[ipoint]);
if membship[ipoint] <> clust[ipoint] then
begin
Inc(Result);
old_clust := membship[ipoint];
MovePointCat(X[ipoint], ipoint, clust[ipoint], old_clust);
if CountClusterMembers(old_clust) = 0 then
begin
from_clust := GetMaxClusterMembers(dummy);
//writeln('zero', #9, from_clust, #9, dummy);
cnt := 0;
for i := 0 to High(membship) do
if membship[i] = from_clust then
begin
choices[cnt] := i;
Inc(cnt);
end;
rindx := choices[RandInt(cnt, Seed)];
MovePointCat(X[rindx], rindx, old_clust, from_clust);
end;
end;
end;
end;
FinishGMMD;
Cost := cost_acc;
end;
function TKModes.ComputeKModes(const ADataset: TByteDynArray2; ANumClusters, ANumInit, ANumModalities: Integer;
out FinalLabels: TIntegerDynArray; out FinalCentroids: TByteDynArray2): Integer;
const
CMaxWorseGraces = 3;
var
init: TByteDynArray2;
all: array of TKmodesRun;
var
i, j, init_no, iattr, ipoint, ik, summemb, itr, bestitr, moves, totalmoves, worsecounter: Integer;
best, dis: UInt64;
converged: Boolean;
prevcost, cost, bestcost: UInt64;
InvGoldenRatio, GRAcc: Single;
Seed: Cardinal;
bestmembship: TIntegerDynArray;
bestcentroids: TByteDynArray2;
begin
Seed := $42381337;
X := ADataset;
NumPoints := Length(X);
NumClusters := ANumClusters;
NumAttrs := 0;
if NumPoints > 0 then
NumAttrs := Length(X[0]);
if NumThreads <= 0 then
NumThreads := ProcThreadPool.MaxThreadCount;
if MaxIter < 0 then
MaxIter := MaxInt;
init := nil;
if ANumInit <= 0 then
begin
SetLength(all, 1);
all[0].StartingPoint := -ANumInit;
end
else
begin
SetLength(all, ANumInit);
InvGoldenRatio := power(NumPoints, 1 / ANumInit);
GRAcc := 1;
for i := 0 to ANumInit - 1 do
begin
all[i].StartingPoint := Round(GRAcc) - 1;
if (i > 0) and (all[i].StartingPoint <= all[i - 1].StartingPoint) then
all[i].StartingPoint := Min(NumPoints - 1, all[i - 1].StartingPoint + 1);
GRAcc := GRAcc * InvGoldenRatio;
end;
end;
for init_no := 0 to High(all) do
begin
SetLength(membship, NumPoints);
SetLength(cl_attr_freq, NumClusters, NumAttrs, ANumModalities);
if init = nil then
centroids := InitFarthestFirst(all[init_no].StartingPoint)
else
centroids := init;
FillDWord(membship[0], NumPoints, $ffffffff);
for j := 0 to NumClusters - 1 do
for i := 0 to NumAttrs - 1 do
FillDWord(cl_attr_freq[j, i, 0], ANumModalities, 0);
if (NumThreads <= 1) and not Assigned(Concurrency) then
begin
for ipoint := 0 to NumPoints - 1 do
membship[ipoint] := GetMinMatchingDissim(centroids, X[ipoint], Length(centroids), dis);
end
else
begin