Debian Codegraph @

R/find_k.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 ### Remove dependancy on fpc by importing pamk to this file.
21 ### #' @importFrom fpc pamk
22 ### NULL
23 # fpc::pamk
24 # Author: Christian Hennig [email protected] http://www.homepages.ucl.ac.uk/~ucakche/
25
26 # fpc::dudahart2
27 dudahart2 <- function(x, clustering, alpha = 0.001) {
28 x <- as.matrix(x)
29 p <- ncol(x)
30 n <- nrow(x)
31 cln <- rep(0, 2)
32 W <- matrix(0, p, p)
33 for (i in 1:2) cln[i] <- sum(clustering == i)
34 for (i in 1:2) {
35 clx <- x[clustering == i, ]
36 cclx <- cov(as.matrix(clx))
37 if (cln[i] < 2) {
38 cclx <- 0
39 }
40 W <- W + ((cln[i] - 1) * cclx)
41 }
42 W1 <- (n - 1) * cov(as.matrix(x))
43 dh <- sum(diag(W)) / sum(diag(W1))
44 z <- qnorm(1 - alpha)
45 compare <- 1 - 2 / (pi * p) - z * sqrt(2 * (1 - 8 / (pi^2 * p)) / (n *
46 p))
47 qz <- (-dh + 1 - 2 / (pi * p)) / sqrt(2 * (1 - 8 / (pi^2 * p)) / (n *
48 p))
49 p.value <- 1 - pnorm(qz)
50 cluster1 <- dh >= compare
51 out <- list(
52 p.value = p.value, dh = dh, compare = compare,
53 cluster1 = cluster1, alpha = alpha, z = z
54 )
55 out
56 }
57
58 # fpc::calinhara
59 calinhara <- function(x, clustering, cn = max(clustering)) {
60 x <- as.matrix(x)
61 p <- ncol(x)
62 n <- nrow(x)
63 cln <- rep(0, cn)
64 W <- matrix(0, p, p)
65 for (i in 1:cn) cln[i] <- sum(clustering == i)
66 for (i in 1:cn) {
67 clx <- x[clustering == i, ]
68 cclx <- cov(as.matrix(clx))
69 if (cln[i] < 2) {
70 cclx <- 0
71 }
72 W <- W + ((cln[i] - 1) * cclx)
73 }
74 S <- (n - 1) * cov(x)
75 B <- S - W
76 out <- (n - cn) * sum(diag(B)) / ((cn - 1) * sum(diag(W)))
77 out
78 }
79
80 # fpc::distcritmulti
81 distcritmulti <- function(x, clustering, part = NULL, ns = 10, criterion = "asw",
82 fun = "dist", metric = "euclidean", count = FALSE,
83 seed = NULL, ...) {
84 if (!is.null(seed)) {
85 set.seed(seed)
86 }
87 n <- length(clustering)
88 if (is.null(part)) {
89 pn1 <- n %/% ns
90 pn2 <- n %% ns
91 part <- rep(pn1, ns)
92 part[ns] <- part[ns] + pn2
93 }
94 np <- sum(part)
95 ns <- length(part)
96 n <- length(clustering)
97 npsam <- sample(n, np)
98 cp <- cumsum(part)
99 ss <- list()
100 ss[[1]] <- npsam[1:cp[1]]
101 asw <- numeric(0)
102 for (i in 2:ns) ss[[i]] <- npsam[(cp[i - 1] + 1):cp[i]]
103 for (i in 1:ns) {
104 if (count) {
105 cat("Subset ", i, "\n")
106 }
107 if (fun == "dist") {
108 dx <- dist(x[ss[[i]], ], method = metric, ...)
109 } else {
110 dx <- cluster::daisy(x[ss[[i]], ], metric = metric, ...)
111 }
112 if (criterion == "asw") {
113 asw[i] <- summary(cluster::silhouette(
114 clustering[ss[[i]]],
115 dx
116 ))$avg.width
117 }
118 if (criterion == "pearsongamma") {
119 asw[i] <- cluster.stats(dx, clustering[ss[[i]]],
120 silhouette = FALSE
121 )$pearsongamma
122 }
123 }
124 aswav <- sum(part * asw) / np
125 crit.sd <- sd(asw)
126 out <- list(
127 crit.overall = aswav, crit.sub = asw, crit.sd = crit.sd,
128 subsets = ss
129 )
130 out
131 }
132
133 # fpc::cluster.stats
134 cluster.stats <- function(d = NULL, clustering, alt.clustering = NULL, noisecluster = FALSE,
135 silhouette = TRUE, G2 = FALSE, G3 = FALSE, wgap = TRUE, sepindex = TRUE,
136 sepprob = 0.1, sepwithnoise = TRUE, compareonly = FALSE,
137 aggregateonly = FALSE) {
138 if (!is.null(d)) {
139 d <- as.dist(d)
140 }
141 cn <- max(clustering)
142 clusteringf <- as.factor(clustering)
143 clusteringl <- levels(clusteringf)
144 cnn <- length(clusteringl)
145 if (cn != cnn) {
146 warning("clustering renumbered because maximum != number of clusters")
147 for (i in 1:cnn) clustering[clusteringf == clusteringl[i]] <- i
148 cn <- cnn
149 }
150 n <- length(clustering)
151 noisen <- 0
152 cwn <- cn
153 if (noisecluster) {
154 noisen <- sum(clustering == cn)
155 cwn <- cn - 1
156 }
157 diameter <- average.distance <- median.distance <- separation <- average.toother <- cluster.size <- within.dist <- between.dist <- numeric(0)
158 for (i in 1:cn) cluster.size[i] <- sum(clustering == i)
159 pk1 <- cluster.size / n
160 pk10 <- pk1[pk1 > 0]
161 h1 <- -sum(pk10 * log(pk10))
162 corrected.rand <- vi <- NULL
163 if (!is.null(alt.clustering)) {
164 choose2 <- function(v) {
165 out <- numeric(0)
166 for (i in 1:length(v)) {
167 out[i] <- ifelse(v[i] >= 2,
168 choose(v[i], 2), 0
169 )
170 }
171 out
172 }
173 cn2 <- max(alt.clustering)
174 clusteringf <- as.factor(alt.clustering)
175 clusteringl <- levels(clusteringf)
176 cnn2 <- length(clusteringl)
177 if (cn2 != cnn2) {
178 warning("alt.clustering renumbered because maximum != number of clusters")
179 for (i in 1:cnn2) alt.clustering[clusteringf == clusteringl[i]] <- i
180 cn2 <- cnn2
181 }
182 nij <- table(clustering, alt.clustering)
183 dsum <- sum(choose2(nij))
184 cs2 <- numeric(0)
185 for (i in 1:cn2) cs2[i] <- sum(alt.clustering == i)
186 sum1 <- sum(choose2(cluster.size))
187 sum2 <- sum(choose2(cs2))
188 pk2 <- cs2 / n
189 pk12 <- nij / n
190 corrected.rand <- (dsum - sum1 * sum2 / choose2(n)) / ((sum1 +
191 sum2) / 2 - sum1 * sum2 / choose2(n))
192 pk20 <- pk2[pk2 > 0]
193 h2 <- -sum(pk20 * log(pk20))
194 icc <- 0
195 for (i in 1:cn) {
196 for (j in 1:cn2) {
197 if (pk12[i, j] > 0) {
198 icc <- icc + pk12[i, j] * log(pk12[i, j] / (pk1[i] *
199 pk2[j]))
200 }
201 }
202 }
203 vi <- h1 + h2 - 2 * icc
204 }
205 if (compareonly) {
206 out <- list(corrected.rand = corrected.rand, vi = vi)
207 }
208 else {
209 dmat <- as.matrix(d)
210 within.cluster.ss <- 0
211 overall.ss <- nonnoise.ss <- sum(d^2) / n
212 if (noisecluster) {
213 nonnoise.ss <- sum(as.dist(dmat[
214 clustering <= cwn,
215 clustering <= cwn
216 ])^2) / sum(clustering <= cwn)
217 }
218 ave.between.matrix <- separation.matrix <- matrix(0,
219 ncol = cn, nrow = cn
220 )
221 di <- list()
222 for (i in 1:cn) {
223 cluster.size[i] <- sum(clustering == i)
224 di <- as.dist(dmat[clustering == i, clustering ==
225 i])
226 if (i <= cwn) {
227 within.cluster.ss <- within.cluster.ss + sum(di^2) / cluster.size[i]
228 within.dist <- c(within.dist, di)
229 }
230 if (length(di) > 0) {
231 diameter[i] <- max(di)
232 } else {
233 diameter[i] <- NA
234 }
235 average.distance[i] <- mean(di)
236 median.distance[i] <- median(di)
237 bv <- numeric(0)
238 for (j in 1:cn) {
239 if (j != i) {
240 sij <- dmat[clustering == i, clustering ==
241 j]
242 bv <- c(bv, sij)
243 if (i < j) {
244 separation.matrix[i, j] <- separation.matrix[
245 j,
246 i
247 ] <- min(sij)
248 ave.between.matrix[i, j] <- ave.between.matrix[
249 j,
250 i
251 ] <- mean(sij)
252 if (i <= cwn & j <= cwn) {
253 between.dist <- c(between.dist, sij)
254 }
255 }
256 }
257 }
258 separation[i] <- min(bv)
259 average.toother[i] <- mean(bv)
260 }
261 average.between <- mean(between.dist)
262 average.within <- mean(within.dist)
263 nwithin <- length(within.dist)
264 nbetween <- length(between.dist)
265 between.cluster.ss <- nonnoise.ss - within.cluster.ss
266 ch <- between.cluster.ss * (n - noisen - cwn) / (within.cluster.ss *
267 (cwn - 1))
268 clus.avg.widths <- avg.width <- NULL
269 if (silhouette) {
270 sii <- silhouette(clustering, dmatrix = dmat)
271 sc <- summary(sii)
272 clus.avg.widths <- sc$clus.avg.widths
273 if (noisecluster) {
274 avg.width <- mean(sii[clustering <= cwn, 3])
275 } else {
276 avg.width <- sc$avg.width
277 }
278 }
279 g2 <- g3 <- cn2 <- cwidegap <- widestgap <- sindex <- NULL
280 if (G2) {
281 splus <- sminus <- 0
282 for (i in 1:nwithin) {
283 splus <- splus + sum(within.dist[i] < between.dist)
284 sminus <- sminus + sum(within.dist[i] > between.dist)
285 }
286 g2 <- (splus - sminus) / (splus + sminus)
287 }
288 if (G3) {
289 sdist <- sort(c(within.dist, between.dist))
290 sr <- nwithin + nbetween
291 dmin <- sum(sdist[1:nwithin])
292 dmax <- sum(sdist[(sr - nwithin + 1):sr])
293 g3 <- (sum(within.dist) - dmin) / (dmax - dmin)
294 }
295 pearsongamma <- cor(c(within.dist, between.dist), c(rep(
296 0,
297 nwithin
298 ), rep(1, nbetween)))
299 dunn <- min(separation[1:cwn]) / max(diameter[1:cwn], na.rm = TRUE)
300 acwn <- ave.between.matrix[1:cwn, 1:cwn]
301 dunn2 <- min(acwn[upper.tri(acwn)]) / max(average.distance[1:cwn],
302 na.rm = TRUE
303 )
304 if (wgap) {
305 cwidegap <- rep(0, cwn)
306 for (i in 1:cwn) {
307 if (sum(clustering == i) > 1) {
308 cwidegap[i] <- max(hclust(as.dist(dmat[clustering ==
309 i, clustering == i]), method = "single")$height)
310 }
311 }
312 widestgap <- max(cwidegap)
313 }
314 if (sepindex) {
315 psep <- rep(NA, n)
316 if (sepwithnoise | !noisecluster) {
317 for (i in 1:n) {
318 psep[i] <- min(dmat[i, clustering !=
319 clustering[i]])
320 }
321 minsep <- floor(n * sepprob)
322 }
323 else {
324 dmatnn <- dmat[clustering <= cwn, clustering <=
325 cwn]
326 clusteringnn <- clustering[clustering <= cwn]
327 for (i in 1:(n - noisen)) {
328 psep[i] <- min(dmatnn[
329 i,
330 clusteringnn != clusteringnn[i]
331 ])
332 }
333 minsep <- floor((n - noisen) * sepprob)
334 }
335 sindex <- mean(sort(psep)[1:minsep])
336 }
337 if (!aggregateonly) {
338 out <- list(
339 n = n, cluster.number = cn, cluster.size = cluster.size,
340 min.cluster.size = min(cluster.size[1:cwn]),
341 noisen = noisen, diameter = diameter, average.distance = average.distance,
342 median.distance = median.distance, separation = separation,
343 average.toother = average.toother, separation.matrix = separation.matrix,
344 ave.between.matrix = ave.between.matrix, average.between = average.between,
345 average.within = average.within, n.between = nbetween,
346 n.within = nwithin, max.diameter = max(diameter[1:cwn],
347 na.rm = TRUE
348 ), min.separation = sepwithnoise *
349 min(separation) + (!sepwithnoise) * min(separation[1:cwn]),
350 within.cluster.ss = within.cluster.ss, clus.avg.silwidths = clus.avg.widths,
351 avg.silwidth = avg.width, g2 = g2, g3 = g3, pearsongamma = pearsongamma,
352 dunn = dunn, dunn2 = dunn2, entropy = h1, wb.ratio = average.within / average.between,
353 ch = ch, cwidegap = cwidegap, widestgap = widestgap,
354 sindex = sindex, corrected.rand = corrected.rand,
355 vi = vi
356 )
357 } else {
358 out <- list(
359 n = n, cluster.number = cn, min.cluster.size = min(cluster.size[1:cwn]),
360 noisen = noisen, average.between = average.between,
361 average.within = average.within, max.diameter = max(diameter[1:cwn],
362 na.rm = TRUE
363 ), min.separation = sepwithnoise *
364 min(separation) + (!sepwithnoise) * min(separation[1:cwn]),
365 ave.within.cluster.ss = within.cluster.ss / (n - noisen),
366 avg.silwidth = avg.width, g2 = g2, g3 = g3, pearsongamma = pearsongamma,
367 dunn = dunn, dunn2 = dunn2, entropy = h1, wb.ratio = average.within / average.between,
368 ch = ch, widestgap = widestgap, sindex = sindex,
369 corrected.rand = corrected.rand, vi = vi
370 )
371 }
372 }
373 out
374 }
375
376 pamk <- function(data, krange = 2:10, criterion = "asw", usepam = TRUE,
377 scaling = FALSE, alpha = 0.001, diss = inherits(data, "dist"),
378 critout = FALSE, ns = 10, seed = NULL, ...) {
379 ddata <- as.matrix(data)
380 if (!identical(scaling, FALSE)) {
381 sdata <- scale(ddata, scale = scaling)
382 } else {
383 sdata <- ddata
384 }
385 cluster1 <- 1 %in% krange
386 critval <- numeric(max(krange))
387 pams <- list()
388 for (k in krange) {
389 if (usepam) {
390 pams[[k]] <- cluster::pam(sdata, k, diss = diss, ...)
391 } else {
392 pams[[k]] <- cluster::clara(sdata, k, ...)
393 }
394 if (k != 1) {
395 critval[k] <- switch(criterion, asw = pams[[k]]$silinfo$avg.width,
396 multiasw = distcritmulti(sdata, pams[[k]]$clustering,
397 seed = seed, ns = ns
398 )$crit.overall, ch = ifelse(diss,
399 cluster.stats(sdata, pams[[k]]$clustering)$ch,
400 calinhara(sdata, pams[[k]]$clustering)
401 )
402 )
403 }
404 if (critout) {
405 cat(k, " clusters ", critval[k], "\\n")
406 }
407 }
408 k.best <- (1:max(krange))[which.max(critval)]
409 if (cluster1) {
410 if (diss) {
411 cluster1 <- FALSE
412 } else {
413 cxx <- dudahart2(sdata, pams[[2]]$clustering, alpha = alpha)
414 critval[1] <- cxx$p.value
415 cluster1 <- cxx$cluster1
416 }
417 }
418 if (cluster1) {
419 k.best <- 1
420 }
421 out <- list(pamobject = pams[[k.best]], nc = k.best, crit = critval)
422 out
423 }
424
425 #' @title Find the (estimated) number of clusters for a dendrogram using average silhouette width
426 #' @rdname find_k
427 #' @export
428 #' @description
429 #' This function estimates the number of clusters based on the maximal average \link[cluster]{silhouette} width
430 #' derived from running \link[cluster]{pam} on the \link[stats]{cophenetic} distance matrix of
431 #' the \link[stats]{dendrogram}. The output is based on the \link[fpc]{pamk} output.
432 #' @param dend A dendrogram (or hclust) tree object
433 #' @param krange integer vector. Numbers of clusters which are to be compared
434 #' by the average silhouette width criterion.
435 #' Note: average silhouette width and Calinski-Harabasz can't estimate number
436 #' of clusters nc=1. If 1 is included, a Duda-Hart test is applied and 1 is
437 #' estimated if this is not significant.
438 #' @param x An object of class "find_k" (has its own S3 plot method).
439 #' @param xlab,ylab,main parameters passed to plot.
440 #' @param ... passed to \link[fpc]{pamk} (the current defaults criterion="asw" and usepam=TRUE can not be changes).
441 #' @seealso
442 #' \link[fpc]{pamk}, \link[cluster]{pam}, \link[cluster]{silhouette}.
443 #' @return
444 #' A \link[fpc]{pamk} output. This is a list with the following components:
445 #' 1) pamobject - The output of the optimal run of the pam-function.
446 #' 2) nc - the optimal number of clusters.
447 #' 3) crit - vector of criterion values for numbers of clusters. crit[1] is the p-value of the Duda-Hart test if 1 is in krange and diss=FALSE.
448 #' 4) k - a copy of nc (just to make it easier to extract - since k is often used in other functions)
449 #' @examples
450 #'
451 #' dend <- iris[, -5] %>%
452 #' dist() %>%
453 #' hclust() %>%
454 #' as.dendrogram()
455 #' dend_k <- find_k(dend)
456 #' plot(dend_k)
457 #' plot(color_branches(dend, k = dend_k$nc))
458 #'
459 #' library(cluster)
460 #' sil <- silhouette(dend_k$pamobject)
461 #' plot(sil)
462 #'
463 #' dend <- USArrests %>%
464 #' dist() %>%
465 #' hclust(method = "ave") %>%
466 #' as.dendrogram()
467 #' dend_k <- find_k(dend)
468 #' plot(dend_k)
469 #' plot(color_branches(dend, k = dend_k$nc))
470 find_k <- function(dend, krange = 2:min(10, (nleaves(dend) - 1)), ...) {
471 # library(fpc)
472 # krange = 2:10
473 # criterion = "asw"
474 d <- cophenetic(dend) # this will work for both a dendrogram and an hclust object.
475 out <- pamk(d, krange = krange, criterion = "asw", usepam = TRUE, ...)
476 out$k <- out$nc # just to make it easier to find.
477 class(out) <- "find_k"
478 out
479 }
480
481
482 #' @export
483 #' @rdname find_k
484 plot.find_k <- function(x,
485 xlab = "Number of clusters (k)",
486 ylab = "Average silhouette width",
487 main = "Estimating the number of clusters using\n average silhouette width",
488 ...) {
489 asw <- x$crit
490 k <- seq_along(x$crit)
491
492 col <- rep("black", length(k))
493 col[which.max(asw)] <- "red"
494
495 plot(asw ~ k,
496 xlab = xlab,
497 ylab = ylab,
498 main = main,
499 type = "b",
500 las = 1,
501 col = col,
502 ...
503 )
504 }