Debian Codegraph @

R/bk_method.R

raw
1 # Copyright (C) Tal Galili
2 #
3 # This file is part of dendextend.
4 #
5 # dendextend is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # dendextend is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18
19
20
21
22
23 #' @title Sorts two clusters vector by their names
24 #' @description Sorts two clusters vector by their names and returns a list with the sorted vectors.
25 #' @export
26 #' @param A1_clusters a numeric vector of cluster grouping (numeric) of items,
27 #' with a name attribute of item name for each element from group A1.
28 #' These are often obtained by using some k cut on a dendrogram.
29 #' @param A2_clusters a numeric vector of cluster grouping (numeric) of items,
30 #' with a name attribute of item name for each element from group A2.
31 #' These are often obtained by using some k cut on a dendrogram.
32 #' @param assume_sorted_vectors logical (FALSE). Can we assume to two group
33 #' vectors are sorter so that they have the same order of items?
34 #' IF FALSE (default), then the vectors will be sorted based on their
35 #' name attribute.
36 #' @param warn logical (default from dendextend_options("warn") is FALSE).
37 #' Set if warning are to be issued, it is safer to keep this at TRUE,
38 #' but for keeping the noise down, the default is FALSE.
39 #' @param ... Ignored.
40 #'
41 #' @return
42 #' A list with two elements, corresponding to the two clustering vectors.
43 #'
44 #' @examples
45 #'
46 #' \dontrun{
47 #'
48 #' set.seed(23235)
49 #' ss <- sample(1:150, 4)
50 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
51 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
52 #' # dend1 <- as.dendrogram(hc1)
53 #' # dend2 <- as.dendrogram(hc2)
54 #' # cutree(dend1)
55 #'
56 #' A1_clusters <- cutree(hc1, k = 3)
57 #' A2_clusters <- sample(cutree(hc1, k = 3))
58 #'
59 #' sort_2_clusters_vectors(A1_clusters, A2_clusters, assume_sorted_vectors = TRUE) # no sorting
60 #' sort_2_clusters_vectors(A1_clusters, A2_clusters, assume_sorted_vectors = FALSE) # Sorted
61 #' }
62 sort_2_clusters_vectors <- function(A1_clusters, A2_clusters, assume_sorted_vectors = FALSE, warn = dendextend_options("warn"), ...) {
63
64 # sanity checks in case the names of the vectors do not make sense:
65 if (!assume_sorted_vectors) {
66 names_A1_clusters <- names(A1_clusters)
67 names_A2_clusters <- names(A2_clusters)
68
69 if (is.null(names_A1_clusters) || is.null(names_A2_clusters)) {
70 if (warn) warning("Names of the clusters are NULL, we will assume the vectors are sorted.")
71 assume_sorted_vectors <- TRUE
72 }
73 if (length(names_A1_clusters) != length(names_A2_clusters)) {
74 if (warn) warning("Names of the clusters are not of equal length, we will assume the vectors are sorted.")
75 assume_sorted_vectors <- TRUE
76 }
77 if (length(names_A1_clusters) != length(A1_clusters)) {
78 if (warn) warning("Names of the clusters are not of equal length as that of the clusters, we will assume the vectors are sorted.")
79 assume_sorted_vectors <- TRUE
80 }
81 }
82 # if we are still NOT assuming the vectors are sorted - we can sort them...
83 if (!assume_sorted_vectors) {
84 A1_clusters <- A1_clusters[order(names_A1_clusters)] # order the vec accourding to the names, so to allow a comparison
85 A2_clusters <- A2_clusters[order(names_A2_clusters)] # order the vec accourding to the names, so to allow a comparison
86 }
87
88 return(list(A1_clusters = A1_clusters, A2_clusters = A2_clusters))
89 }
90
91
92
93 #' @title Calculating Fowlkes-Mallows index in R
94 #' @export
95 #' @description
96 #'
97 #' Calculating Fowlkes-Mallows index.
98 #'
99 #' The \code{FM_index_R}
100 #' function also calculates the expectancy and variance of the FM Index
101 #' under the null hypothesis of no relation.
102 #'
103 #'
104 #' @param A1_clusters a numeric vector of cluster grouping (numeric) of items,
105 #' with a name attribute of item name for each element from group A1.
106 #' These are often obtained by using some k cut on a dendrogram.
107 #' @param A2_clusters a numeric vector of cluster grouping (numeric) of items,
108 #' with a name attribute of item name for each element from group A2.
109 #' These are often obtained by using some k cut on a dendrogram.
110 #' @param assume_sorted_vectors logical (FALSE). Can we assume to two group
111 #' vectors are sorter so that they have the same order of items?
112 #' IF FALSE (default), then the vectors will be sorted based on their
113 #' name attribute.
114 #' @param warn logical (default from dendextend_options("warn") is FALSE).
115 #' Set if warning are to be issued, it is safer to keep this at TRUE,
116 #' but for keeping the noise down, the default is FALSE.
117 #' @param ... Ignored.
118 #'
119 #' @details
120 #' From Wikipedia:
121 #'
122 #' Fowlkes-Mallows index (see references) is an external evaluation method
123 #' that is used to determine the similarity between two clusterings
124 #' (clusters obtained after a clustering algorithm). This measure of similarity
125 #' could be either between two hierarchical clusterings or a clustering and
126 #' a benchmark classification. A higher the value for the Fowlkes-Mallows index
127 #' indicates a greater similarity between the clusters and the benchmark
128 #' classifications.
129 #'
130 #' @seealso
131 #' \link{cor_bakers_gamma}
132 #' @return
133 #' The Fowlkes-Mallows index between two vectors of clustering groups.
134 #'
135 #' Includes the attributes E_FM and V_FM for the relevant expectancy and
136 #' variance under the null hypothesis of no-relation.
137 #'
138 #' @references
139 #'
140 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
141 #' "A Method for Comparing Two Hierarchical Clusterings".
142 #' Journal of the American Statistical Association 78 (383): 553.
143 #'
144 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
145 #'
146 #' @examples
147 #'
148 #' \dontrun{
149 #'
150 #' set.seed(23235)
151 #' ss <- TRUE # sample(1:150, 10 )
152 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
153 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
154 #' # dend1 <- as.dendrogram(hc1)
155 #' # dend2 <- as.dendrogram(hc2)
156 #' # cutree(dend1)
157 #'
158 #' FM_index_R(cutree(hc1, k = 3), cutree(hc1, k = 3)) # 1
159 #' set.seed(1341)
160 #' FM_index_R(cutree(hc1, k = 3),
161 #' sample(cutree(hc1, k = 3)),
162 #' assume_sorted_vectors = TRUE) # 0.38037
163 #' FM_index_R(cutree(hc1, k = 3),
164 #' sample(cutree(hc1, k = 3)),
165 #' assume_sorted_vectors = FALSE) # 1 again :)
166 #' FM_index_R(cutree(hc1, k = 3),
167 #' cutree(hc2, k = 3)) # 0.8059
168 #' FM_index_R(cutree(hc1, k = 30),
169 #' cutree(hc2, k = 30)) # 0.4529
170 #'
171 #' fo <- function(k) FM_index_R(cutree(hc1, k), cutree(hc2, k))
172 #' lapply(1:4, fo)
173 #' ks <- 1:150
174 #' plot(sapply(ks, fo) ~ ks, type = "b", main = "Bk plot for the iris dataset")
175 #'
176 #' clu_1 <- cutree(hc2, k = 100) # this is a lie - since this one is NOT well defined!
177 #' clu_2 <- cutree(as.dendrogram(hc2), k = 100) # We see that we get a vector of NAs for this...
178 #'
179 #' FM_index_R(clu_1, clu_2) # NA
180 #' }
181 FM_index_R <- function(A1_clusters, A2_clusters, assume_sorted_vectors = FALSE, warn = dendextend_options("warn"), ...) {
182 if (!assume_sorted_vectors) {
183 sorted_As <- sort_2_clusters_vectors(A1_clusters, A2_clusters,
184 assume_sorted_vectors = assume_sorted_vectors,
185 warn = warn
186 )
187 A1_clusters <- sorted_As[[1]]
188 A2_clusters <- sorted_As[[2]]
189 }
190
191 if (any(is.na(A1_clusters)) | any(is.na(A2_clusters))) {
192 if (warn) warning("The clusterings have some NA's in them - returned NA.")
193 FM_index <- NA
194 attr(FM_index, "E_FM") <- NA
195 attr(FM_index, "V_FM") <- NA
196 return(FM_index)
197 }
198
199
200
201 # creating matrix M
202 # ----------
203 # a not-so-smart way
204 # M <- matrix(0, nrow = k, ncol = k)
205 # for(i in 1:k)
206 # {
207 # for(j in 1:k)
208 # {
209 # M[i,j] <- sum(rect.hclust(A1, k = k)[[i]] %in% rect.hclust(A2, k = k)[[j]])
210 # how many of the objects in cluser i in tree A1, exist in cluster j in tree A2
211 # }
212 # }
213 # ----------
214 # a much better way!
215 M <- table(A1_clusters, A2_clusters)
216 # calculate n
217 n <- length(A1_clusters)
218
219 Tk <- sum(M^2) - n
220 m_i. <- apply(M, 1, sum)
221 m_.j <- apply(M, 2, sum)
222 m_.. <- n # sum(M)
223 if (sum(M) != n) stop("Why does M matrix doesn't sum up to n ??")
224 Pk <- sum(m_i.^2) - n
225 Qk <- sum(m_.j^2) - n
226
227 FM <- Tk / sqrt(Pk * Qk)
228
229 # Expectancy of the FM (according to H0)
230 E_FM <- sqrt(Pk * Qk) / (n * (n - 1))
231
232
233 Pk2 <- sum(m_i. * (m_i. - 1) * (m_i. - 2))
234 Qk2 <- sum(m_.j * (m_.j - 1) * (m_.j - 2))
235 # variance of the FM (according to H0)
236 V_FM <- 2 / (n * (n - 1)) +
237 4 * Pk2 * Qk2 / ((n * (n - 1) * (n - 2)) * Pk * Qk) +
238 (Pk - 2 - 4 * Pk2 / Pk) * (Qk - 2 - 4 * Qk2 / Qk) / ((n * (n - 1) * (n - 2) * (n - 3))) -
239 Pk * Qk / (n^2 * (n - 1)^2)
240
241
242 FM_index <- FM # c(, E_FM, V_FM)
243 attr(FM_index, "E_FM") <- E_FM
244 attr(FM_index, "V_FM") <- V_FM
245
246 return(FM_index)
247 }
248
249
250
251
252
253
254
255
256
257 #' @title Calculating Fowlkes-Mallows Index
258 #' @export
259 #' @description
260 #'
261 #' Calculating Fowlkes-Mallows index.
262 #'
263 #' The \code{FM_index_R} function calculates the expectancy and variance of the FM Index
264 #' under the null hypothesis of no relation.
265 #'
266 #'
267 #' @param A1_clusters a numeric vector of cluster grouping (numeric) of items,
268 #' with a name attribute of item name for each element from group A1.
269 #' These are often obtained by using some k cut on a dendrogram.
270 #' @param A2_clusters a numeric vector of cluster grouping (numeric) of items,
271 #' with a name attribute of item name for each element from group A2.
272 #' These are often obtained by using some k cut on a dendrogram.
273 #' @param assume_sorted_vectors logical (FALSE). Can we assume to two group
274 #' vectors are sorter so that they have the same order of items?
275 #' IF FALSE (default), then the vectors will be sorted based on their
276 #' name attribute.
277 #' @param warn logical (default from dendextend_options("warn") is FALSE).
278 #' Set if warning are to be issued, it is safer to keep this at TRUE,
279 #' but for keeping the noise down, the default is FALSE.
280 #' @param ... Ignored
281 #'
282 #' @details
283 #' From Wikipedia:
284 #'
285 #' Fowlkes-Mallows index (see references) is an external evaluation method
286 #' that is used to determine the similarity between two clusterings
287 #' (clusters obtained after a clustering algorithm). This measure of similarity
288 #' could be either between two hierarchical clusterings or a clustering and
289 #' a benchmark classification. A higher the value for the Fowlkes-Mallows index
290 #' indicates a greater similarity between the clusters and the benchmark
291 #' classifications.
292 #'
293 #' @seealso
294 #' \link{cor_bakers_gamma}
295 #' @return
296 #' The Fowlkes-Mallows index between two vectors of clustering groups.
297 #'
298 #' Includes the attributes E_FM and V_FM for the relevant expectancy and
299 #' variance under the null hypothesis of no-relation.
300 #'
301 #' @references
302 #'
303 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
304 #' "A Method for Comparing Two Hierarchical Clusterings".
305 #' Journal of the American Statistical Association 78 (383): 553.
306 #'
307 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
308 #'
309 #' @examples
310 #'
311 #' \dontrun{
312 #'
313 #' set.seed(23235)
314 #' ss <- TRUE # sample(1:150, 10 )
315 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
316 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
317 #' # dend1 <- as.dendrogram(hc1)
318 #' # dend2 <- as.dendrogram(hc2)
319 #' # cutree(dend1)
320 #'
321 #' FM_index(cutree(hc1, k = 3), cutree(hc1, k = 3)) # 1 with EV
322 #'
323 #' # checking speed gains
324 #' library(microbenchmark)
325 #' microbenchmark(
326 #' FM_index(cutree(hc1, k = 3), cutree(hc1, k = 3)),
327 #' FM_index(cutree(hc1, k = 3), cutree(hc1, k = 3),
328 #' assume_sorted_vectors = TRUE
329 #' ),
330 #' FM_index(cutree(hc1, k = 3), cutree(hc1, k = 3),
331 #' assume_sorted_vectors = TRUE
332 #' )
333 #' )
334 #' # C code is 1.2-1.3 times faster.
335 #'
336 #' set.seed(1341)
337 #' FM_index(cutree(hc1, k = 3), sample(cutree(hc1, k = 3)),
338 #' assume_sorted_vectors = TRUE
339 #' ) # 0.38037
340 #' FM_index(cutree(hc1, k = 3), sample(cutree(hc1, k = 3)),
341 #' assume_sorted_vectors = FALSE
342 #' ) # 1 again :)
343 #' FM_index(cutree(hc1, k = 3), cutree(hc2, k = 3)) # 0.8059
344 #' FM_index(cutree(hc1, k = 30), cutree(hc2, k = 30)) # 0.4529
345 #'
346 #' fo <- function(k) FM_index(cutree(hc1, k), cutree(hc2, k))
347 #' lapply(1:4, fo)
348 #' ks <- 1:150
349 #' plot(sapply(ks, fo) ~ ks, type = "b", main = "Bk plot for the iris dataset")
350 #' }
351 FM_index <- function(A1_clusters, A2_clusters, assume_sorted_vectors = FALSE, warn = dendextend_options("warn"), ...) {
352 FM <- FM_index_R(A1_clusters, A2_clusters,
353 assume_sorted_vectors = assume_sorted_vectors, warn = warn, ...
354 )
355
356 return(FM)
357 }
358
359
360
361
362
363
364
365 #' @title Calculating Fowlkes-Mallows Index under H0
366 #' @export
367 #' @description
368 #'
369 #' Calculating Fowlkes-Mallows index under the null hypothesis of no relation
370 #' between the clusterings (random order of the items labels).
371 #'
372 #' @param A1_clusters a numeric vector of cluster grouping (numeric) of items,
373 #' with a name attribute of item name for each element from group A1.
374 #' These are often obtained by using some k cut on a dendrogram.
375 #' @param A2_clusters a numeric vector of cluster grouping (numeric) of items,
376 #' with a name attribute of item name for each element from group A2.
377 #' These are often obtained by using some k cut on a dendrogram.
378 #' @param warn logical (default from dendextend_options("warn") is FALSE).
379 #' Set if warning are to be issued, it is safer to keep this at TRUE,
380 #' but for keeping the noise down, the default is FALSE.
381 #' @param ... Ignored
382 #'
383 #'
384 #' @seealso
385 #' \link{cor_bakers_gamma},
386 #' \code{\link{FM_index_R}}, \code{\link{FM_index}}
387 #'
388 #' @return
389 #' The Fowlkes-Mallows index between two vectors of clustering groups.
390 #' Under H0. (a double without attr)
391 #'
392 #' @references
393 #'
394 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
395 #' "A Method for Comparing Two Hierarchical Clusterings".
396 #' Journal of the American Statistical Association 78 (383): 553.
397 #'
398 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
399 #'
400 #' @examples
401 #'
402 #' \dontrun{
403 #'
404 #' set.seed(23235)
405 #' ss <- TRUE # sample(1:150, 10 )
406 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
407 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
408 #' # dend1 <- as.dendrogram(hc1)
409 #' # dend2 <- as.dendrogram(hc2)
410 #' # cutree(dend1)
411 #'
412 #' # small k
413 #' A1_clusters <- cutree(hc1, k = 3) # will give a right tailed distribution
414 #' # large k
415 #' A1_clusters <- cutree(hc1, k = 50) # will give a discrete distribution
416 #' # "medium" k
417 #' A1_clusters <- cutree(hc1, k = 25) # gives almost the normal distribution!
418 #' A2_clusters <- A1_clusters
419 #'
420 #' R <- 10000
421 #' set.seed(414130)
422 #' FM_index_H0 <- replicate(R, FM_index_permutation(A1_clusters, A2_clusters)) # can take 10 sec
423 #' plot(density(FM_index_H0), main = "FM Index distribution under H0\n (10000 permutation)")
424 #' abline(v = mean(FM_index_H0), col = 1, lty = 2)
425 #'
426 #'
427 #' # The permutation distribution is with a heavy right tail:
428 #' # Source of the skew functions is based on: library(psych)
429 #'
430 #' skew <- function (x, na.rm = TRUE) {
431 #' x <- na.omit(x)
432 #' sum((x - mean(x))^3)/(length(x) * sd(x)^3)
433 #' }
434 #' skew(FM_index_H0) # 1.254
435 #'
436 #'
437 #' mean(FM_index_H0)
438 #' var(FM_index_H0)
439 #' the_FM_index <- FM_index(A1_clusters, A2_clusters)
440 #' the_FM_index
441 #' our_dnorm <- function(x) {
442 #' dnorm(x,
443 #' mean = attr(the_FM_index, "E_FM"),
444 #' sd = sqrt(attr(the_FM_index, "V_FM"))
445 #' )
446 #' }
447 #' # our_dnorm(0.35)
448 #' curve(our_dnorm,
449 #' col = 4,
450 #' from = -1, to = 1, n = R, add = TRUE
451 #' )
452 #' abline(v = attr(the_FM_index, "E_FM"), col = 4, lty = 2)
453 #'
454 #' legend("topright", legend = c("asymptotic", "permutation"), fill = c(4, 1))
455 #' }
456 FM_index_permutation <- function(A1_clusters, A2_clusters, warn = dendextend_options("warn"), ...) {
457 return(
458 as.vector(FM_index(sample(A1_clusters),
459 sample(A2_clusters),
460 assume_sorted_vectors = TRUE, warn = warn, ...
461 ))
462 )
463 }
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483 #' @title Bk - Calculating Fowlkes-Mallows Index for two dendrogram
484 #' @export
485 #' @description
486 #'
487 #' Bk is the calculation of Fowlkes-Mallows index for a series of k cuts
488 #' for two dendrograms.
489 #'
490 #' @param tree1 a dendrogram/hclust/phylo object.
491 #' @param tree2 a dendrogram/hclust/phylo object.
492 #' @param k an integer scalar or vector with the desired number
493 #' of cluster groups.
494 #' If missing - the Bk will be calculated for a default k range of
495 #' 2:(nleaves-1).
496 #' No point in checking k=1/k=n, since both will give Bk=1.
497 #' @param warn logical (default from dendextend_options("warn") is FALSE).
498 #' Set if warning are to be issued, it is safer to keep this at TRUE,
499 #' but for keeping the noise down, the default is FALSE.
500 #' @param ... Ignored (passed to FM_index_R).
501 #'
502 #' @details
503 #' From Wikipedia:
504 #'
505 #' Fowlkes-Mallows index (see references) is an external evaluation method
506 #' that is used to determine the similarity between two clusterings
507 #' (clusters obtained after a clustering algorithm). This measure of similarity
508 #' could be either between two hierarchical clusterings or a clustering and
509 #' a benchmark classification. A higher the value for the Fowlkes-Mallows index
510 #' indicates a greater similarity between the clusters and the benchmark
511 #' classifications.
512 #'
513 #' @seealso
514 #' \link{FM_index}, \link{cor_bakers_gamma}, \link{Bk_plot}
515 #' @return
516 #' A list (of k's length) of Fowlkes-Mallows index between two dendrogram for
517 #' a scalar/vector of k values.
518 #' The names of the lists' items is the k for which it was calculated.
519 #'
520 #' @references
521 #'
522 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
523 #' "A Method for Comparing Two Hierarchical Clusterings".
524 #' Journal of the American Statistical Association 78 (383): 553.
525 #'
526 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
527 #'
528 #' @examples
529 #'
530 #' \dontrun{
531 #'
532 #' set.seed(23235)
533 #' ss <- TRUE # sample(1:150, 10 )
534 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
535 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
536 #' tree1 <- as.dendrogram(hc1)
537 #' tree2 <- as.dendrogram(hc2)
538 #' # cutree(tree1)
539 #'
540 #' Bk(hc1, hc2, k = 3)
541 #' Bk(hc1, hc2, k = 2:10)
542 #' Bk(hc1, hc2)
543 #'
544 #' Bk(tree1, tree2, k = 3)
545 #' Bk(tree1, tree2, k = 2:5)
546 #'
547 #' system.time(Bk(hc1, hc2, k = 2:5)) # 0.01
548 #' system.time(Bk(hc1, hc2)) # 1.28
549 #' system.time(Bk(tree1, tree2, k = 2:5)) # 0.24 # after fixes.
550 #' system.time(Bk(tree1, tree2, k = 2:10)) # 0.31 # after fixes.
551 #' system.time(Bk(tree1, tree2)) # 7.85
552 #' Bk(tree1, tree2, k = 99:101)
553 #'
554 #' y <- Bk(hc1, hc2, k = 2:10)
555 #' plot(unlist(y) ~ c(2:10), type = "b", ylim = c(0, 1))
556 #'
557 #' # can take a few seconds
558 #' y <- Bk(hc1, hc2)
559 #' plot(unlist(y) ~ as.numeric(names(y)),
560 #' main = "Bk plot", pch = 20,
561 #' xlab = "k", ylab = "FM Index",
562 #' type = "b", ylim = c(0, 1)
563 #' )
564 #' # we are still missing some hypothesis testing here.
565 #' # for this we'll have the Bk_plot function.
566 #' }
567 Bk <- function(tree1, tree2, k, warn = dendextend_options("warn"), ...) {
568
569 # some sanity checks!
570 if (warn) { # the sanity checks are turned off by default since the "labels" function for dendrogram is one which takes some time to run...
571 # notice that we must have labels.hclust and labels.dendrogram defined!
572 tree1_labels <- labels(tree1)
573 tree2_labels <- labels(tree2)
574 length_tree1_labels <- length(tree1_labels)
575 length_tree2_labels <- length(tree2_labels)
576
577 # Checking for common error options:
578 if (length_tree1_labels != length_tree2_labels) stop("The two clusters don't have the same number of items!") # If cluster sized are different - stop
579 if (!all(sort(tree1_labels) == sort(tree2_labels))) stop("Your trees are having leaves with different names - please correct it in order to use this function")
580 }
581
582
583 if (missing(k)) k <- 2:(nleaves(tree1) - 1)
584 cutree_tree1 <- cutree(tree1, k, NA_to_0L = FALSE)
585 cutree_tree2 <- cutree(tree2, k, NA_to_0L = FALSE)
586 # makes sure the output is a matrix:
587 # This is if length(k)==1 since in that case
588 # the output would be a vector, not a matrix.
589 if (length(k) == 1) {
590 cutree_tree1 <- as.matrix(cutree_tree1)
591 cutree_tree2 <- as.matrix(cutree_tree2)
592 }
593 # example of such a case:
594 # a = cutree(tree1, k=1:2)
595 # is.vector(a)
596 # is.matrix(a)
597 # a = as.matrix(a)
598 # is.vector(a)
599 # is.matrix(a)
600
601 n_ks <- ncol(cutree_tree1)
602
603 Bk_for_each_k <- function(i_k) {
604 FM_index(
605 cutree_tree1[, i_k], cutree_tree2[, i_k],
606 assume_sorted_vectors = FALSE,
607 # We can't trust cutree to give the same order of items!
608 # In order to assume it, we would need to match order by labels
609 # and then have cutree( ) with order_clusters_as_data=TRUE
610 # but for small length of k's, this per-process (/checks)
611 # will likely be more expensive than simply running it with
612 # assume_sorted_vectors = FALSE,
613 warn = warn
614 )
615 }
616
617 the_Bks <- lapply(seq_len(n_ks), Bk_for_each_k)
618 names(the_Bks) <- k
619
620 return(the_Bks)
621 }
622
623
624
625
626
627
628 #' @title Bk permutation - Calculating Fowlkes-Mallows Index for two dendrogram
629 #' @export
630 #' @description
631 #'
632 #' Bk is the calculation of Fowlkes-Mallows index for a series of k cuts
633 #' for two dendrograms.
634 #'
635 #' Bk permutation calculates the Bk under the null hypothesis of no similarirty
636 #' between the two trees by randomally shuffling the labels of the two trees
637 #' and calculating their Bk.
638 #' @param tree1 a dendrogram/hclust/phylo object.
639 #' @param tree2 a dendrogram/hclust/phylo object.
640 #' @param k an integer scalar or vector with the desired number
641 #' of cluster groups.
642 #' If missing - the Bk will be calculated for a default k range of
643 #' 2:(nleaves-1).
644 #' No point in checking k=1/k=n, since both will give Bk=1.
645 #' @param R integer (Default is 1000). The number of Bk permutation to perform for each k.
646 #' @param warn logical (default from dendextend_options("warn") is FALSE).
647 #' Set if warning are to be issued, it is safer to keep this at TRUE,
648 #' but for keeping the noise down, the default is FALSE.
649 #' If set to TRUE, extra checks are made to varify that the two clusters have
650 #' the same size and the same labels.
651 #' @param ... Ignored (passed to FM_index_R).
652 #'
653 #' @details
654 #' From Wikipedia:
655 #'
656 #' Fowlkes-Mallows index (see references) is an external evaluation method
657 #' that is used to determine the similarity between two clusterings
658 #' (clusters obtained after a clustering algorithm). This measure of similarity
659 #' could be either between two hierarchical clusterings or a clustering and
660 #' a benchmark classification. A higher the value for the Fowlkes-Mallows index
661 #' indicates a greater similarity between the clusters and the benchmark
662 #' classifications.
663 #'
664 #' @seealso
665 #' \code{\link{FM_index}}, \link{Bk}
666 #' @return
667 #' A list (of the length of k's), where each element of the list has
668 #' R (number of permutations) calculations of Fowlkes-Mallows index
669 #' between two dendrogram after having their labels shuffled.
670 #'
671 #' The names of the lists' items is the k for which it was calculated.
672 #'
673 #' @references
674 #'
675 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
676 #' "A Method for Comparing Two Hierarchical Clusterings".
677 #' Journal of the American Statistical Association 78 (383): 553.
678 #'
679 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
680 #'
681 #' @examples
682 #'
683 #' \dontrun{
684 #'
685 #' set.seed(23235)
686 #' ss <- TRUE # sample(1:150, 10 )
687 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
688 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
689 #' # tree1 <- as.treerogram(hc1)
690 #' # tree2 <- as.treerogram(hc2)
691 #' # cutree(tree1)
692 #'
693 #' some_Bk <- Bk(hc1, hc2, k = 20)
694 #' some_Bk_permu <- Bk_permutations(hc1, hc2, k = 20)
695 #'
696 #' # we can see that the Bk is much higher than the permutation Bks:
697 #' plot(
698 #' x = rep(1, 1000), y = some_Bk_permu[[1]],
699 #' main = "Bk distribution under H0",
700 #' ylim = c(0, 1)
701 #' )
702 #' points(1, y = some_Bk, pch = 19, col = 2)
703 #' }
704 Bk_permutations <- function(tree1, tree2, k, R = 1000, warn = dendextend_options("warn"), ...) {
705
706 # some sanity checks!
707 if (warn) { # the sanity checks are turned off by default since the "labels" function for dendrogram is one which takes some time to run...
708 # notice that we must have labels.hclust and labels.dendrogram defined!
709 tree1_labels <- labels(tree1)
710 tree2_labels <- labels(tree2)
711 length_tree1_labels <- length(tree1_labels)
712 length_tree2_labels <- length(tree2_labels)
713
714 # Checking for common error options:
715 if (length_tree1_labels != length_tree2_labels) stop("The two clusters don't have the same number of items!") # If cluster sized are different - stop
716 if (!all(sort(tree1_labels) == sort(tree2_labels))) stop("Your trees are having leaves with different names - please correct it in order to use this function")
717 }
718
719 Bk_permutations_for_each_k <- function(k) {
720 A1_clusters <- cutree(tree1, k)
721 A2_clusters <- cutree(tree2, k)
722
723 FM_index_H0 <- replicate(R, FM_index_permutation(A1_clusters, A2_clusters, warn = warn)) # can take 10 sec
724
725 return(FM_index_H0)
726 }
727
728 if (missing(k)) k <- 2:(nleaves(tree1) - 1)
729 the_Bks_permutations <- lapply(k, Bk_permutations_for_each_k)
730 names(the_Bks_permutations) <- k
731
732 return(the_Bks_permutations)
733 }
734
735
736
737
738
739
740
741
742
743
744 #' @title Bk plot - ploting the Fowlkes-Mallows Index of two dendrogram for various k's
745 #' @export
746 #' @description
747 #'
748 #' Bk is the calculation of Fowlkes-Mallows index for a series of k cuts
749 #' for two dendrograms.
750 #' A Bk plot is simply a scatter plot of Bk versus k.
751 #' This plot helps in identifiying the similarity between two dendrograms in
752 #' different levels of k (number of clusters).
753 #'
754 #' @param tree1 a dendrogram/hclust/phylo object.
755 #' @param tree2 a dendrogram/hclust/phylo object.
756 #' @param k an integer scalar or vector with the desired number
757 #' of cluster groups.
758 #' If missing - the Bk will be calculated for a default k range of
759 #' 2:(nleaves-1).
760 #' No point in checking k=1/k=n, since both will give Bk=1.
761 #' @param add_E logical (TRUE). Should we add a line of the Expected Bk value
762 #' for each k, under the null hypothesis of no relation between the clusterings?
763 #' @param rejection_line_asymptotic logical (TRUE). Should we add a line of
764 #' the one sided rejection region based on the asymptotic distribution
765 #' of Bk values, for each k, under the null hypothesis of no relation
766 #' between the clusterings?
767 #' @param rejection_line_permutation logical (FALSE). Should we add a line of
768 #' the one sided rejection region based on the asymptotic distribution
769 #' of Bk values, for each k, under the null hypothesis of no relation
770 #' between the clusterings?
771 #' @param R integer (Default is 1000). The number of Bk permutation to perform
772 #' for each k. Applicable only if rejection_line_permutation is TRUE.
773 #' @param k_permutation the k's to be used for permutation (sometimes we might
774 #' be only interested in some k's and it is not important to run the simulation
775 #' for all possible ks). If missing - k itself will be used.
776 #' @param conf.level the level of one sided confidence interval used for creation
777 #' of the rejection lines.
778 #' @param p.adjust.methods a character scalar of either "none" (default), or
779 #' "bonferroni". This controls the multiple correction method to use for the
780 #' critical rejection values. Currently only the Bonferroni method
781 #' is implemented (based on the number of different k values).
782 #' @param col_line_Bk the color of the Bk line.
783 #' @param col_line_asymptotic the color of the rejection asymptotic Bk line.
784 #' @param col_line_permutation the color of the rejection asymptotic Bk line.
785 #' @param warn logical (default from dendextend_options("warn") is FALSE).
786 #' Set if warning are to be issued, it is safer to keep this at TRUE,
787 #' but for keeping the noise down, the default is FALSE.
788 #' If set to TRUE, extra checks are made to varify that the two clusters have
789 #' the same size and the same labels.
790 #' @param main passed to \link{plot}.
791 #' @param xlab passed to \link{plot}.
792 #' @param ylab passed to \link{plot}.
793 #' @param xlim passed to \link{plot}. If missign, xlim is from 2 to nleaves-1
794 #' @param ylim passed to \link{plot}.
795 #' @param try_cutree_hclust logical (TRUE). Since cutree for hclust is MUCH
796 #' faster than for dendrogram - Bk_plot will first try to change the dendrogram
797 #' into an hclust object. If it will fail (for example, with unbranched trees),
798 #' it will continue using the cutree.dendrogram functions.
799 #' If try_cutree_hclust=FALSE, it will force to use cutree.dendrogram and
800 #' not cutree.hclust.
801 #' @param ... Ignored.
802 #'
803 #' @details
804 #' From Wikipedia:
805 #'
806 #' Fowlkes-Mallows index (see references) is an external evaluation method
807 #' that is used to determine the similarity between two clusterings
808 #' (clusters obtained after a clustering algorithm). This measure of similarity
809 #' could be either between two hierarchical clusterings or a clustering and
810 #' a benchmark classification. A higher the value for the Fowlkes-Mallows index
811 #' indicates a greater similarity between the clusters and the benchmark
812 #' classifications.
813 #'
814 #' The default Bk plot comes with a line with dots (type "b") of the Bk values.
815 #' Also with a fragmented (lty=2) line (of the same color) of the expected Bk
816 #' line under H0,
817 #' And a solid red line of the upper critical Bk values for rejection
818 #'
819 #'
820 #' @seealso
821 #' \code{\link{FM_index}}, \link{Bk}, \link{Bk_permutations}
822 #' @return
823 #' After plotting the Bk plot.
824 #' Returns (invisible) the output of the elements used for constructing the plot:
825 #' The Bk values, Bk permutations (if used), Bk theoratical values, etc.
826 #'
827 #' @references
828 #'
829 #' Fowlkes, E. B.; Mallows, C. L. (1 September 1983).
830 #' "A Method for Comparing Two Hierarchical Clusterings".
831 #' Journal of the American Statistical Association 78 (383): 553.
832 #'
833 #' \url{https://en.wikipedia.org/wiki/Fowlkes-Mallows_index}
834 #'
835 #' @examples
836 #'
837 #' \dontrun{
838 #'
839 #' set.seed(23235)
840 #' ss <- TRUE # sample(1:150, 10 )
841 #' hc1 <- hclust(dist(iris[ss, -5]), "com")
842 #' hc2 <- hclust(dist(iris[ss, -5]), "single")
843 #' # tree1 <- as.treerogram(hc1)
844 #' # tree2 <- as.treerogram(hc2)
845 #' # cutree(tree1)
846 #'
847 #' Bk_plot(hc1, hc2, k = 2:20, xlim = c(2, 149))
848 #' Bk_plot(hc1, hc2)
849 #'
850 #' Bk_plot(hc1, hc2, k = 3)
851 #' Bk_plot(hc1, hc2, k = 3:10)
852 #' Bk_plot(hc1, hc2)
853 #' Bk_plot(hc1, hc2, p.adjust.methods = "bonferroni") # higher rejection lines
854 #'
855 #' # this one can take a bit of time:
856 #' Bk_plot(hc1, hc2,
857 #' rejection_line_permutation = TRUE,
858 #' k_permutation = c(2, 4, 6, 8, 10, 20, 30, 40, 50), R = 100
859 #' )
860 #' # we can see that the permutation line is VERY close to the asymptotic line.
861 #' # This is great since it means one can often use the asymptotic results
862 #' # Without having to do many simulations.
863 #'
864 #' # works just as well for dendrograms:
865 #' dend1 <- as.dendrogram(hc1)
866 #' dend2 <- as.dendrogram(hc2)
867 #' Bk_plot(dend1, dend2, k = 2:3, try_cutree_hclust = FALSE) # slower than hclust, but works...
868 #' Bk_plot(hc1, dend2, k = 2:3, try_cutree_hclust = FALSE) # slower than hclust, but works...
869 #' Bk_plot(dend1, dend1, k = 2:3, try_cutree_hclust = TRUE) # slower than hclust, but works...
870 #' Bk_plot(hc1, hc1, k = 2:3) # slower than hclust, but works...
871 #' # for some reason it can't turn dend2 back to hclust :(
872 #' a <- Bk_plot(hc1, hc2, k = 2:3, try_cutree_hclust = TRUE) # slower than hclust, but works...
873 #'
874 #' hc1_mixed <- as.hclust(sample(as.dendrogram(hc1)))
875 #' Bk_plot(
876 #' tree1 = hc1, tree2 = hc1_mixed,
877 #' add_E = FALSE,
878 #' rejection_line_permutation = TRUE, k_permutation = c(2, 4, 6, 8, 10, 20, 30, 40, 50), R = 100
879 #' )
880 #' }
881 Bk_plot <- function(tree1, tree2, k,
882 add_E = TRUE,
883 rejection_line_asymptotic = TRUE,
884 rejection_line_permutation = FALSE,
885 R = 1000,
886 k_permutation,
887 conf.level = 0.95,
888 p.adjust.methods = c("none", "bonferroni"),
889 col_line_Bk = 1,
890 col_line_asymptotic = 2,
891 col_line_permutation = 4,
892 warn = dendextend_options("warn"),
893 main = "Bk plot",
894 xlab = "k (number of clusters)",
895 ylab = "Bk (Fowlkes-Mallows Index)",
896 xlim,
897 ylim = c(0, 1),
898 try_cutree_hclust = TRUE,
899 ...) {
900 if (try_cutree_hclust) {
901 # if we succeed (tryCatch) in turning it into hclust - use it!
902 # if not - go on with the function.
903 if (!is.hclust(tree1)) {
904 tree1_hc <- tryCatch(as.hclust(tree1), error = function(e) {
905 FALSE
906 })
907 }
908 if (!is.hclust(tree2)) {
909 tree2_hc <- tryCatch(as.hclust(tree2), error = function(e) {
910 FALSE
911 })
912 }
913
914 # only if we got BOTH trees to be hclust - can be put them in...
915
916 if ((exists("tree1_hc") & exists("tree2_hc")) &&
917 !(is.logical(tree1_hc) | is.logical(tree2_hc))) {
918 tree1 <- tree1_hc
919 tree2 <- tree2_hc
920 }
921 }
922
923 output <- list()
924 if (missing(k)) k <- 2:(nleaves(tree1) - 1)
925 the_Bks <- Bk(tree1, tree2,
926 k = k,
927 warn = warn
928 )
929 output[length(output) + 1] <- list(Bk = the_Bks)
930 if (missing(xlim)) xlim <- c(2, c(nleaves(tree1) - 1))
931
932 # k and as.numeric(names(the_Bks)) should be THE SAME
933 plot(unlist(the_Bks) ~ k,
934 main = main, xlab = xlab, ylab = ylab,
935 xlim = xlim, ylim = ylim,
936 col = col_line_Bk,
937 pch = 20, type = "b"
938 )
939
940
941 if (add_E) {
942 the_Bks_E <- sapply(the_Bks, function(x) attr(x, "E_FM"))
943 lines(the_Bks_E ~ k,
944 col = col_line_Bk,
945 type = "l", lty = 2, lwd = 2
946 )
947 # the points are added for the case we have NA's in the Bk
948 points(the_Bks_E ~ k,
949 col = col_line_Bk,
950 pch = 19, cex = .01
951 )
952 }
953
954 p.adjust.methods <- match.arg(p.adjust.methods)
955 if (p.adjust.methods == "bonferroni") {
956 alfa <- 1 - conf.level
957 conf.level <- 1 - alfa / length(k)
958 }
959
960 if (rejection_line_asymptotic) {
961 if (!exists("the_Bks_E")) the_Bks_E <- sapply(the_Bks, function(x) attr(x, "E_FM"))
962 the_Bks_V <- sapply(the_Bks, function(x) attr(x, "V_FM"))
963
964 the_Bks_SD <- sqrt(the_Bks_V)
965 Z <- qnorm(conf.level)
966
967 Bk_critical_value_asymptotic <- the_Bks_E + Z * the_Bks_SD
968
969 lines(Bk_critical_value_asymptotic ~ k,
970 col = col_line_asymptotic,
971 pch = 20, type = "l", lty = 1, lwd = 2, cex = .5
972 )
973 # the points are added for the case we have NA's in the Bk
974 points(Bk_critical_value_asymptotic ~ k,
975 col = col_line_asymptotic,
976 pch = 19, cex = .01
977 )
978 output[length(output) + 1] <- list(Bk_critical_value_asymptotic = Bk_critical_value_asymptotic)
979 }
980
981 if (rejection_line_permutation) {
982 if (missing(k_permutation)) k_permutation <- k
983 some_Bk_permu <- Bk_permutations(tree1, tree2, k = k_permutation, R = R, warn = warn)
984 # we can see that the Bk is much higher than the permutation Bks:
985 Bk_critical_value_permu <- unname(sapply(some_Bk_permu, quantile, probs = conf.level))
986 lines(Bk_critical_value_permu ~ k_permutation,
987 col = col_line_permutation,
988 pch = 20, type = "l", lty = 1, lwd = 2, cex = .5
989 )
990 output[length(output) + 1] <- list(Bk_permutations = some_Bk_permu)
991 output[length(output) + 1] <- list(Bk_critical_value_permu = Bk_critical_value_permu)
992 }
993
994
995 return(invisible(output))
996 }
997
998
999
1000 # Bk_plot(tree1, tree2, k = 30:50)
1001 # Bk_plot(tree1, tree2)
1002
1003 # The Bk function was previously also implemented by Matt in:
1004 # https://cran.r-project.org/package=profdpm
1005 # See pages 9 and 10 here: https://CRAN.R-project.org/package=profdpm/vignettes/profdpm.pdf
1006 # As of February 2020 the package went off CRAN, so I removed it also from dendextend.
1007 # I came by this package thanks to chl: https://stats.stackexchange.com/questions/3672/a-measure-to-describe-the-distribution-of-a-dendrogram
1008 # Also, there is a great overview of similarity measures on this here:
1009 # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.164.6189&rep=rep1&type=pdf