-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
clustering_functions.R
2524 lines (1976 loc) · 118 KB
/
clustering_functions.R
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
utils::globalVariables(c("x", "y")) # to avoid the following NOTE when package checking takes place --> plot_2d: no visible binding for global variables 'x', 'y'
#' tryCatch function to prevent armadillo errors
#'
#' @keywords internal
tryCatch_GMM <- function(data,
gaussian_comps,
dist_mode,
seed_mode,
km_iter,
em_iter,
verbose,
var_floor,
seed,
full_covariance_matrices) {
Error = tryCatch(GMM_arma(data,
gaussian_comps,
dist_mode,
seed_mode,
km_iter,
em_iter,
verbose,
var_floor,
seed,
full_covariance_matrices),
error = function(e) e)
if (inherits(Error, "error")) {
return(list(Error = Error, warning = "probable causes of error: 'warning: gmm_diag::learn(): number of vectors is less than number of gaussians' OR 'warning: gmm_diag::learn(): EM algorithm failed'"))}
else {
return(Error)
}
}
#' Gaussian Mixture Model clustering
#'
#' @param data matrix or data frame
#' @param gaussian_comps the number of gaussian mixture components
#' @param dist_mode the distance used during the seeding of initial means and k-means clustering. One of, \emph{eucl_dist}, \emph{maha_dist}.
#' @param seed_mode how the initial means are seeded prior to running k-means and/or EM algorithms. One of, \emph{static_subset}, \emph{random_subset}, \emph{static_spread}, \emph{random_spread}.
#' @param km_iter the number of iterations of the k-means algorithm
#' @param em_iter the number of iterations of the EM algorithm
#' @param verbose either TRUE or FALSE; enable or disable printing of progress during the k-means and EM algorithms
#' @param var_floor the variance floor (smallest allowed value) for the diagonal covariances
#' @param seed integer value for random number generator (RNG)
#' @param full_covariance_matrices a boolean. If FALSE "diagonal" covariance matrices (i.e. in each covariance matrix, all entries outside the main diagonal are assumed to be zero) otherwise "full" covariance matrices will be returned. Be aware in case of "full" covariance matrices a cube (3-dimensional) rather than a matrix for the output "covariance_matrices" value will be returned.
#' @return a list consisting of the centroids, covariance matrix ( where each row of the matrix represents a diagonal covariance matrix), weights and the log-likelihoods for each gaussian component. In case of Error it returns the error message and the possible causes.
#' @details
#' This function is an R implementation of the 'gmm_diag' class of the Armadillo library. The only exception is that user defined parameter settings are not supported, such as seed_mode = 'keep_existing'.
#' For probabilistic applications, better model parameters are typically learned with dist_mode set to maha_dist.
#' For vector quantisation applications, model parameters should be learned with dist_mode set to eucl_dist, and the number of EM iterations set to zero.
#' In general, a sufficient number of k-means and EM iterations is typically about 10.
#' The number of training samples should be much larger than the number of Gaussians.
#' Seeding the initial means with static_spread and random_spread can be much more time consuming than with static_subset and random_subset.
#' The k-means and EM algorithms will run faster on multi-core machines when OpenMP is enabled in your compiler (eg. -fopenmp in GCC)
#' @references
#' http://arma.sourceforge.net/docs.html
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = as.matrix(dietary_survey_IBS[, -ncol(dietary_survey_IBS)])
#'
#' dat = center_scale(dat)
#'
#' gmm = GMM(dat, 2, "maha_dist", "random_subset", 10, 10)
GMM = function(data,
gaussian_comps = 1,
dist_mode = 'eucl_dist',
seed_mode = 'random_subset',
km_iter = 10,
em_iter = 5,
verbose = FALSE,
var_floor = 1e-10,
seed = 1,
full_covariance_matrices = FALSE) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (gaussian_comps < 1) stop('the number of gaussian mixture components should be greater than 0')
if (!dist_mode %in% c('eucl_dist', 'maha_dist')) stop("available distance modes are 'eucl_dist' and 'maha_dist'")
if (!seed_mode %in% c('static_subset','random_subset','static_spread','random_spread')) stop("available seed modes are 'static_subset','random_subset','static_spread' and 'random_spread'")
if (km_iter < 0 ) stop('the km_iter parameter can not be negative')
if (em_iter < 0 ) stop('the em_iter parameter can not be negative')
if (!is.logical(verbose)) stop('the verbose parameter should be either TRUE or FALSE')
if (var_floor < 0 ) stop('the var_floor parameter can not be negative')
if (!inherits(full_covariance_matrices, 'logical')) stop('The full_covariance_matrices parameter must be a boolean!')
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
res = tryCatch_GMM(data,
gaussian_comps,
dist_mode,
seed_mode,
km_iter,
em_iter,
verbose,
var_floor,
seed,
full_covariance_matrices)
if ('Error' %in% names(res)) {
return(res)
} else {
structure(list(call = match.call(),
centroids = res$centroids,
covariance_matrices = res$covariance_matrices,
weights = as.vector(res$weights),
Log_likelihood = res$Log_likelihood_raw),
class = c("GMMCluster", 'Gaussian Mixture Models'))
}
}
#' Prediction function for a Gaussian Mixture Model object
#'
#' @param data matrix or data frame
#' @param CENTROIDS matrix or data frame containing the centroids (means), stored as row vectors
#' @param COVARIANCE matrix or data frame containing the diagonal covariance matrices, stored as row vectors
#' @param WEIGHTS vector containing the weights
#' @return a list consisting of the log-likelihoods, cluster probabilities and cluster labels.
#' @author Lampros Mouselimis
#' @details
#' This function takes the centroids, covariance matrix and weights from a trained model and returns the log-likelihoods, cluster probabilities and cluster labels for new data.
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = as.matrix(dietary_survey_IBS[, -ncol(dietary_survey_IBS)])
#'
#' dat = center_scale(dat)
#'
#' gmm = GMM(dat, 2, "maha_dist", "random_subset", 10, 10)
#'
#' # pr = predict_GMM(dat, gmm$centroids, gmm$covariance_matrices, gmm$weights)
#'
predict_GMM = function(data, CENTROIDS, COVARIANCE, WEIGHTS) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if ('data.frame' %in% class(CENTROIDS)) CENTROIDS = as.matrix(CENTROIDS)
if (!inherits(CENTROIDS, 'matrix')) stop('CENTROIDS should be either a matrix or a data frame')
if ('data.frame' %in% class(COVARIANCE)) COVARIANCE = as.matrix(COVARIANCE)
if (!inherits(COVARIANCE, 'matrix')) stop('COVARIANCE should be either a matrix or a data frame')
if (ncol(data) != ncol(CENTROIDS) || ncol(data) != ncol(COVARIANCE) || length(WEIGHTS) != nrow(CENTROIDS) || length(WEIGHTS) != nrow(COVARIANCE))
stop('the number of columns of the data, CENTROIDS and COVARIANCE should match and the number of rows of the CENTROIDS AND COVARIANCE should be equal to the length of the WEIGHTS vector')
if (!inherits(WEIGHTS, 'numeric') || !is.vector(WEIGHTS))
stop('WEIGHTS should be a numeric vector')
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
res = predict_MGausDPDF(data, CENTROIDS, COVARIANCE, WEIGHTS, eps = 1.0e-8)
# I've added 1 to the output cluster labels to account for the difference in indexing between R and C++
list(log_likelihood = res$Log_likelihood_raw,
cluster_proba = res$cluster_proba,
cluster_labels = as.vector(res$cluster_labels) + 1)
}
#' @rdname predict_GMM
#' @param object,newdata,... arguments for the `predict` generic
#' @export
predict.GMMCluster <- function(object, newdata, ...) {
predict_GMM(newdata, object$centroids, object$covariance_matrices, object$weights)$cluster_labels
}
#' @export
print.GMMCluster <- function(x, ...) {
cat("GMM Cluster\n",
"Call:", deparse(x$call), "\n",
"Data cols:", ncol(x$centroids), "\n",
"Centroids:", nrow(x$centroids), "\n")
}
#' tryCatch function to prevent armadillo errors in GMM_arma_AIC_BIC
#'
#' @keywords internal
tryCatch_optimal_clust_GMM <- function(data, max_clusters, dist_mode, seed_mode, km_iter, em_iter, verbose, var_floor, criterion, seed) {
Error = tryCatch(GMM_arma_AIC_BIC(data, max_clusters, dist_mode, seed_mode, km_iter, em_iter, verbose, var_floor, criterion, seed),
error = function(e) e)
if (inherits(Error, "error")) {
return(list(Error = Error, warning = "probable causes of error: 'warning: gmm_diag::learn(): number of vectors is less than number of gaussians' OR 'warning: gmm_diag::learn(): EM algorithm failed'"))}
else {
return(Error)
}
}
#' Optimal number of Clusters for the gaussian mixture models
#'
#' @param data matrix or data frame
#' @param max_clusters either a numeric value, a contiguous or non-continguous numeric vector specifying the cluster search space
#' @param criterion one of 'AIC' or 'BIC'
#' @param dist_mode the distance used during the seeding of initial means and k-means clustering. One of, \emph{eucl_dist}, \emph{maha_dist}.
#' @param seed_mode how the initial means are seeded prior to running k-means and/or EM algorithms. One of, \emph{static_subset}, \emph{random_subset}, \emph{static_spread}, \emph{random_spread}.
#' @param km_iter the number of iterations of the k-means algorithm
#' @param em_iter the number of iterations of the EM algorithm
#' @param verbose either TRUE or FALSE; enable or disable printing of progress during the k-means and EM algorithms
#' @param var_floor the variance floor (smallest allowed value) for the diagonal covariances
#' @param plot_data either TRUE or FALSE indicating whether the results of the function should be plotted
#' @param seed integer value for random number generator (RNG)
#' @return a vector with either the AIC or BIC for each iteration. In case of Error it returns the error message and the possible causes.
#' @author Lampros Mouselimis
#' @details
#' \strong{AIC} : the Akaike information criterion
#'
#' \strong{BIC} : the Bayesian information criterion
#'
#' In case that the \emph{max_clusters} parameter is a contiguous or non-contiguous vector then plotting is disabled. Therefore, plotting is enabled only if the \emph{max_clusters} parameter is of length 1.
#'
#' @importFrom grDevices dev.cur
#' @importFrom grDevices dev.off
#' @importFrom graphics plot
#' @importFrom graphics axis
#' @importFrom graphics abline
#' @importFrom graphics text
#'
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#'
#' dat = center_scale(dat)
#'
#' opt_gmm = Optimal_Clusters_GMM(dat, 10, criterion = "AIC", plot_data = FALSE)
#'
#'
#' #----------------------------
#' # non-contiguous search space
#' #----------------------------
#'
#' search_space = c(2,5)
#'
#' opt_gmm = Optimal_Clusters_GMM(dat, search_space, criterion = "AIC", plot_data = FALSE)
#'
Optimal_Clusters_GMM = function(data,
max_clusters,
criterion = "AIC",
dist_mode = 'eucl_dist',
seed_mode = 'random_subset',
km_iter = 10,
em_iter = 5,
verbose = FALSE,
var_floor = 1e-10,
plot_data = TRUE,
seed = 1) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (!inherits(max_clusters, c('numeric', 'integer'))) stop('max_clusters should be a numeric or integer vector')
if (length(max_clusters) == 1) {
if (plot_data && max_clusters < 2) stop('if plot_data is TRUE the max_clusters parameter should be at least 2')
}
if (!criterion %in% c("AIC", "BIC")) stop("supported criteria are 'AIC' or 'BIC'")
if (!dist_mode %in% c('eucl_dist', 'maha_dist')) stop("available distance modes are 'eucl_dist' and 'maha_dist'")
if (!seed_mode %in% c('static_subset','random_subset','static_spread','random_spread'))
stop("available seed modes are 'static_subset','random_subset','static_spread' and 'random_spread'")
if (km_iter < 0 ) stop('the km_iter parameter can not be negative')
if (em_iter < 0 ) stop('the em_iter parameter can not be negative')
if (!is.logical(verbose)) stop('the verbose parameter should be either TRUE or FALSE')
if (var_floor < 0 ) stop('the var_floor parameter can not be negative')
if (length(max_clusters) != 1) {
plot_data = FALSE # set "plot_data" to FALSE if the "max_clusters" parameter is not of length 1
if (nrow(data) < max(max_clusters) && verbose) {
warning("the number of rows of the data should be larger than the maximum value of 'max_clusters'", call. = F)
cat(" ", '\n')
}
}
else {
if (nrow(data) < max_clusters && verbose) {
warning("the number of rows of the data should be larger than 'max_clusters'", call. = F)
cat(" ", '\n')
}
}
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
if (length(max_clusters) == 1) {
pass_vector = 1:max_clusters}
else {
pass_vector = max_clusters
}
if (0 %in% pass_vector) {
stop("The 'max_clusters' vector can not include a 0 value !", call. = F)
}
gmm = tryCatch_optimal_clust_GMM(data, pass_vector, dist_mode, seed_mode, km_iter, em_iter, verbose, var_floor, criterion, seed)
if ('Error' %in% names(gmm)) {
return(gmm)
}
else {
if (plot_data) {
if (grDevices::dev.cur() != 1) {
grDevices::dev.off() # reset par()
}
vec_out = as.vector(gmm)
tmp_VAL = as.vector(stats::na.omit(vec_out))
if (length(which(is.na(vec_out))) > 0) {
x_dis = (1:length(vec_out))[-which(is.na(vec_out))]
y_dis = vec_out[-which(is.na(vec_out))]
}
else {
x_dis = 1:length(vec_out)
y_dis = vec_out
}
y_MAX = max(tmp_VAL)
graphics::plot(x = x_dis, y = y_dis, type = 'l', xlab = 'clusters', ylab = criterion, col = 'blue', lty = 3, axes = FALSE)
graphics::axis(1, at = seq(1, length(vec_out) , by = 1))
graphics::axis(2, at = seq(round(min(tmp_VAL) - round(summary(y_MAX)[['Max.']]) / 10), y_MAX + round(summary(y_MAX)[['Max.']]) / 10, by = round((summary(tmp_VAL)['Max.'] - summary(tmp_VAL)['Min.']) / 5)), las = 1, cex.axis = 0.8)
graphics::abline(h = seq(round(min(tmp_VAL) - round(summary(y_MAX)[['Max.']]) / 10), y_MAX + round(summary(y_MAX)[['Max.']]) / 10, by = round((summary(tmp_VAL)['Max.'] - summary(tmp_VAL)['Min.']) / 5)), v = seq(1, length(vec_out) , by = 1), col = "gray", lty = 3)
graphics::text(x = 1:length(vec_out), y = vec_out, labels = round(vec_out, 1), cex = 0.8, font = 2)
}
res = as.vector(gmm)
return(res)
}
}
#' tryCatch function to prevent armadillo errors in KMEANS_arma
#'
#' @keywords internal
tryCatch_KMEANS_arma <- function(data, clusters, n_iter, verbose, seed_mode, CENTROIDS, seed) {
Error = tryCatch(KMEANS_arma(data, clusters, n_iter, verbose, seed_mode, CENTROIDS, seed),
error = function(e) e)
if (inherits(Error, "error")) {
return(list(Error = Error, message = Error$message))}
else if (sum(dim(Error)) == 0) {
return("warning: kmeans(): number of vectors is less than number of means")}
else {
return(Error)
}
}
#' k-means using the Armadillo library
#'
#' @param data matrix or data frame
#' @param clusters the number of clusters
#' @param n_iter the number of clustering iterations (about 10 is typically sufficient)
#' @param seed_mode how the initial centroids are seeded. One of, \emph{keep_existing}, \emph{static_subset}, \emph{random_subset}, \emph{static_spread}, \emph{random_spread}.
#' @param verbose either TRUE or FALSE, indicating whether progress is printed during clustering
#' @param CENTROIDS a matrix of initial cluster centroids. The rows of the CENTROIDS matrix should be equal to the number of clusters and the columns should be equal to the columns of the data. CENTROIDS should be used in combination with seed_mode 'keep_existing'.
#' @param seed integer value for random number generator (RNG)
#' @return the centroids as a matrix. In case of Error it returns the error message, whereas in case of an empty centroids-matrix it returns a warning-message.
#' @details
#' This function is an R implementation of the 'kmeans' class of the Armadillo library.
#' It is faster than the KMeans_rcpp function but it lacks some features. For more info see the details section of the KMeans_rcpp function.
#' The number of columns should be larger than the number of clusters or CENTROIDS.
#' If the clustering fails, the means matrix is reset and a bool set to false is returned.
#' The clustering will run faster on multi-core machines when OpenMP is enabled in your compiler (eg. -fopenmp in GCC)
#' @references
#' http://arma.sourceforge.net/docs.html
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#'
#' dat = center_scale(dat)
#'
#' km = KMeans_arma(dat, clusters = 2, n_iter = 10, "random_subset")
#'
KMeans_arma = function(data,
clusters,
n_iter = 10,
seed_mode = "random_subset",
verbose = FALSE,
CENTROIDS = NULL,
seed = 1) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (!is.numeric(clusters) || length(clusters) != 1 || clusters < 1) stop('clusters should be numeric and greater than 0')
if (n_iter < 0) stop('the n_iter parameter can not be negative')
if (!seed_mode %in% c('keep_existing','static_subset','random_subset','static_spread','random_spread'))
stop("available seed modes are 'keep_existing','static_subset','random_subset','static_spread' and 'random_spread'")
if ((seed_mode == 'keep_existing' && is.null(CENTROIDS)) || (seed_mode != 'keep_existing' && !is.null(CENTROIDS)))
stop('the keep_existing seed_mode should be used when CENTROIDS is not NULL')
if (!is.logical(verbose)) stop('the verbose parameter should be either TRUE or FALSE')
if (!is.null(CENTROIDS) && (!inherits(CENTROIDS, 'matrix') || nrow(CENTROIDS) != clusters || ncol(CENTROIDS) != ncol(data)))
stop('CENTROIDS should be a matrix with number of rows equal to the number of clusters and number of columns equal to the number of columns of the data')
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
res = tryCatch_KMEANS_arma(data, clusters, n_iter, verbose, seed_mode, CENTROIDS, seed)
if ('Error' %in% names(res) || is.character(res)) {
return(res)
} else {
## FIXME: this function currently returns centroids. It should probably
## return the same data structure as KMeans_cpp.
## return(structure(res, class = c("KMeansCluster", "k-means clustering")))
return (structure(res, class = "k-means clustering"))
}
}
#' k-means using RcppArmadillo
#'
#' @param data matrix or data frame
#' @param clusters the number of clusters
#' @param num_init number of times the algorithm will be run with different centroid seeds
#' @param max_iters the maximum number of clustering iterations
#' @param initializer the method of initialization. One of, \emph{optimal_init}, \emph{quantile_init}, \emph{kmeans++} and \emph{random}. See details for more information
#' @param fuzzy either TRUE or FALSE. If TRUE, then prediction probabilities will be calculated using the distance between observations and centroids
#' @param verbose either TRUE or FALSE, indicating whether progress is printed during clustering.
#' @param CENTROIDS a matrix of initial cluster centroids. The rows of the CENTROIDS matrix should be equal to the number of clusters and the columns should be equal to the columns of the data.
#' @param tol a float number. If, in case of an iteration (iteration > 1 and iteration < max_iters) 'tol' is greater than the squared norm of the centroids, then kmeans has converged
#' @param tol_optimal_init tolerance value for the 'optimal_init' initializer. The higher this value is, the far appart from each other the centroids are.
#' @param seed integer value for random number generator (RNG)
#' @return a list with the following attributes: clusters, fuzzy_clusters (if fuzzy = TRUE), centroids, total_SSE, best_initialization, WCSS_per_cluster, obs_per_cluster, between.SS_DIV_total.SS
#' @author Lampros Mouselimis
#' @details
#' This function has the following features in comparison to the KMeans_arma function:
#'
#' Besides optimal_init, quantile_init, random and kmeans++ initilizations one can specify the centroids using the CENTROIDS parameter.
#'
#' The running time and convergence of the algorithm can be adjusted using the num_init, max_iters and tol parameters.
#'
#' If num_init > 1 then KMeans_rcpp returns the attributes of the best initialization using as criterion the within-cluster-sum-of-squared-error.
#'
#'
#' ---------------initializers----------------------
#'
#' \strong{optimal_init} : this initializer adds rows of the data incrementally, while checking that they do not already exist in the centroid-matrix [ experimental ]
#'
#' \strong{quantile_init} : initialization of centroids by using the cummulative distance between observations and by removing potential duplicates [ experimental ]
#'
#' \strong{kmeans++} : kmeans++ initialization. Reference : http://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf AND http://stackoverflow.com/questions/5466323/how-exactly-does-k-means-work
#'
#' \strong{random} : random selection of data rows as initial centroids
#'
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#'
#' dat = center_scale(dat)
#'
#' km = KMeans_rcpp(dat, clusters = 2, num_init = 5, max_iters = 100, initializer = 'kmeans++')
#'
KMeans_rcpp = function(data,
clusters,
num_init = 1,
max_iters = 100,
initializer = 'kmeans++',
fuzzy = FALSE,
verbose = FALSE,
CENTROIDS = NULL,
tol = 1e-4,
tol_optimal_init = 0.3,
seed = 1) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (!is.numeric(clusters) || length(clusters) != 1 || clusters < 1) stop('clusters should be numeric and greater than 0')
if (num_init < 1) stop('the num_init parameter should be greater than 0')
if (max_iters < 1) stop('the max_iters parameter should be greater than 0')
if (!initializer %in% c('kmeans++', 'random', 'optimal_init', 'quantile_init')) stop("available initializer methods are 'kmeans++', 'random', 'optimal_init' and 'quantile_init'")
if (!is.logical(fuzzy)) stop('the fuzzy parameter should be either TRUE or FALSE')
if (!is.logical(verbose)) stop('the verbose parameter should be either TRUE or FALSE')
if (!is.null(CENTROIDS) && (!inherits(CENTROIDS, 'matrix') || nrow(CENTROIDS) != clusters || ncol(CENTROIDS) != ncol(data)))
stop('CENTROIDS should be a matrix with number of rows equal to the number of clusters and number of columns equal to the number of columns of the data')
if (tol <= 0.0) stop('tol should be a float number greater than 0.0')
if (tol_optimal_init <= 0.0) stop('tol_optimal_init should be a float number greater than 0.0')
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
res = KMEANS_rcpp(data, clusters, num_init, max_iters, initializer, fuzzy, verbose, CENTROIDS, tol, eps = 1.0e-6, tol_optimal_init, seed)
if (fuzzy) {
return(structure(list(call = match.call(),
clusters = as.vector(res$clusters + 1),
fuzzy_clusters = res$fuzzy_clusters,
centroids = res$centers,
total_SSE = res$total_SSE,
best_initialization = res$best_initialization,
WCSS_per_cluster = res$WCSS_per_cluster,
obs_per_cluster = res$obs_per_cluster,
between.SS_DIV_total.SS = (res$total_SSE - sum(res$WCSS_per_cluster)) / res$total_SSE),
class = c("KMeansCluster", "k-means clustering")))
} else {
return(structure(list(call = match.call(),
clusters = as.vector(res$clusters + 1),
centroids = res$centers,
total_SSE = res$total_SSE,
best_initialization = res$best_initialization,
WCSS_per_cluster = res$WCSS_per_cluster,
obs_per_cluster = res$obs_per_cluster,
between.SS_DIV_total.SS = (res$total_SSE - sum(res$WCSS_per_cluster)) / res$total_SSE),
class = c("KMeansCluster", "k-means clustering")))
}
}
#' Prediction function for the k-means
#'
#' @param data matrix or data frame
#' @param CENTROIDS a matrix of initial cluster centroids. The rows of the CENTROIDS matrix should be equal to the number of clusters and the columns should be equal to the columns of the data.
#' @param threads an integer specifying the number of cores to run in parallel
#' @param fuzzy either TRUE or FALSE. If TRUE, then probabilities for each cluster will be returned based on the distance between observations and centroids.
#' @return a vector (clusters)
#' @author Lampros Mouselimis
#' @details
#' This function takes the data and the output centroids and returns the clusters.
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#'
#' dat = center_scale(dat)
#'
#' km = KMeans_rcpp(dat, clusters = 2, num_init = 5, max_iters = 100, initializer = 'kmeans++')
#'
#' pr = predict_KMeans(dat, km$centroids, threads = 1)
predict_KMeans = function(data, CENTROIDS, threads = 1, fuzzy = FALSE) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (!is.matrix(CENTROIDS)) stop("CENTROIDS should be a matrix")
if (ncol(data) != ncol(CENTROIDS))
stop('the number of columns of the data should match the number of columns of the CENTROIDS ')
if (threads < 1) stop('the number of threads should be greater or equal to 1')
if (!is.logical(fuzzy)) stop('fuzzy should be either TRUE or FALSE')
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values", call. = F)
if (!is.null(class(CENTROIDS))) class(CENTROIDS) = NULL # set the class of the input 'CENTROIDS' to NULL otherwise the 'duplicated()' function might check it column-wise rather than row-wise
flag_dups = duplicated(CENTROIDS)
if (sum(flag_dups) > 0) stop("The 'CENTROIDS' input matrix includes duplicated rows!", call. = F)
res = validate_centroids(data = data,
init_centroids = CENTROIDS,
threads = threads,
fuzzy = fuzzy,
eps = 1.0e-6)
if (fuzzy) {
return(res$fuzzy_probs)
}
else {
return(as.vector(res$clusters) + 1)
}
}
#' @rdname predict_KMeans
#' @param object,newdata,... arguments for the `predict` generic
#' @export
predict.KMeansCluster <- function(object, newdata, fuzzy = FALSE, threads = 1, ...) {
out <- predict_KMeans(newdata,
CENTROIDS = object$centroids,
threads = threads,
fuzzy = fuzzy)
return(out)
}
#' @export
print.KMeansCluster <- function(x, ...) {
WSSE <- sum(x$WCSS_per_cluster)
BSSE <- x$total_SSE - WSSE
cat("KMeans Cluster\n",
"Call:", deparse(x$call), "\n",
"Data cols:", ncol(x$centroids), "\n",
"Centroids:", nrow(x$centroids), "\n",
"BSS/SS:", BSSE/x$total_SSE, "\n",
"SS:", x$total_SSE, "=", WSSE, "(WSS) +", BSSE, "(BSS)\n")
}
#' Silhouette width based on pre-computed clusters
#'
#' @param data a matrix or a data frame
#' @param clusters a numeric vector which corresponds to the pre-computed clusters (see the example section for more details). The size of the 'clusters' vector must be equal to the number of rows of the input data
#' @return a list object where the first sublist is the 'silhouette summary', the second sublist is the 'silhouette matrix' and the third sublist is the 'global average silhouette' (based on the silhouette values of all observations)
#' @author Lampros Mouselimis
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#' dat = center_scale(dat)
#'
#' clusters = 2
#'
#' # compute k-means
#' km = KMeans_rcpp(dat, clusters = clusters, num_init = 5, max_iters = 100, initializer = 'kmeans++')
#'
#' # compute the silhouette width
#' silh_km = silhouette_of_clusters(data = dat, clusters = km$clusters)
#'
#' # silhouette summary
#' silh_summary = silh_km$silhouette_summary
#'
#' # silhouette matrix (including cluster & dissimilarity)
#' silh_mtrx = silh_km$silhouette_matrix
#'
#' # global average silhouette
#' glob_avg = silh_km$silhouette_global_average
#'
silhouette_of_clusters = function(data, clusters) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('the "data" parameter must be either a matrix or a data frame!')
if (!inherits(clusters, c('numeric', 'integer'))) stop('the "clusters" parameter must be either of type numeric or of type integer!')
if (nrow(data) != length(clusters)) stop("I expect that the number of observations of the 'clusters' parameter is equal to the number of rows of the input 'data'!")
silh_lst = silhouette_clusters(data, clusters)
colnames(silh_lst[["silhouette_matrix"]]) = c('cluster', 'intra_cluster_dissim', 'silhouette')
return(silh_lst)
}
#' Optimal number of Clusters for Kmeans or Mini-Batch-Kmeans
#'
#' @param data matrix or data frame
#' @param max_clusters either a numeric value, a contiguous or non-continguous numeric vector specifying the cluster search space
#' @param criterion one of \emph{variance_explained}, \emph{WCSSE}, \emph{dissimilarity}, \emph{silhouette}, \emph{distortion_fK}, \emph{AIC}, \emph{BIC} and \emph{Adjusted_Rsquared}. See details for more information.
#' @param fK_threshold a float number used in the 'distortion_fK' criterion
#' @param num_init number of times the algorithm will be run with different centroid seeds
#' @param max_iters the maximum number of clustering iterations
#' @param initializer the method of initialization. One of, \emph{optimal_init}, \emph{quantile_init}, \emph{kmeans++} and \emph{random}. See details for more information
#' @param tol a float number. If, in case of an iteration (iteration > 1 and iteration < max_iters) 'tol' is greater than the squared norm of the centroids, then kmeans has converged
#' @param plot_clusters either TRUE or FALSE, indicating whether the results of the \emph{Optimal_Clusters_KMeans} function should be plotted
#' @param verbose either TRUE or FALSE, indicating whether progress is printed during clustering
#' @param tol_optimal_init tolerance value for the 'optimal_init' initializer. The higher this value is, the far appart from each other the centroids are.
#' @param seed integer value for random number generator (RNG)
#' @param mini_batch_params either NULL or a list of the following parameters : \emph{batch_size}, \emph{init_fraction}, \emph{early_stop_iter}. If not NULL then the optimal number of clusters will be found based on the Mini-Batch-Kmeans. See the details and examples sections for more information.
#' @return a vector with the results for the specified criterion. If plot_clusters is TRUE then it plots also the results.
#' @author Lampros Mouselimis
#' @details
#' ---------------criteria--------------------------
#'
#' \strong{variance_explained} : the sum of the within-cluster-sum-of-squares-of-all-clusters divided by the total sum of squares
#'
#' \strong{WCSSE} : the sum of the within-cluster-sum-of-squares-of-all-clusters
#'
#' \strong{dissimilarity} : the average intra-cluster-dissimilarity of all clusters (the distance metric defaults to euclidean)
#'
#' \strong{silhouette} : the average silhouette width where first the average per cluster silhouette is computed and then the global average (the distance metric defaults to euclidean). To compute the silhouette width for each cluster separately see the 'silhouette_of_clusters()' function
#'
#' \strong{distortion_fK} : this criterion is based on the following paper, 'Selection of K in K-means clustering' (https://www.ee.columbia.edu/~dpwe/papers/PhamDN05-kmeans.pdf)
#'
#' \strong{AIC} : the Akaike information criterion
#'
#' \strong{BIC} : the Bayesian information criterion
#'
#' \strong{Adjusted_Rsquared} : the adjusted R^2 statistic
#'
#'
#' ---------------initializers----------------------
#'
#' \strong{optimal_init} : this initializer adds rows of the data incrementally, while checking that they do not already exist in the centroid-matrix [ experimental ]
#'
#' \strong{quantile_init} : initialization of centroids by using the cummulative distance between observations and by removing potential duplicates [ experimental ]
#'
#' \strong{kmeans++} : kmeans++ initialization. Reference : http://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf AND http://stackoverflow.com/questions/5466323/how-exactly-does-k-means-work
#'
#' \strong{random} : random selection of data rows as initial centroids
#'
#'
#' If the \emph{mini_batch_params} parameter is not NULL then the optimal number of clusters will be found based on the Mini-batch-Kmeans algorithm, otherwise based on the Kmeans. The higher the \emph{init_fraction}
#' parameter is the more close the results between Mini-Batch-Kmeans and Kmeans will be.
#'
#' In case that the \emph{max_clusters} parameter is a contiguous or non-contiguous vector then plotting is disabled. Therefore, plotting is enabled only if the \emph{max_clusters} parameter is of length 1.
#' Moreover, the \emph{distortion_fK} criterion can't be computed if the \emph{max_clusters} parameter is a contiguous or non-continguous vector ( the \emph{distortion_fK} criterion requires consecutive clusters ).
#' The same applies also to the \emph{Adjusted_Rsquared} criterion which returns incorrect output.
#'
#' @references
#'
#' https://www.ee.columbia.edu/~dpwe/papers/PhamDN05-kmeans.pdf
#'
#' @importFrom utils txtProgressBar
#' @importFrom utils setTxtProgressBar
#' @importFrom graphics par
#' @importFrom graphics mtext
#' @importFrom stats na.omit
#'
#' @export
#' @examples
#'
#' data(dietary_survey_IBS)
#'
#' dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)]
#'
#' dat = center_scale(dat)
#'
#'
#' #-------
#' # kmeans
#' #-------
#'
#' opt_km = Optimal_Clusters_KMeans(dat, max_clusters = 10, criterion = "distortion_fK",
#'
#' plot_clusters = FALSE)
#'
#' #------------------
#' # mini-batch-kmeans
#' #------------------
#'
#'
#' params_mbkm = list(batch_size = 10, init_fraction = 0.3, early_stop_iter = 10)
#'
#' opt_mbkm = Optimal_Clusters_KMeans(dat, max_clusters = 10, criterion = "distortion_fK",
#'
#' plot_clusters = FALSE, mini_batch_params = params_mbkm)
#'
#'
#' #----------------------------
#' # non-contiguous search space
#' #----------------------------
#'
#' search_space = c(2,5)
#'
#' opt_km = Optimal_Clusters_KMeans(dat, max_clusters = search_space,
#'
#' criterion = "variance_explained",
#'
#' plot_clusters = FALSE)
#'
Optimal_Clusters_KMeans = function(data,
max_clusters,
criterion = "variance_explained",
fK_threshold = 0.85,
num_init = 1,
max_iters = 200,
initializer = 'kmeans++',
tol = 1e-4,
plot_clusters = TRUE,
verbose = FALSE,
tol_optimal_init = 0.3,
seed = 1,
mini_batch_params = NULL) {
if ('data.frame' %in% class(data)) data = as.matrix(data)
if (!inherits(data, 'matrix')) stop('data should be either a matrix or a data frame')
if (!inherits(max_clusters, c('numeric', 'integer'))) stop('max_clusters should be a numeric or integer vector')
if (length(max_clusters) == 1) {
if (max_clusters < 1) {
stop('In case that max_clusters is of length 1 it should be greater than 0')
}
}
if (!criterion %in% c('variance_explained', 'WCSSE', 'dissimilarity', 'silhouette', 'distortion_fK', 'AIC', 'BIC', 'Adjusted_Rsquared'))
stop("available criteria are 'variance_explained', 'WCSSE', 'dissimilarity', 'silhouette', 'distortion_fK', 'AIC', 'BIC' and 'Adjusted_Rsquared'")
if (num_init < 1) stop('the num_init parameter should be greater than 0')
if (max_iters < 1) stop('the max_iters parameter should be greater than 0')
if (!initializer %in% c('kmeans++', 'random', 'optimal_init', 'quantile_init'))
stop("available initializer methods are 'kmeans++', 'random', 'quantile_init' and 'optimal_init'")
if (tol <= 0.0) stop('tol should be a float number greater than 0.0')
if (!is.logical(plot_clusters)) stop('the plot_clusters parameter should be either TRUE or FALSE')
if (!is.logical(verbose)) stop('the verbose parameter should be either TRUE or FALSE')
if (tol_optimal_init <= 0.0) stop('tol_optimal_init should be a float number greater than 0.0')
if (!is.null(mini_batch_params)) {
if (!all(names(mini_batch_params) %in% c("batch_size", "init_fraction", "early_stop_iter"))) {
stop("The 'mini_batch_params' parameter should be of type list and valid inputs to the 'mini_batch_params' are: 'batch_size', 'init_fraction' and 'early_stop_iter'!", call. = F)
}
if (criterion == "variance_explained") {
stop("The 'variance_explained' criterion is not supported in case of mini-batch-kmeans (when 'mini_batch_params' is not NULL)!", call. = F)
}
}
if (length(max_clusters) != 1) plot_clusters = FALSE # set "plot_clusters" to FALSE if the "max_clusters" parameter is not of length 1
flag_non_finite = check_NaN_Inf(data)
if (!flag_non_finite) stop("the data includes NaN's or +/- Inf values")
LEN_CLUST = ITER_CLUST = NA
if (length(max_clusters) == 1) {
LEN_CLUST = max_clusters
ITER_CLUST = 1:max_clusters}
else {
LEN_CLUST = length(max_clusters)
ITER_CLUST = max_clusters
}
vec_out = rep(NA, LEN_CLUST)
if (verbose) { cat("", '\n'); pb = utils::txtProgressBar(min = 1, max = LEN_CLUST, style = 3); cat("", '\n') }
COUNT = 1
for (i in ITER_CLUST) {
if (is.null(mini_batch_params)) {
km = KMEANS_rcpp(data, i, num_init, max_iters, initializer, FALSE, FALSE, NULL, tol, 1.0e-6, tol_optimal_init, seed)
}
else {
km = MiniBatchKmeans(data, i, mini_batch_params[["batch_size"]], num_init, max_iters, mini_batch_params[["init_fraction"]],
initializer, mini_batch_params[["early_stop_iter"]], FALSE, NULL, tol, tol_optimal_init, seed)
tmp_cent = km$centroids
km["centroids"] = NULL
km[["centers"]] = tmp_cent # rename the mini-batch-kmeans centroids-name to match the one of the kmeans algorithm
if (criterion %in% c("dissimilarity", "silhouette", "BIC")) { # in these cases call also the 'predict_MBatchKMeans' function to receive the clusters
km_preds = predict_MBatchKMeans(data, tmp_cent, FALSE)
km[["clusters"]] = as.vector(km_preds)
}
}
if (criterion == "variance_explained") {
vec_out[COUNT] = sum(stats::na.omit(as.vector(km$WCSS_per_cluster))) / km$total_SSE
}
if (criterion == "WCSSE") {
vec_out[COUNT] = sum(stats::na.omit(as.vector(km$WCSS_per_cluster)))
}
if (criterion == "dissimilarity") {
eval_km = evaluation_rcpp(data, as.vector(km$clusters), FALSE)
tmp_dis = mean(stats::na.omit(unlist(lapply(eval_km$INTRA_cluster_dissimilarity, mean))))
vec_out[COUNT] = tmp_dis
}
if (criterion == "silhouette") {
if (i == 1) {
vec_out[COUNT] = 0.0
}
else {
silh_out = silhouette_of_clusters(data = data, clusters = as.vector(km$clusters))
vec_out[COUNT] = silh_out$silhouette_global_average # https://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette_score.html#sklearn.metrics.silhouette_score
}
}
if (criterion == "distortion_fK") {
vec_out[COUNT] = sum(stats::na.omit(as.vector(km$WCSS_per_cluster)))
}
if (criterion == "AIC") { # http://stackoverflow.com/questions/15839774/how-to-calculate-bic-for-k-means-clustering-in-r
m = ncol(km$centers)
k = nrow(km$centers)
D = sum(stats::na.omit(km$WCSS_per_cluster))
vec_out[COUNT] = D + 2.0 * m * k
}
if (criterion == "BIC") { # http://stackoverflow.com/questions/15839774/how-to-calculate-bic-for-k-means-clustering-in-r
m = ncol(km$centers)
k = nrow(km$centers)
n = length(km$clusters)
D = sum(stats::na.omit(km$WCSS_per_cluster))
vec_out[COUNT] = D + log(n) * m * k
}
if (criterion == 'Adjusted_Rsquared') {
vec_out[COUNT] = sum(stats::na.omit(km$WCSS_per_cluster))
}
if (verbose) { utils::setTxtProgressBar(pb, COUNT) }
COUNT = COUNT + 1
}
if (verbose) { close(pb); cat("", '\n') }
if (criterion == 'Adjusted_Rsquared') { # http://sherrytowers.com/2013/10/24/k-means-clustering/
if (length(max_clusters) != 1) {
vec_out = "The 'Adjusted_Rsquared' criterion doesn't return the correct output if the 'max_clusters' parameter is greater than 1"
}
else {
vec_out = 1.0 - (vec_out * (nrow(data) - 1)) / (vec_out[1] * (nrow(data) - ITER_CLUST))
}
}
if (criterion %in% c('variance_explained', 'WCSSE', 'dissimilarity', 'silhouette', 'AIC', 'BIC', 'Adjusted_Rsquared')) {
if (plot_clusters) {
tmp_VAL = as.vector(stats::na.omit(vec_out))
if (length(which(is.na(vec_out))) > 0) {
x_dis = (1:length(vec_out))[-which(is.na(vec_out))]
y_dis = vec_out[-which(is.na(vec_out))]
}
else {
x_dis = 1:length(vec_out)
y_dis = vec_out
}
y_MAX = max(tmp_VAL)
graphics::plot(x = x_dis, y = y_dis, type = 'l', xlab = 'clusters', ylab = criterion, col = 'blue', lty = 3, axes = FALSE)
graphics::axis(1, at = seq(1, length(vec_out) , by = 1))
if (criterion == 'silhouette') {
graphics::axis(2, at = seq(0, y_MAX + 0.05, by = 0.05 ), las = 1, cex.axis = 0.8)
graphics::abline(h = seq(0.0, max(as.vector(stats::na.omit(vec_out))), 0.05), v = seq(1, length(vec_out) , by = 1), col = "gray", lty = 3)
}
else {
tmp_summary = round(summary(y_MAX)[['Max.']])
out_max_summary = ifelse(tmp_summary == 0, 1, tmp_summary)
graphics::axis(2, at = seq(0, y_MAX + out_max_summary / 10, by = out_max_summary / 10), las = 1, cex.axis = 0.8)
graphics::abline(h = seq(0.0, max(as.vector(stats::na.omit(vec_out))), out_max_summary / 10), v = seq(1, length(vec_out) , by = 1), col = "gray", lty = 3)
}
if (criterion %in% c("variance_explained", "Adjusted_Rsquared", "dissimilarity", "silhouette")) {
graphics::text(x = 1:length(vec_out), y = vec_out, labels = round(vec_out, 2), cex = 0.8, font = 2)
}
else {
graphics::text(x = 1:length(vec_out), y = vec_out, labels = round(vec_out, 1), cex = 0.8, font = 2)
}
}
}
else { # "distortion_fK"
if (length(max_clusters) != 1) {
fK_vec = "The 'distortion_fK' criterion can not be computed if the length of the 'max_clusters' parameter is greater than 1. See the details for more information!"
}
else {
f_K = opt_clust_fK(vec_out, ncol(data), fK_threshold)
fK_vec = as.vector(f_K$fK_evaluation)
}
if (plot_clusters) {
if (length(which(is.na(fK_vec))) > 0) {
x_fk = (1:length(fK_vec))[-which(is.na(fK_vec))]
y_fk = fK_vec[-which(is.na(fK_vec))]
}
else {
x_fk = 1:length(fK_vec)
y_fk = fK_vec
}
graphics::par(oma = c(0, 2, 0, 0))
graphics::plot(y_fk, type = 'l', xlab = 'clusters', ylab = 'f(K)', col = 'green', axes = FALSE)
graphics::axis(1, at = x_fk)
graphics::axis(2, at = seq(0, max(y_fk) + 0.1, by = round(summary(y_fk)[['Max.']]) / 10), las = 1, cex.axis = 0.8)
graphics::abline(h = seq(0.0, max(y_fk), round(summary(y_fk)[['Max.']]) / 10), v = seq(1, length(y_fk) , by = 1), col = "gray", lty = 3)
graphics::abline(h = fK_threshold, col = 'blue', lty = 3)
graphics::mtext("threshold", side = 2, line = 2, at = fK_threshold, las = 1, cex = 0.9)
graphics::text(x = x_fk, y = y_fk, labels = round(y_fk,2), cex = 0.8, font = 2)
}
}
if (criterion %in% c('variance_explained', 'WCSSE', 'dissimilarity', 'silhouette', 'AIC', 'BIC', 'Adjusted_Rsquared')) {