-
Notifications
You must be signed in to change notification settings - Fork 23
/
klustakwik.cpp
1887 lines (1681 loc) · 60.7 KB
/
klustakwik.cpp
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
// MaskedKlustaKwik2.C
//
// Fast clustering using the CEM algorithm with Masks.
#ifndef VERSION
#define VERSION "0.3.0-nogit"
#endif
// Disable some Visual Studio warnings
#define _CRT_SECURE_NO_WARNINGS
#include "klustakwik.h"
#define _USE_MATH_DEFINES
#include<math.h>
#ifdef _OPENMP
#include<omp.h>
#endif
// GLOBAL VARIABLES
FILE *Distfp;
integer global_numiterations = 0;
scalar iteration_metric2 = (scalar)0;
scalar iteration_metric3 = (scalar)0;
clock_t Clock0;
scalar timesofar;
// Does a memory check (should only be called for first instance of KK)
void KK::MemoryCheck()
{
long long NP = (long long)nPoints;
long long MPC = (long long)MaxPossibleClusters;
long long ND = (long long)nDims;
vector<MemoryUsage> usages;
#ifdef STORE_DATA_AS_INTEGER
usages.push_back(MemoryUsage("Data", "data_int", sizeof(data_int), NP*ND, "nPoints*nDims", 2, 3));
#else
usages.push_back(MemoryUsage("Data", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3));
#endif
#ifdef COMPUTED_BINARY_MASK
if (!UseDistributional)
usages.push_back(MemoryUsage("Masks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3));
#else
usages.push_back(MemoryUsage("Masks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3));
#endif
#ifdef STORE_FLOAT_MASK_AS_CHAR
usages.push_back(MemoryUsage("CharFloatMasks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3));
#else
usages.push_back(MemoryUsage("FloatMasks", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3));
#endif
if (UseDistributional)
usages.push_back(MemoryUsage("Cov", "scalar", sizeof(scalar), MPC*ND*ND, "MaxPossibleClusters*nDims*nDims", 0, 3));
else
usages.push_back(MemoryUsage("Cov", "scalar", sizeof(scalar), MPC*ND*ND, "MaxPossibleClusters*nDims*nDims", 2, 3));
usages.push_back(MemoryUsage("LogP", "scalar", sizeof(scalar), MPC*NP, "MaxPossibleClusters*nPoints", 2, 3));
usages.push_back(MemoryUsage("AllVector2Mean", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3));
#ifndef COMPUTED_CORRECTION_TERM
if (UseDistributional)
usages.push_back(MemoryUsage("CorrectionTerm", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3));
#endif
check_memory_usage(usages, RamLimitGB, nPoints, nDims, MaxPossibleClusters);
}
template<class T>
inline void resize_and_fill_with_zeros(vector<T> &x, integer newsize)
{
if (x.size() == 0)
{
x.resize((uinteger)newsize);
return;
}
if (x.size() > (uinteger)newsize)
{
fill(x.begin(), x.end(), (T)0);
x.resize((uinteger)newsize);
}
else
{
x.resize((uinteger)newsize);
fill(x.begin(), x.end(), (T)0);
}
}
// Sets storage for KK class. Needs to have nDims and nPoints defined
void KK::AllocateArrays() {
nDims2 = nDims*nDims;
NoisePoint = 1; // Ensures that the mixture weight for the noise cluster never gets to zero
// Set sizes for arrays
resize_and_fill_with_zeros(Data, nPoints * nDims);
//SNK
#ifdef COMPUTED_BINARY_MASK
if(!UseDistributional)
resize_and_fill_with_zeros(Masks, nPoints * nDims);
#else
resize_and_fill_with_zeros(Masks, nPoints * nDims);
#endif
#ifdef STORE_FLOAT_MASK_AS_CHAR
resize_and_fill_with_zeros(CharFloatMasks, nPoints * nDims);
#else
resize_and_fill_with_zeros(FloatMasks, nPoints * nDims);
#endif
resize_and_fill_with_zeros(UnMaskDims, nPoints); //SNK Number of unmasked dimensions for each data point when using float masks $\sum m_i$
resize_and_fill_with_zeros(Weight, MaxPossibleClusters);
resize_and_fill_with_zeros(Mean, MaxPossibleClusters*nDims);
if (!UseDistributional)
resize_and_fill_with_zeros(Cov, MaxPossibleClusters*nDims2);
resize_and_fill_with_zeros(LogP, MaxPossibleClusters*nPoints);
resize_and_fill_with_zeros(Class, nPoints);
resize_and_fill_with_zeros(OldClass, nPoints);
resize_and_fill_with_zeros(Class2, nPoints);
resize_and_fill_with_zeros(BestClass, nPoints);
resize_and_fill_with_zeros(ClassAlive, MaxPossibleClusters);
resize_and_fill_with_zeros(AliveIndex, MaxPossibleClusters);
resize_and_fill_with_zeros(ClassPenalty, MaxPossibleClusters);
resize_and_fill_with_zeros(nClassMembers, MaxPossibleClusters);
if(UseDistributional)
{
#ifndef COMPUTED_CORRECTION_TERM
resize_and_fill_with_zeros(CorrectionTerm, nPoints * nDims);
#endif
resize_and_fill_with_zeros(ClusterMask, MaxPossibleClusters*nDims);
}
}
// recompute index of alive clusters (including 0, the noise cluster)
// should be called after anything that changes ClassAlive
void KK::Reindex()
{
integer c;
AliveIndex[0] = 0;
nClustersAlive=1;
for(c=1;c<MaxPossibleClusters;c++)
{
if (ClassAlive[c])
{
AliveIndex[nClustersAlive] = c;
nClustersAlive++;
}
}
}
// Penalty for standard CEM
// Penalty(nAlive) returns the complexity penalty for that many clusters
// bearing in mind that cluster 0 has no free params except p.
scalar KK::Penalty(integer n)
{
integer nParams;
if(n==1)
return 0;
nParams = (nDims*(nDims+1)/2 + nDims + 1)*(n-1); // each has cov, mean, &p
scalar p = penaltyK*(scalar)(nParams) // AIC units (Spurious factor of 2 removed from AIC units on 09.07.13)
+penaltyKLogN*((scalar)nParams*(scalar)log((scalar)nPoints)/2); // BIC units
return p;
}
// Penalties for Masked CEM
void KK::ComputeClassPenalties()
{
if(UseDistributional==0) // This function must only be called in Use Distributional mode
{
// Output("Caught in ComputeClassPenalties");
return;
}
// Output("ComputeClassPenalties: Correct if UseDistributional only");
for(integer c=0; c<MaxPossibleClusters; c++)
ClassPenalty[c] = (scalar)0;
// compute sum of nParams for each
vector<integer> NumberInClass(MaxPossibleClusters);
for(integer p=0; p<nPoints; p++)
{
integer c = Class[p];
NumberInClass[c]++;
// integer n = UnmaskedInd[p+1]-UnmaskedInd[p]; // num unmasked dimensions
scalar n = UnMaskDims[p];
scalar nParams = n*(n+1)/2+n+1;
ClassPenalty[c] += nParams;
}
// compute mean nParams for each cluster
for(integer c=0; c<MaxPossibleClusters; c++)
if(NumberInClass[c]>0)
ClassPenalty[c] /= (scalar)NumberInClass[c];
// compute penalty for each cluster
for(integer c=0; c<MaxPossibleClusters; c++)
{
scalar nParams = ClassPenalty[c];
ClassPenalty[c] = penaltyK*(scalar)(nParams*2)
+penaltyKLogN*((scalar)nParams*(scalar)log((scalar)nPoints)/2);
}
}
// Compute the cluster masks (i.e. the sets of features which are masked/unmasked
// for the whole cluster). Used by M-step and E-step
void KK::ComputeClusterMasks()
{
Reindex();
// Initialise cluster mask to 0
for(integer i=0; i<nDims*MaxPossibleClusters; i++)
ClusterMask[i] = 0;
// Compute cluster mask
for(integer p=0; p<nPoints; p++)
{
integer c = Class[p];
for (integer i = 0; i < nDims; i++)
{
#ifdef STORE_FLOAT_MASK_AS_CHAR
ClusterMask[c*nDims + i] += (scalar)(CharFloatMasks[p*nDims + i]/(scalar)255.0);
#else
ClusterMask[c*nDims + i] += FloatMasks[p*nDims + i];
#endif
}
}
// Compute the set of masked/unmasked features for each cluster
// reset all the subvectors to empty
ClusterUnmaskedFeatures.clear();
ClusterUnmaskedFeatures.resize(MaxPossibleClusters);
ClusterMaskedFeatures.clear();
ClusterMaskedFeatures.resize(MaxPossibleClusters);
// fill them in
for (integer cc = 0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c];
vector<integer> &CurrentMasked = ClusterMaskedFeatures[c];
for (integer i = 0; i < nDims; i++)
{
if (ClusterMask[c*nDims + i]>=PointsForClusterMask)
CurrentUnmasked.push_back(i);
else
CurrentMasked.push_back(i);
}
if (Verbose>=2)
{
Output("Cluster mask: cluster %d unmasked %d iterations %d/%d init type %d.\n",
(int)cc, (int)CurrentUnmasked.size(),
(int)numiterations, (int)global_numiterations, (int)init_type);
}
}
}
// M-step: Calculate mean, cov, and weight for each living class
// also deletes any classes with fewer points than nDim
void KK::MStep()
{
vector<scalar> Vec2Mean(nDims);
// clear arrays
memset((void*)&nClassMembers.front(), 0, MaxPossibleClusters*sizeof(integer));
memset((void*)&Mean.front(), 0, MaxPossibleClusters*nDims*sizeof(scalar));
if (!UseDistributional)
memset((void*)&Cov.front(), 0, MaxPossibleClusters*nDims2*sizeof(scalar));
// NOTE: memset commands above replace the code below:
// for(c=0; c<MaxPossibleClusters; c++) {
// nClassMembers[c] = 0;
// for(i=0; i<nDims; i++) Mean[c*nDims + i] = 0;
// }
if (Debug) { Output("Entering Unmasked Mstep \n");}
// Accumulate total number of points in each class
for (integer p=0; p<nPoints; p++) nClassMembers[Class[p]]++;
// check for any dead classes
if(UseDistributional)
{
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
if (Debug){Output("DistributionalMstep: Class %d contains %d members \n", (int)c, (int)nClassMembers[c]);}
if (c>0 && nClassMembers[c]<1)//nDims)
{
ClassAlive[c]=0;
if (Debug) {Output("UnmaskedMstep_dist: Deleted class %d: no members\n", (int)c);}
}
}
}
else
{
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
if (Debug) {Output("Mstep: Class %d contains %d members \n", (int)c, (int)nClassMembers[c]);}
if (c>0 && nClassMembers[c]<=nDims)
{
ClassAlive[c]=0;
if (Debug) {Output("Deleted class %d: not enough members\n", (int)c);}
}
}
}
Reindex();
// Normalize by total number of points to give class weight
// Also check for dead classes
if(UseDistributional)
{
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
//Output("DistributionalMstep: PriorPoint on weights ");
// add "noise point" to make sure Weight for noise cluster never gets to zero
if(c==0)
{
Weight[c] = ((scalar)nClassMembers[c]+NoisePoint) / (nPoints+NoisePoint+priorPoint*(nClustersAlive-1));
}
else
{
Weight[c] = ((scalar)nClassMembers[c]+priorPoint) / (nPoints+NoisePoint+priorPoint*(nClustersAlive-1));
}
}
}
else // For Original KlustaKwik, Classical EM
{
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
// add "noise point" to make sure Weight for noise cluster never gets to zero
if(c==0)
{
Weight[c] = ((scalar)nClassMembers[c]+NoisePoint) / (nPoints+NoisePoint);
}
else
{
Weight[c] = ((scalar)nClassMembers[c]) / (nPoints+NoisePoint);
}
}
}
Reindex();
// Accumulate sums for mean calculation
for (integer p=0; p<nPoints; p++)
{
integer c = Class[p];
for(integer i=0; i<nDims; i++)
{
Mean[c*nDims + i] += GetData(p, i);
}
}
// and normalize
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
for (integer i=0; i<nDims; i++) Mean[c*nDims + i] /= nClassMembers[c];
}
// Covariance matrix is quite big, and won't fit in the L1d cache
// (which is 16 or 32 k usually, corresponding to a matrix of about 64x64 or 90x90)
// so can probably improve performance by doing some sort of blocking here
// Accumulate sums for covariance calculation
// for (p=0; p<nPoints; p++)
// {
// c = Class[p];
// // calculate distance from mean
// for(i=0; i<nDims; i++)
// Vec2Mean[i] = Data[p*nDims + i] - Mean[c*nDims + i];
// for(i=0; i<nDims; i++)
// for(j=i; j<nDims; j++)
// Cov[c*nDims2 + i*nDims + j] += Vec2Mean[i] * Vec2Mean[j];
// }
if ((integer)AllVector2Mean.size() < nPoints*nDims)
{
//mem.add((nPoints*nDims-AllVector2Mean.size())*sizeof(scalar));
AllVector2Mean.resize(nPoints*nDims);
}
vector< vector<integer> > PointsInClass(MaxPossibleClusters);
for(integer p=0; p<nPoints; p++)
{
integer c = Class[p];
PointsInClass[c].push_back(p);
for (integer i = 0; i < nDims; i++)
AllVector2Mean[p*nDims + i] = GetData(p, i) - Mean[c*nDims + i];
}
if (UseDistributional)
{
// Compute the cluster masks, used below to optimise the computation
ComputeClusterMasks();
// Empty the dynamic covariance matrices (we will fill it up as we go)
DynamicCov.clear();
for (integer cc = 0; cc < nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c];
vector<integer> &CurrentMasked = ClusterMaskedFeatures[c];
DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked));
}
#pragma omp parallel for schedule(dynamic)
for (integer cc = 0; cc<nClustersAlive; cc++)
{
const integer c = AliveIndex[cc];
const vector<integer> &PointsInThisClass = PointsInClass[c];
const integer NumPointsInThisClass = PointsInThisClass.size();
const vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c];
//const vector<integer> &CurrentMasked = ClusterMaskedFeatures[c];
BlockPlusDiagonalMatrix &CurrentCov = DynamicCov[cc];
if (CurrentUnmasked.size() > 0)
{
const integer npoints = (integer)PointsInThisClass.size();
const integer nunmasked = (integer)CurrentUnmasked.size();
if (npoints > 0 && nunmasked > 0)
{
const integer * __restrict pitc = &(PointsInThisClass[0]);
const integer * __restrict cu = &(CurrentUnmasked[0]);
for (integer q = 0; q < npoints; q++)
{
const integer p = pitc[q];
const scalar * __restrict av2mp = &(AllVector2Mean[p*nDims]);
for (integer ii = 0; ii < nunmasked; ii++)
{
const integer i = cu[ii];
const scalar av2mp_i = av2mp[i];
scalar * __restrict row = &(CurrentCov.Block[ii*nunmasked]);
for (integer jj = 0; jj < nunmasked; jj++)
{
const integer j = cu[jj];
//Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
row[jj] += av2mp_i * av2mp[j];
}
}
}
}
}
//
for (integer ii = 0; ii<CurrentCov.NumUnmasked; ii++)
{
const integer i = (*CurrentCov.Unmasked)[ii];
scalar ccf = 0.0; // class correction factor
for (integer q = 0; q<NumPointsInThisClass; q++)
{
const integer p = PointsInThisClass[q];
#ifdef COMPUTED_CORRECTION_TERM
ccf += GetCorrectionTerm(p, i);
#else
ccf += CorrectionTerm[p*nDims + i];
#endif
}
CurrentCov.Block[ii*CurrentCov.NumUnmasked + ii] += ccf;
}
for (integer ii = 0; ii<CurrentCov.NumMasked; ii++)
{
const integer i = (*CurrentCov.Masked)[ii];
scalar ccf = 0.0; // class correction factor
for (integer q = 0; q<NumPointsInThisClass; q++)
{
const integer p = PointsInThisClass[q];
#ifdef COMPUTED_CORRECTION_TERM
ccf += GetCorrectionTerm(p, i);
#else
ccf += CorrectionTerm[p*nDims + i];
#endif
}
CurrentCov.Diagonal[ii] += ccf;
}
//
for (integer ii = 0; ii < CurrentCov.NumUnmasked; ii++)
CurrentCov.Block[ii*CurrentCov.NumUnmasked + ii] += priorPoint*NoiseVariance[(*CurrentCov.Unmasked)[ii]];
for (integer ii = 0; ii < CurrentCov.NumMasked; ii++)
CurrentCov.Diagonal[ii] += priorPoint*NoiseVariance[(*CurrentCov.Masked)[ii]];
//
const scalar factor = 1.0 / (nClassMembers[c] + priorPoint - 1);
for (integer i = 0; i < (integer)CurrentCov.Block.size(); i++)
CurrentCov.Block[i] *= factor;
for (integer i = 0; i < (integer)CurrentCov.Diagonal.size(); i++)
CurrentCov.Diagonal[i] *= factor;
}
}
if (UseDistributional)
{
// // Compute the cluster masks, used below to optimise the computation
// ComputeClusterMasks();
// // Empty the dynamic covariance matrices (we will fill it up as we go)
// DynamicCov.clear();
//
// for (cc = 0; cc < nClustersAlive; cc++)
// {
// c = AliveIndex[cc];
// vector<integer> &PointsInThisClass = PointsInClass[c];
// vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c];
// vector<integer> &CurrentMasked = ClusterMaskedFeatures[c];
// DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked));
// }
//
//#pragma omp parallel for
// for (integer cc = 0; cc<nClustersAlive; cc++)
// {
// integer c = AliveIndex[cc];
// vector<integer> &PointsInThisClass = PointsInClass[c];
// vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c];
// vector<integer> &CurrentMasked = ClusterMaskedFeatures[c];
// //DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked));
// BlockPlusDiagonalMatrix &CurrentCov = DynamicCov[cc];
// if (CurrentUnmasked.size() == 0)
// continue;
//
// //// Correct version for dynamic cov matrix
// //for (integer q = 0; q < (integer)PointsInThisClass.size(); q++)
// //{
// // p = PointsInThisClass[q];
// // for (integer ii = 0; ii < (integer)CurrentUnmasked.size(); ii++)
// // {
// // i = CurrentUnmasked[ii];
// // for (integer jj = 0; jj < (integer)CurrentUnmasked.size(); jj++)
// // {
// // j = CurrentUnmasked[jj];
// // //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
// // CurrentCov.Block[ii*CurrentCov.NumUnmasked + jj] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
// // }
// // }
// //}
// // Fast version for dynamic cov matrix
// const integer npoints = (integer)PointsInThisClass.size();
// const integer nunmasked = (integer)CurrentUnmasked.size();
// if (npoints > 0 && nunmasked > 0)
// {
// const integer * __restrict pitc = &(PointsInThisClass[0]);
// const integer * __restrict cu = &(CurrentUnmasked[0]);
// for (integer q = 0; q < npoints; q++)
// {
// const integer p = pitc[q];
// const scalar * __restrict av2mp = &(AllVector2Mean[p*nDims]);
// for (integer ii = 0; ii < nunmasked; ii++)
// {
// const integer i = cu[ii];
// const scalar av2mp_i = av2mp[i];
// scalar * __restrict row = &(CurrentCov.Block[ii*nunmasked]);
// for (integer jj = 0; jj < nunmasked; jj++)
// {
// const integer j = cu[jj];
// //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
// row[jj] += av2mp_i * av2mp[j];
// }
// }
// }
// }
//
// // Correct version
// //for (integer q = 0; q < (integer)PointsInThisClass.size(); q++)
// //{
// // p = PointsInThisClass[q];
// // for (integer ii = 0; ii < (integer)CurrentUnmasked.size(); ii++)
// // {
// // i = CurrentUnmasked[ii];
// // for (integer jj = 0; jj < (integer)CurrentUnmasked.size(); jj++)
// // {
// // j = CurrentUnmasked[jj];
// // Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
// // }
// // }
// //}
// // Faster version (equivalent)
// // Doesn't make any use of cache structure, but no need to upgrade now because
// // we will move to a sparse block matrix structure that will make this more
// // natural
// /*
// const integer * __restrict cu = &(CurrentUnmasked[0]);
// const integer ncu = (integer)CurrentUnmasked.size();
// scalar * __restrict cov_c = &(Cov[c*nDims2]);
// const integer * __restrict pitc = &(PointsInThisClass[0]);
// const integer npitc = (integer)PointsInThisClass.size();
// const scalar * __restrict av2m = &(AllVector2Mean[0]);
// for (integer q = 0; q < npitc; q++)
// {
// const integer p = pitc[q];
// const scalar * __restrict av2m_p = av2m + p*nDims;
// for (integer ii = 0; ii < ncu; ii++)
// {
// const integer i = cu[ii];
// const scalar av2m_p_i = av2m_p[i];
// scalar * __restrict cov_c_i = cov_c + i*nDims;
// for (integer jj = 0; jj < ncu; jj++)
// {
// const integer j = cu[jj];
// cov_c_i[j] += av2m_p_i*av2m_p[j];
// //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j];
// }
// }
// }
// */
// }
}
else
{
// I think this code gives wrong results (but only slightly) (DFMG: 2014/10/13)
for (integer c = 0; c < MaxPossibleClusters; c++)
{
vector<integer> &PointsInThisClass = PointsInClass[c];
SafeArray<scalar> safeCov(Cov, c*nDims2, "safeCovMStep");
for (integer iblock = 0; iblock < nDims; iblock += COVARIANCE_BLOCKSIZE)
{
for (integer jblock = iblock; jblock < nDims; jblock += COVARIANCE_BLOCKSIZE)
{
for (integer q = 0; q < (integer)PointsInThisClass.size(); q++)
{
integer p = PointsInThisClass[q];
scalar *cv2m = &AllVector2Mean[p*nDims];
for (integer i = iblock; i < MIN(nDims, iblock + COVARIANCE_BLOCKSIZE); i++)
{
scalar cv2mi = cv2m[i];
integer jstart;
if (jblock != iblock)
jstart = jblock;
else
jstart = i;
scalar *covptr = &safeCov[i*nDims + jstart];
scalar *cv2mjptr = &cv2m[jstart];
//scalar *cv2mjend = cv2m+MIN(nDims, jblock+COVARIANCE_BLOCKSIZE);
//for(j=jstart; j<MIN(nDims, jblock+COVARIANCE_BLOCKSIZE); j++)
//for(; cv2mjptr!=cv2mjend;)
for (integer j = MIN(nDims, jblock + COVARIANCE_BLOCKSIZE) - jstart; j; j--)
*covptr++ += cv2mi*(*cv2mjptr++);
}
}
}
}
}
}
// and normalize
if(!UseDistributional)
{ //For original KlustaKwik classical EM
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
for(integer i=0; i<nDims; i++)
for(integer j=i; j<nDims; j++)
Cov[c*nDims2 + i*nDims + j] /= (nClassMembers[c]-1);
}
}
// That's it!
// Diagnostics
if (Debug)
{
for (integer cc=0; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
Output("Class %d - Weight %.2g\n", (int)c, Weight[c]);
Output("Mean: ");
MatPrint(stdout, &Mean.front() + c*nDims, 1, nDims);
if (!UseDistributional)
{
Output("\nCov:\n");
MatPrint(stdout, &Cov.front() + c*nDims2, nDims, nDims);
}
Output("\n");
}
}
}
// E-step. Calculate Log Probs for each point to belong to each living class
// will delete a class if covariance matrix is singular
// also counts number of living classes
void KK::EStep()
{
integer nSkipped;
scalar LogRootDet; // log of square root of covariance determinant
scalar correction_factor = (scalar)1; // for partial correction in distributional step
//scalar InverseClusterNorm;
vector<scalar> Chol(nDims2); // to store choleski decomposition
vector<scalar> Vec2Mean(nDims); // stores data point minus class mean
vector<scalar> Root(nDims); // stores result of Chol*Root = Vec
vector<scalar> InvCovDiag;
if(UseDistributional)
InvCovDiag.resize(nDims);
SafeArray<scalar> safeChol(Chol, "safeChol");
SafeArray<scalar> safeVec2Mean(Vec2Mean, "safeVec2Mean");
SafeArray<scalar> safeRoot(Root, "safeRoot");
SafeArray<scalar> safeInvCovDiag(InvCovDiag, "safeInvCovDiag");
nSkipped = 0;
if (Debug) {Output("Entering Unmasked Estep \n");}
// start with cluster 0 - uniform distribution over space
// because we have normalized all dims to 0...1, density will be 1.
vector<integer> NumberInClass(MaxPossibleClusters); // For finding number of points in each class
for (integer p=0; p<nPoints; p++)
{
LogP[p*MaxPossibleClusters + 0] = (float)-log(Weight[0]);
integer ccc = Class[p];
NumberInClass[ccc]++;
}
BlockPlusDiagonalMatrix *CurrentCov;
BlockPlusDiagonalMatrix *CholBPD = NULL;
for (integer cc = 1; cc<nClustersAlive; cc++)
{
integer c = AliveIndex[cc];
// calculate cholesky decomposition for class c
integer chol_return;
if (UseDistributional)
{
CurrentCov = &(DynamicCov[cc]);
if (CholBPD)
{
delete CholBPD;
CholBPD = NULL;
}
CholBPD = new BlockPlusDiagonalMatrix(*(CurrentCov->Masked), *(CurrentCov->Unmasked));
chol_return = BPDCholesky(*CurrentCov, *CholBPD);
//if (MinMaskOverlap>0)
//{
// // compute the norm of the cluster mask (used for skipping points)
// const scalar * __restrict cm = &(ClusterMask[c*nDims]);
// scalar ClusterNorm = 0.0;
// for (i = 0; i < nDims; i++)
// {
// scalar m = cm[i];
// //if (m > ClusterNorm)
// // ClusterNorm = m;
// ClusterNorm += m*m;
// }
// //InverseClusterNorm = 1.0 / ClusterNorm;
// InverseClusterNorm = 1.0 / sqrt(ClusterNorm);
// //InverseClusterNorm = sqrt((scalar)nDims) / sqrt(ClusterNorm);
//}
}
else
{
SafeArray<scalar> safeCov(Cov, c*nDims2, "safeCov");
chol_return = Cholesky(safeCov, safeChol, nDims);
}
if(chol_return)
{
// If Cholesky returns 1, it means the matrix is not positive definite.
// So kill the class.
// Cholesky is defined in linalg.cpp
Output("Unmasked E-step: Deleting class %d (%d points): covariance matrix is singular \n", (int)c, (int)NumberInClass[c]);
ClassAlive[c] = 0;
continue;
}
// LogRootDet is given by log of product of diagonal elements
if (UseDistributional)
{
LogRootDet = 0;
for (integer ii = 0; ii < CholBPD->NumUnmasked; ii++)
LogRootDet += log(CholBPD->Block[ii*CholBPD->NumUnmasked + ii]);
for (integer ii = 0; ii < CholBPD->NumMasked; ii++)
LogRootDet += log(CholBPD->Diagonal[ii]);
}
else
{
LogRootDet = 0;
for (integer i = 0; i < nDims; i++)
LogRootDet += log(Chol[i*nDims + i]);
}
// if distributional E step, compute diagonal of inverse of cov matrix
if(UseDistributional)
{
vector<scalar> BasisVector(nDims);
SafeArray<scalar> safeBasisVector(BasisVector, "BasisVector");
for(integer i=0; i<nDims; i++)
safeBasisVector[i] = (scalar)0;
for(integer i=0; i<nDims; i++)
{
safeBasisVector[i] = (scalar)1;
// calculate Root vector - by Chol*Root = BasisVector
BPDTriSolve(*CholBPD, safeBasisVector, safeRoot);
// add half of Root vector squared to log p
scalar Sii = (scalar)0;
for(integer j=0; j<nDims; j++)
Sii += Root[j]*Root[j];
safeInvCovDiag[i] = Sii;
safeBasisVector[i] = (scalar)0;
}
}
#pragma omp parallel for schedule(dynamic) firstprivate(Vec2Mean, Root) default(shared)
for(integer p=0; p<nPoints; p++)
{
// to save time -- only recalculate if the last one was close
if (
!FullStep
&& (Class[p] == OldClass[p])
&& (LogP[p*MaxPossibleClusters+c] - LogP[p*MaxPossibleClusters+Class[p]] > DistThresh)
)
{
#pragma omp atomic
nSkipped++;
continue;
}
// to save time, skip points with mask overlap below threshold
if (MinMaskOverlap > 0)
{
// compute dot product of point mask with cluster mask
#ifdef STORE_FLOAT_MASK_AS_CHAR
const unsigned char * __restrict CharPointMask = &(CharFloatMasks[p*nDims]);
#else
const scalar * __restrict PointMask = &(FloatMasks[p*nDims]);
#endif
//const scalar * __restrict cm = &(ClusterMask[c*nDims]);
scalar dotprod = 0.0;
//// InverseClusterNorm is computed above, uncomment it if you uncomment any of this
//for (i = 0; i < nDims; i++)
//{
// dotprod += cm[i] * PointMask[i] * InverseClusterNorm;
// if (dotprod >= MinMaskOverlap)
// break;
//}
const integer NumUnmasked = CurrentCov->NumUnmasked;
if (NumUnmasked)
{
const integer * __restrict cu = &((*(CurrentCov->Unmasked))[0]);
for (integer ii = 0; ii < NumUnmasked; ii++)
{
const integer i = cu[ii];
#ifdef STORE_FLOAT_MASK_AS_CHAR
dotprod += CharPointMask[i]/(scalar)255.0;
#else
dotprod += PointMask[i];
#endif
if (dotprod >= MinMaskOverlap)
break;
}
}
//dotprod *= InverseClusterNorm;
if (dotprod < MinMaskOverlap)
{
#pragma omp atomic
nSkipped++;
continue;
}
}
SafeArray<scalar> safeVec2Mean(Vec2Mean, "safeVec2Mean");
SafeArray<scalar> safeRoot(Root, "safeRoot");
// Compute Mahalanobis distance
scalar Mahal = 0;
// calculate data minus class mean
//for (i = 0; i<nDims; i++)
// Vec2Mean[i] = Data[p*nDims + i] - Mean[c*nDims + i];
restricted_data_pointer Data_p = &(Data[p*nDims]);
scalar * __restrict Mean_c = &(Mean[c*nDims]);
scalar * __restrict v2m = &(Vec2Mean[0]);
for (integer i = 0; i < nDims; i++)
v2m[i] = get_data_from_pointer(Data_p, i) - Mean_c[i];
// calculate Root vector - by Chol*Root = Vec2Mean
if (UseDistributional)
BPDTriSolve(*CholBPD, safeVec2Mean, safeRoot);
else
TriSolve(safeChol, safeVec2Mean, safeRoot, nDims);
// add half of Root vector squared to log p
for(integer i=0; i<nDims; i++)
Mahal += Root[i]*Root[i];
// if distributional E step, add correction term
if (UseDistributional)
{
const scalar * __restrict icd = &(InvCovDiag[0]);
scalar subMahal = 0.0;
#ifdef COMPUTED_CORRECTION_TERM
#ifdef STORE_FLOAT_MASK_AS_CHAR
const unsigned char * __restrict ptr_char_w = &(CharFloatMasks[p*nDims]);
#else
const scalar * __restrict ptr_w = &(FloatMasks[p*nDims]);
#endif
const scalar * __restrict ptr_nu = &(NoiseMean[0]);
const scalar * __restrict ptr_sigma2 = &(NoiseVariance[0]);
restricted_data_pointer ptr_y = &(Data[p*nDims]);
for (integer i = 0; i < nDims; i++)
{
#ifdef STORE_FLOAT_MASK_AS_CHAR
const scalar w = ptr_char_w[i]/(scalar)255.0;
#else
const scalar w = ptr_w[i];
#endif
const scalar nu = ptr_nu[i];
const scalar sigma2 = ptr_sigma2[i];
const scalar y = get_data_from_pointer(ptr_y, i);
scalar eta;
if(w==(scalar)0.0)
{
const scalar z = nu*nu+sigma2;
eta = z-y*y;
} else
{
const scalar x = (y-(1-w)*nu)/w;
const scalar z = w*x*x+(1-w)*(nu*nu+sigma2);
eta = z-y*y;
}
subMahal += eta * icd[i];
}
#else
const scalar * __restrict ctp = &(CorrectionTerm[p*nDims]);
for (integer i = 0; i < nDims; i++)
subMahal += ctp[i] * icd[i];
#endif
Mahal += subMahal*correction_factor;
}
// Score is given by Mahal/2 + log RootDet - log weight
LogP[p*MaxPossibleClusters + c] = Mahal/2
+ LogRootDet
- log(Weight[c])
+ (0.5*log(2 * M_PI))*nDims;
} // for(p=0; p<nPoints; p++)
} // for(cc=1; cc<nClustersAlive; cc++)
if (CholBPD)
delete CholBPD;
}
// Choose best class for each point (and second best) out of those living
void KK::CStep(bool allow_assign_to_noise)
{
integer p, c, cc, TopClass, SecondClass;
integer ccstart = 0;
if(!allow_assign_to_noise)
ccstart = 1;
scalar ThisScore, BestScore, SecondScore;
for (p=0; p<nPoints; p++)
{
OldClass[p] = Class[p];
BestScore = HugeScore;
SecondScore = HugeScore;
TopClass = SecondClass = 0;
for (cc=ccstart; cc<nClustersAlive; cc++)
{
c = AliveIndex[cc];
ThisScore = LogP[p*MaxPossibleClusters + c];
if (ThisScore < BestScore)
{
SecondClass = TopClass;
TopClass = c;
SecondScore = BestScore;
BestScore = ThisScore;
}
else if (ThisScore < SecondScore)
{
SecondClass = c;
SecondScore = ThisScore;
}
}
Class[p] = TopClass;
Class2[p] = SecondClass;
}
}
// Sometimes deleting a cluster will improve the score, when you take into account
// the BIC. This function sees if this is the case. It will not delete more than
// one cluster at a time.
void KK::ConsiderDeletion()
{
integer c, p, CandidateClass=0;
scalar Loss, DeltaPen;
vector<scalar> DeletionLoss(MaxPossibleClusters); // the increase in log P by deleting the cluster
if (Debug)
Output(" Entering ConsiderDeletion: ");
for(c=1; c<MaxPossibleClusters; c++)