Debian Codegraph @

inst/doc/Cluster_Analysis.Rmd

raw
1 ---
2 title: "Hierarchical cluster analysis on famous data sets - enhanced with the _dendextend_ package"
3 date: "`r Sys.Date()`"
4 author: "Tal Galili"
5 output:
6 html_vignette:
7 toc: yes
8 ---
9 <!--
10 %\VignetteEngine{knitr::rmarkdown}
11 %\VignetteIndexEntry{Hierarchical cluster analysis on famous data sets - enhanced with the _dendextend_ package}
12 -->
13
14 ```{r, echo = FALSE, message = FALSE, warning=FALSE}
15 library(dendextend)
16 library(knitr)
17 knitr::opts_chunk$set(
18 cache = TRUE,
19 dpi = 75,
20 fig.width = 6, fig.height = 6,
21 # dev = "svg",
22 # comment = "#>",
23 tidy = FALSE)
24
25 # https://stackoverflow.com/questions/24091735/why-pandoc-does-not-retrieve-the-image-file
26 # < ! -- rmarkdown v1 -->
27
28 ```
29
30
31 ## Introduction
32
33 This document demonstrates, on several famous data sets, how the _dendextend_ R package can be used to enhance Hierarchical Cluster Analysis (through better visualization and sensitivity analysis).
34
35
36
37 ## iris - Edgar Anderson's Iris Data
38
39 ### Background
40
41 > The famous (Fisher's or Anderson's) iris data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica. (from `?iris`)
42
43
44
45 The [Iris flower data set](https://en.wikipedia.org/wiki/Iris_flower_data_set) is fun for learning supervised classification algorithms, and is known as a difficult case for unsupervised learning. This is easily seen through the following Scatter Plot Matrix (SPLOM):
46
47 Define variables:
48
49 ```{r}
50 iris <- datasets::iris
51 iris2 <- iris[,-5]
52 species_labels <- iris[,5]
53 library(colorspace) # get nice colors
54 species_col <- rev(rainbow_hcl(3))[as.numeric(species_labels)]
55 ```
56
57 SPLOM:
58
59 ```{r, fig.width=9, fig.height=9, fig.show='hold'}
60 # Plot a SPLOM:
61 pairs(iris2, col = species_col,
62 lower.panel = NULL,
63 cex.labels=2, pch=19, cex = 1.2)
64
65 # Add a legend
66 par(xpd = TRUE)
67 legend(x = 0.05, y = 0.4, cex = 2,
68 legend = as.character(levels(species_labels)),
69 fill = unique(species_col))
70 par(xpd = NA)
71
72 ```
73
74 We can see that the *Setosa* species are distinctly different from *Versicolor* and *Virginica* (they have lower petal length and width). But *Versicolor* and *Virginica* cannot easily be separated based on measurements of their sepal and petal width/length.
75
76 The same conclusion can be made by looking at the parallel coordinates plot of the data:
77
78 ```{r, fig.height=3}
79 # http://blog.safaribooksonline.com/2014/03/31/mastering-parallel-coordinate-charts-r/
80 par(las = 1, mar = c(4.5, 3, 3, 2) + 0.1, cex = .8)
81 MASS::parcoord(iris2, col = species_col, var.label = TRUE, lwd = 2)
82
83 # Add Title
84 title("Parallel coordinates plot of the Iris data")
85 # Add a legend
86 par(xpd = TRUE)
87 legend(x = 1.75, y = -.25, cex = 1,
88 legend = as.character(levels(species_labels)),
89 fill = unique(species_col), horiz = TRUE)
90 par(xpd = NA)
91
92 ```
93
94
95 ### The 3 clusters from the "complete" method vs the real species category
96
97
98 The default hierarchical clustering method in `hclust` is "complete". We can visualize the result of running it by turning the object to a dendrogram and making several adjustments to the object, such as: changing the labels, coloring the labels based on the real species category, and coloring the branches based on cutting the tree into three clusters.
99
100
101
102
103 ```{r, fig.height = 10, fig.width=7}
104
105 d_iris <- dist(iris2) # method="man" # is a bit better
106 hc_iris <- hclust(d_iris, method = "complete")
107 iris_species <- rev(levels(iris[,5]))
108
109 library(dendextend)
110 dend <- as.dendrogram(hc_iris)
111 # order it the closest we can to the order of the observations:
112 dend <- rotate(dend, 1:150)
113
114 # Color the branches based on the clusters:
115 dend <- color_branches(dend, k=3) #, groupLabels=iris_species)
116
117 # Manually match the labels, as much as possible, to the real classification of the flowers:
118 labels_colors(dend) <-
119 rainbow_hcl(3)[sort_levels_values(
120 as.numeric(iris[,5])[order.dendrogram(dend)]
121 )]
122
123 # We shall add the flower type to the labels:
124 labels(dend) <- paste(as.character(iris[,5])[order.dendrogram(dend)],
125 "(",labels(dend),")",
126 sep = "")
127 # We hang the dendrogram a bit:
128 dend <- hang.dendrogram(dend,hang_height=0.1)
129 # reduce the size of the labels:
130 # dend <- assign_values_to_leaves_nodePar(dend, 0.5, "lab.cex")
131 dend <- set(dend, "labels_cex", 0.5)
132 # And plot:
133 par(mar = c(3,3,3,7))
134 plot(dend,
135 main = "Clustered Iris data set
136 (the labels give the true flower species)",
137 horiz = TRUE, nodePar = list(cex = .007))
138 legend("topleft", legend = iris_species, fill = rainbow_hcl(3))
139
140 #### BTW, notice that:
141 # labels(hc_iris) # no labels, because "iris" has no row names
142 # is.integer(labels(dend)) # this could cause problems...
143 # is.character(labels(dend)) # labels are no longer "integer"
144 ```
145
146 The same can be presented in a circular layout:
147
148 ```{r, fig.width=7, fig.height=7}
149 # Requires that the circlize package will be installed
150 par(mar = rep(0,4))
151 circlize_dendrogram(dend)
152 ```
153
154
155 These visualizations easily demonstrates how the separation of the hierarchical clustering is very good with the "Setosa" species, but misses in labeling many "Versicolor" species as "Virginica".
156
157 The hanging of the tree also helps to locate extreme observations. For example, we can see that observation "virginica (107)" is not very similar to the Versicolor species, but still, it is among them. Also, "Versicolor (71)" is located too much "within" the group of Virginica flowers.
158
159 ```{r, echo=FALSE, eval=FALSE}
160 # some_col_func <- function(n, top_color = "red4") {
161 # seq_cols <- c("#F7FCFD", "#E0ECF4", "#BFD3E6", "#9EBCDA", "#8C96C6", "#8C6BB1",
162 # "#88419D", "#810F7C")
163 # c(colorRampPalette(seq_cols, bias =1)(n-1), top_color)
164 # }
165
166 ```
167
168
169
170
171
172
173
174
175 We can also explore the data using a heatmap. The rows are ordered based on the order of the hierarchical clustering (using the "complete" method). The colored bar indicates the species category each row belongs to. The color in the heatmap indicates the length of each measurement (from light yellow to dark red).
176
177 In the heatmap we also see how the Setosa species has low petal values (in light yellow), but it is very difficult to see any clear distinction between the other two species.
178
179
180 ```{r, fig.width=9, fig.height=9}
181
182 some_col_func <- function(n) rev(colorspace::heat_hcl(n, c = c(80, 30), l = c(30, 90), power = c(1/5, 1.5)))
183
184 # scaled_iris2 <- iris2 %>% as.matrix %>% scale
185 # library(gplots)
186 gplots::heatmap.2(as.matrix(iris2),
187 main = "Heatmap for the Iris data set",
188 srtCol = 20,
189 dendrogram = "row",
190 Rowv = dend,
191 Colv = "NA", # this to make sure the columns are not ordered
192 trace="none",
193 margins =c(5,0.1),
194 key.xlab = "Cm",
195 denscol = "grey",
196 density.info = "density",
197 RowSideColors = rev(labels_colors(dend)), # to add nice colored strips
198 col = some_col_func
199 )
200
201
202 ```
203
204 We can get an interactive heatmap by using the `heatmaply` package/function: (code is not evaluated in order to keep the HTML size)
205
206 ```{r, cache = FALSE, eval = FALSE}
207 heatmaply::heatmaply(as.matrix(iris2),
208 dendrogram = "row",
209 Rowv = dend)
210 ```
211
212
213
214
215 ### Similarity/difference between various clustering algorithms
216
217
218 We may ask ourselves how many different results we could get if we would use different clustering algorithms (`hclust` has 8 different algorithms implemented). For the purpose of this analysis, we will create all 8 hclust objects, and chain them together into a single `dendlist` object (which, as the name implies, can hold a bunch of dendrograms together for the purpose of further analysis).
219
220 ```{r}
221
222 hclust_methods <- c("ward.D", "single", "complete", "average", "mcquitty",
223 "median", "centroid", "ward.D2")
224 iris_dendlist <- dendlist()
225 for(i in seq_along(hclust_methods)) {
226 hc_iris <- hclust(d_iris, method = hclust_methods[i])
227 iris_dendlist <- dendlist(iris_dendlist, as.dendrogram(hc_iris))
228 }
229 names(iris_dendlist) <- hclust_methods
230 iris_dendlist
231 ```
232
233 Next, we can look at the cophenetic correlation between each clustering result using `cor.dendlist`. (This can be nicely plotted using the `corrplot` function from the _corrplot_ package):
234
235 ```{r, fig.width=8, fig.height=8}
236 iris_dendlist_cor <- cor.dendlist(iris_dendlist)
237 iris_dendlist_cor
238 corrplot::corrplot(iris_dendlist_cor, "pie", "lower")
239 ```
240
241
242 From the above figure, we can easily see that most clustering methods yield very similar results, except for the complete method (the default method in `hclust`), which yields a correlation measure of around 0.6.
243
244 The default cophenetic correlation uses pearson's measure, but what if we use the spearman's correlation coefficient?
245
246 ```{r, fig.width=8, fig.height=8}
247 iris_dendlist_cor_spearman <- cor.dendlist(iris_dendlist, method_coef = "spearman")
248 corrplot::corrplot(iris_dendlist_cor_spearman, "pie", "lower")
249 ```
250
251 We can see that the correlations are not so strong, indicating a behavior that is dependent on some items which are very distant from one another having an influence on the pearson's correlation more than that of the spearman's correlation.
252
253
254 To further explore the similarity and difference between the alternative clustering algorithms, we can turn to using the `tanglegram` function (which works for either two `dendrogram`s, or a `dendlist`).
255
256 First, let us see two methods which are very similar: ward.D vs ward.D2. From a first glance, we can see how they both give the same result for the top 3 clusters. However, since they are both ladderizes (i.e.: having their smaller branch rotated to be higher for each node), we can see that their clustering is not identical (due to the crossings).
257
258 ```{r, fig.height=5}
259 # The `which` parameter allows us to pick the elements in the list to compare
260 iris_dendlist %>% dendlist(which = c(1,8)) %>% ladderize %>%
261 set("branches_k_color", k=3) %>%
262 # untangle(method = "step1side", k_seq = 3:20) %>%
263 # set("clear_branches") %>% #otherwise the single lines are not black, since they retain the previous color from the branches_k_color.
264 tanglegram(faster = TRUE) # (common_subtrees_color_branches = TRUE)
265 ```
266
267
268 Next, let us look at two methods which also have a high cophenetic correlation: ward.D vs the average:
269
270 ```{r, fig.height=5}
271 # The `which` parameter allows us to pick the elements in the list to compare
272 iris_dendlist %>% dendlist(which = c(1,4)) %>% ladderize %>%
273 set("branches_k_color", k=2) %>%
274 # untangle(method = "step1side", k_seq = 3:20) %>%
275 tanglegram(faster = TRUE) # (common_subtrees_color_branches = TRUE)
276 ```
277
278 We see that when it comes to the major clusters, the two algorithms perform quite similarly.
279
280 However, how are they doing inside each of the clusters? It is quite difficult to compare the two because of the high value in ward.D. For comparison purposes, we can "rank" the heights of the branches in the two dendrograms (while still preserving their internal order). Next, we can highlight the shared common sub-trees (with different colors), and the distinct edges (with a dashed line):
281
282 ```{r, fig.height=5}
283 # The `which` parameter allows us to pick the elements in the list to compare
284 iris_dendlist %>% dendlist(which = c(1,4)) %>% ladderize %>%
285 # untangle(method = "step1side", k_seq = 3:20) %>%
286 set("rank_branches") %>%
287 tanglegram(common_subtrees_color_branches = TRUE)
288 ```
289
290 We have 39 sub-trees that are identical between the two dendrograms:
291
292 ```{r}
293 length(unique(common_subtrees_clusters(iris_dendlist[[1]], iris_dendlist[[4]]))[-1])
294 # -1 at the end is because we are ignoring the "0" subtree, which indicates leaves that are singletons.
295 ```
296
297 What we can learn from this is that actually the two algorithms seem to give quite different results in the high resolution (higher cuts). However, since both capture the two major clusters (Setosa vs the others), they are considered quite similar by the cophenetic correlation.
298
299 But what about the "complete" method (that got a lower cophenetic correlation than the other methods)? When we compare "complete" vs "average", we can quickly see that in the "complete" method, the splitting of the clusters is much more balanced, and mixes the "Setosa" species with another one. This is probably the cause for the big difference found in the cophenetic correlation between the "complete method" and the other clustering methods:
300
301 ```{r, fig.height=5}
302 iris_dendlist %>% dendlist(which = c(3,4)) %>% ladderize %>%
303 untangle(method = "step1side", k_seq = 2:6) %>%
304 set("branches_k_color", k=2) %>%
305 tanglegram(faster = TRUE) # (common_subtrees_color_branches = TRUE)
306 ```
307
308
309 We can quickly plot all 8 methods to see this phenomenon (i.e.: that "complete" has its smaller cluster larger than it is in all the other clustering methods):
310
311 ```{r, fig.height=15}
312 par(mfrow = c(4,2))
313 for(i in 1:8) {
314 iris_dendlist[[i]] %>% set("branches_k_color", k=2) %>% plot(axes = FALSE, horiz = TRUE)
315 title(names(iris_dendlist)[i])
316 }
317 ```
318
319 It seems that the cophenetic correlation is very biased towards the influence of the main clusters. Another correlation measure to use is the `cor_common_nodes` correlation (giving the proportion of nodes which share the exact same list of labels in both dendrograms). We can also check it out:
320
321 ```{r}
322 iris_dendlist_cor2 <- cor.dendlist(iris_dendlist, method = "common")
323 iris_dendlist_cor2
324 ```
325
326 And plot it:
327
328 ```{r, fig.width=5, fig.height=5}
329 # corrplot::corrplot(iris_dendlist_cor2, "pie", "lower")
330 ```
331
332 This gives us another perspective on our clustering algorithms. We can see that most methods have around 75% common nodes with one another. Centroid and median seem relatively close to one another, as well as ward.D2 and ward.D to one another and to complete, average, and mcquitty (as compared to the other methods).
333
334
335 ### Clustering prediction of the 3 species classes
336
337 Lastly, we would like to see which of the different clustering algorithms came the closest to detecting the 3 flower species (when using a cut of k=3).
338
339 For this purpose, we compare the clustering solution of each algorithm with the real clusters, using the Fowlkes-Mallows Index (also using in the package for the `Bk_plot`). This measure is similar to rand (or rand adjusted) index, and gives a value of 1 when the two clusters confirm, and 0 when they do not.
340
341 ```{r}
342
343 get_ordered_3_clusters <- function(dend) {
344 cutree(dend, k = 3)[order.dendrogram(dend)]
345 }
346
347 dend_3_clusters <- lapply(iris_dendlist, get_ordered_3_clusters)
348
349 compare_clusters_to_iris <- function(clus) {FM_index(clus, rep(1:3, each = 50), assume_sorted_vectors = TRUE)}
350
351 clusters_performance <- sapply(dend_3_clusters, compare_clusters_to_iris)
352 dotchart(sort(clusters_performance), xlim = c(0.7,1),
353 xlab = "Fowlkes-Mallows Index (from 0 to 1)",
354 main = "Perormance of clustering algorithms \n in detecting the 3 species",
355 pch = 19)
356 ```
357
358 We can see that the "median" method did the best, although similar results were achieved by ward.D2, average, ward.D, and mcquitty. However, the complete, centroid, and single method did worse in our case.
359
360
361
362
363 ### Conclusion
364
365 The Iris data set is only 4-dimensional, making it possible to explore using pairs plot (SPLOM) or parallel coordinates plot. It is clear from these that two main clusters are visible, while the separation of the third cluster is difficult.
366
367 In the above analysis, we learned that the complete method fails to do the proper separation of the two main clusters when cut in k=2 (but succeeds in doing it, if moving to k=3 clusters). This is different from all the other 7 methods available in `hclust`, which do succeed in separating the 2 main clusters from the beginning (i.e.: for k=2).
368
369 We also noticed that all clustering algorithms share a relatively high proportion of common nodes (between 75% to 90%).
370
371 Lastly, when it came to trying to separating the flowers into 3 species, the median clustering method did the best, while the single method did the worst in this regard.
372
373 While the Iris data set is well known, I hope the above analysis was able to offer some new perspectives on the performance of the different hierarchical clustering methods.
374
375
376
377 ## khan - Microarray gene expression data set from Khan et al., 2001. Subset of 306 genes.
378
379
380 ### Background
381
382 > Khan contains gene expression profiles of four types of small, round, blue cell tumors of childhood (SRBCT) published by Khan et al. (2001). It also contains further gene annotation retrieved from SOURCE at http://source.stanford.edu/.
383
384 This interesting data set offers two interesting items:
385
386 * train: data.frame of 306 rows and 64 columns. The training data set of 64 arrays and 306 gene expression values
387 * test: data.frame, of 306 rows and 25 columns. The test data set of 25 arrays and 306 genes expression values
388
389 This way we can create a hierarchical clustering on the 306 genes expression values on the train and the test data and compare the two to see the stability of the results.
390
391 We define the variables:
392
393 ```{r}
394 train <- dendextend::khan$train
395 test <- dendextend::khan$test
396 ```
397
398 And create the dendrograms:
399
400 ```{r}
401 d_train <- train %>% dist %>% hclust %>% as.dendrogram
402 d_test <- test %>% dist %>% hclust %>% as.dendrogram
403 d_train_test <- dendlist(train = d_train, test = d_test)
404 ```
405
406
407 ### Comparing the train vs test dendrograms
408
409 Using a cophenetic correlation, we can see the two trees have some similarity (0.57):
410
411 ```{r}
412 d_train_test %>% cor.dendlist
413 ```
414
415 However, when looking at the cophenetic correlation with the spearman correlation coefficiant, the value is lower (0.49) indicating that some of the similarity is due to a small number of items, distant from the others, which are correlated similarly in the two trees:
416
417 ```{r}
418 d_train_test %>% cor.dendlist(method_coef = "spearman")
419 ```
420
421 We may ask at which level of cutting the dendrogram we get the "best" level of similarity. For this we may turn to the Bk plot. The plots shows us that at around 7 clusters the groups in the two are starting to look significantly similar. (Note that significantly does not mean substantially)
422
423 ```{r}
424 Bk_plot(d_train, d_test, k = 2:30, xlim = c(2,30))
425 ```
426
427 Next, we compare the results with a tanglegram. We make sure to color the connecting line with the colors of the branches of the train (left) dendrogram. This can help us see which patterns are somewhat preserved between the two trees.
428
429 ```{r, fig.width=8, fig.height=5}
430 pre_tang_d_train_test <- d_train_test %>% ladderize %>% # untangle %>%
431 set("branches_k_color", k = 7)
432 train_branches_colors <- get_leaves_branches_col(pre_tang_d_train_test$train)
433 pre_tang_d_train_test %>% tanglegram(fast = TRUE, color_lines = train_branches_colors)
434 ```
435
436 We can see that the top most (small) cluster is somewhat preserved between the two trees. However, a large spaghetti-like tangle of lines is indicating that the two trees are far from being identical.
437
438 ```{r, echo = FALSE}
439 # dput(d_train_test_common)
440 d_train_test_common <- structure(list(train = structure(list(structure(list(structure(171L, label = "491565", members = 1L, height = 0, leaf = TRUE),
441 structure(178L, label = "505491", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 7.1369942952198),
442 structure(list(structure(list(structure(8L, label = "283315", members = 1L, height = 0, leaf = TRUE),
443 structure(9L, label = "897177", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 2.55936539399907),
444 structure(list(structure(list(structure(106L, label = "345553", members = 1L, height = 0, leaf = TRUE),
445 structure(112L, label = "307660", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 5.17910461856101),
446 structure(list(structure(list(structure(268L, label = "504791", members = 1L, height = 0, leaf = TRUE),
447 structure(306L, label = "782503", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 4.27052507661529),
448 structure(list(structure(list(structure(246L, label = "81518", members = 1L, height = 0, leaf = TRUE),
449 structure(290L, label = "280837", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 1.37572388944875),
450 structure(list(structure(list(structure(266L, label = "866694", members = 1L, height = 0, leaf = TRUE),
451 structure(277L, label = "811956", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 3.31301518861595),
452 structure(list(structure(273L, label = "842918", members = 1L, height = 0, leaf = TRUE),
453 structure(274L, label = "626555", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 2.71864544948399)), members = 4, midpoint = 1.5, height = 6.35097701381449)), members = 6, midpoint = 2, height = 8.7097033164167)), members = 8, midpoint = 2.25, height = 9.23807936424017)), members = 10, midpoint = 2.375, height = 11.6573350998416)), members = 12, midpoint = 2.4375, height = 17.5620766260713)), members = 14, midpoint = 2.46875, height = 30.2363452779928, class = "dendrogram"),
454 test = structure(list(structure(list(structure(list(structure(171L, label = "491565", members = 1L, height = 0, leaf = TRUE),
455 structure(178L, label = "505491", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 3.96666017450449),
456 structure(list(structure(list(structure(list(structure(268L, label = "504791", members = 1L, height = 0, leaf = TRUE),
457 structure(306L, label = "782503", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 2.31497882927685),
458 structure(list(structure(list(structure(266L, label = "866694", members = 1L, height = 0, leaf = TRUE),
459 structure(277L, label = "811956", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 1.75475236429532),
460 structure(list(structure(273L, label = "842918", members = 1L, height = 0, leaf = TRUE),
461 structure(274L, label = "626555", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 1.34617375921535)), members = 4, midpoint = 1.5, height = 2.76465021476497)), members = 6, midpoint = 2, height = 4.52927251774499),
462 structure(list(structure(list(structure(246L, label = "81518", members = 1L, height = 0, leaf = TRUE),
463 structure(290L, label = "280837", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 0.714433271901582),
464 structure(list(structure(8L, label = "283315", members = 1L, height = 0, leaf = TRUE),
465 structure(9L, label = "897177", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 1.71895552589356)), members = 4, midpoint = 1.5, height = 6.44143803354499)), members = 10, midpoint = 4.75, height = 7.736516720075)), members = 12, midpoint = 3.625, height = 11.0066972375913),
466 structure(list(structure(106L, label = "345553", members = 1L, height = 0, leaf = TRUE),
467 structure(112L, label = "307660", members = 1L, height = 0, leaf = TRUE)), members = 2L, midpoint = 0.5, height = 3.6486307417989)), members = 14, midpoint = 8.0625, height = 18.2331742971431, class = "dendrogram")), class = "dendlist", .Names = c("train",
468 "test"))
469 ```
470
471 If we look only at subtrees of the two dendrograms so that they include only genes that are clustered with genes in both trees, we get only 14 genes (while the original trees had 306 genes). We can see how we have several groups of pairs of genes, and one group with four genes clustered together in both trees:
472
473 ```{r}
474 # This was calculated before
475 # d_train_test_common <- d_train_test %>% prune_common_subtrees.dendlist
476 # d_train_test_common
477 d_train_test_common %>% untangle %>% tanglegram(common_subtrees_color_branches = TRUE)
478 ```
479
480 Trees' sizes:
481
482 ```{r}
483 d_train_test %>% nleaves
484 d_train_test_common %>% nleaves
485 ```
486
487
488
489 ### Conclusion
490
491 To conclude: we see that the clustering algorithm resulted in trees which are significantly similar in both the training and the test data sets beyond chance, but that this similarity is restricted to only a very small proportion of genes.
492
493
494 ## votes.repub - Votes for Republican Candidate in Presidential Elections
495
496
497 ### Background
498
499 > This is a data frame with the percentage of votes given to the republican candidate in presidential elections from 1856 to 1976. Rows represent the 50 states, and columns the 31 elections.
500
501
502 > Source: S. Peterson (1973): A Statistical History of the American Presidential Elections. New York: Frederick Ungar Publishing Co.
503 Data from 1964 to 1976 is from R. M. Scammon, American Votes 12, Congressional Quarterly.
504
505
506 Define variables:
507
508 ```{r}
509 votes.repub <- cluster::votes.repub
510 ```
511
512 These data can be visualized using a (costumed made) parallel coordinates plot:
513
514
515 ```{r, fig.height=5}
516 years <- as.numeric(gsub("X", "", colnames(votes.repub)))
517
518 par(las = 2, mar = c(4.5, 3, 3, 2) + 0.1, cex = .8)
519 # MASS::parcoord(votes.repub, var.label = FALSE, lwd = 1)
520 matplot(1L:ncol(votes.repub), t(votes.repub), type = "l", col = 1, lty = 1,
521 axes = F, xlab = "", ylab = "")
522 axis(1, at = seq_along(years), labels = years)
523 axis(2)
524 # Add Title
525 title("Votes for Republican Candidate\n in Presidential Elections \n (each line is a country - over the years)")
526 ```
527
528
529 ### Heatmap
530
531 This is a nice example when the parallel coordinates plot has some serious limitations: it does not help us detect the states, we fail to see the missing value patterns, and it is tricky to see clusters in general (due to the large number of threads).
532
533 For these data, it can be quite helpful to see a heatmap of the votes across the years. The ordering of the rows is tricky. First, the distance of the vectors (later used for the clustering) should be done after transformation (since we are dealing with proportion of votes). In this case, I used the arcsin transformation (a logit transformation could also work, but the arcsin is safer for dealing with 0/1 observations). But given the clusters, we wish to order the leaves (as much as possible), in order to take into account the missing value clusterings. So we, in fact, have two clusters, one for the raw values, and another for the "shadow matrix" (i.e.: the matrix with 0/1, indicating if a value was missing or not).
534
535
536
537
538
539
540 ```{r, fig.width=9, fig.height=9}
541 arcsin_transformation <- function(x) asin(x/100)
542
543 dend_NA <- votes.repub %>% is.na %>%
544 dist %>% hclust %>% as.dendrogram %>% ladderize
545
546 dend <- votes.repub %>% arcsin_transformation %>%
547 dist %>% hclust(method = "com") %>% as.dendrogram %>%
548 rotate(labels(dend_NA)) %>%
549 color_branches(k=3)
550
551 # some_col_func <- function(n) rev(colorspace::heat_hcl(n, c = c(80, 30), l = c(30, 90), power = c(1/5, 1.5)))
552 some_col_func <- colorspace::diverge_hcl
553
554
555 # par(mar = c(3,3,3,3))
556 # library(gplots)
557 gplots::heatmap.2(as.matrix(votes.repub),
558 main = "Votes for\n Republican Presidential Candidate\n (clustered using complete)",
559 srtCol = 60,
560 dendrogram = "row",
561 Rowv = dend,
562 Colv = "NA", # this to make sure the columns are not ordered
563 trace="none",
564 margins =c(3,6),
565 key.xlab = "% Votes for Republican\n Presidential Candidate",
566 labCol = years,
567 denscol = "grey",
568 density.info = "density",
569 col = some_col_func
570 )
571 # RowSideColors = rev(labels_colors(dend)), # to add nice colored strips
572 ```
573
574
575 How much of a difference would we get if we used another clustering algorithm?
576
577 We first calculate the clustering using 8 different methods:
578
579 ```{r}
580
581 hclust_methods <- c("ward.D", "single", "complete", "average", "mcquitty",
582 "median", "centroid", "ward.D2")
583 votes.repub_dendlist <- dendlist()
584
585 for(i in seq_along(hclust_methods)) {
586 tmp_dend <- votes.repub %>% arcsin_transformation %>% dist %>% hclust(method = hclust_methods[i]) %>% as.dendrogram
587 votes.repub_dendlist <- dendlist(votes.repub_dendlist, tmp_dend)
588 }
589 names(votes.repub_dendlist) <- hclust_methods
590 # votes.repub_dendlist
591 ```
592
593 Next, we can look at the cophenetic correlation between each clustering result using `cor.dendlist`. (This can be nicely plotted using the `corrplot` function from the _corrplot_ package):
594
595 ```{r, fig.width=8, fig.height=8}
596 corrplot::corrplot(cor.dendlist(votes.repub_dendlist), "pie", "lower")
597 ```
598
599 We see that the "complete" method is somewhat similar to the ward.D/ward.D2 methods, but there is less similarity with the other methods. We can see that the methods "average", "mcquitty" and "median", all give somewhat similar results. So by using "average", we will see an alternative presentation that represents (in a sense) three other clustering solutions.
600
601 We can look at the heatmap of the "average" method. However, as you can see, it is not very helpful in seeing the difference between the two clustering solutions.
602
603 ```{r, echo=FALSE, fig.width=9, fig.height=9}
604 arcsin_transformation <- function(x) asin(x/100)
605
606 dend_NA <- votes.repub %>% is.na %>%
607 dist %>% hclust %>% as.dendrogram %>% ladderize
608
609 dend <- votes.repub %>% arcsin_transformation %>%
610 dist %>% hclust(method = "ave") %>% as.dendrogram %>%
611 rotate(labels(dend_NA)) %>%
612 color_branches(k=3)
613
614 # some_col_func <- function(n) rev(colorspace::heat_hcl(n, c = c(80, 30), l = c(30, 90), power = c(1/5, 1.5)))
615 some_col_func <- colorspace::diverge_hcl
616
617
618 # par(mar = c(3,3,3,3))
619 # library(gplots)
620 gplots::heatmap.2(as.matrix(votes.repub),
621 main = "Votes for\n Republican Presidential Candidate\n (clustered using average)",
622 srtCol = 60,
623 dendrogram = "row",
624 Rowv = dend,
625 Colv = "NA", # this to make sure the columns are not ordered
626 trace="none",
627 margins =c(3,6),
628 key.xlab = "% Votes for Republican\n Presidential Candidate",
629 labCol = years,
630 denscol = "grey",
631 density.info = "density",
632 col = some_col_func
633 )
634 # RowSideColors = rev(labels_colors(dend)), # to add nice colored strips
635 ```
636
637
638 Let's look at the tanglegram of the two methods to get a better insight into the differences between the two:
639
640
641 ```{r, echo=FALSE}
642
643 ord1 <- c("North Carolina", "Virginia", "Tennessee", "Kentucky", "Maryland",
644 "Delaware", "Oklahoma", "Missouri", "New Mexico", "Oregon", "Washington",
645 "California", "West Virginia", "Hawaii", "Nevada", "Arizona",
646 "Montana", "Idaho", "Wyoming", "Utah", "Colorado", "Alaska",
647 "Illinois", "New York", "Indiana", "Ohio", "Connecticut", "New Hampshire",
648 "New Jersey", "Pennsylvania", "Iowa", "South Dakota", "North Dakota",
649 "Wisconsin", "Minnesota", "Nebraska", "Kansas", "Maine", "Michigan",
650 "Massachusetts", "Rhode Island", "Vermont", "Alabama", "Georgia",
651 "Louisiana", "Arkansas", "Florida", "Texas", "South Carolina",
652 "Mississippi")
653
654 ord2 <- c("North Carolina", "Virginia", "Tennessee", "Oklahoma", "Kentucky",
655 "Maryland", "Delaware", "Missouri", "New Mexico", "West Virginia",
656 "Oregon", "Washington", "California", "Nevada", "Arizona", "Montana",
657 "Colorado", "Alaska", "Idaho", "Wyoming", "Utah", "Hawaii", "Maine",
658 "Illinois", "New York", "New Jersey", "Indiana", "Ohio", "Connecticut",
659 "New Hampshire", "Pennsylvania", "Michigan", "Iowa", "South Dakota",
660 "North Dakota", "Wisconsin", "Minnesota", "Massachusetts", "Rhode Island",
661 "Nebraska", "Kansas", "Vermont", "Alabama", "Georgia", "Louisiana",
662 "Arkansas", "Florida", "Texas", "South Carolina", "Mississippi"
663 )
664
665 # dput(lapply(dends, labels)[[2]])
666
667 ```
668
669
670 ```{r}
671 dend_com <- votes.repub %>% arcsin_transformation %>%
672 dist %>% hclust(method = "com") %>% as.dendrogram %>%
673 rotate(labels(dend_NA)) %>%
674 color_branches(k=3) # %>% ladderize
675 dend_ave <- votes.repub %>% arcsin_transformation %>%
676 dist %>% hclust(method = "ave") %>% as.dendrogram %>%
677 rotate(labels(dend_NA)) %>%
678 color_branches(k=3) # %>% ladderize
679
680 # The orders were predefined after using untangle("step2side")
681 # They are omitted here to save running time.
682 dend_com <- rotate(dend_com, ord1)
683 dend_ave <- rotate(dend_ave, ord2)
684
685 dends <- dendlist(complete = dend_com, average = dend_ave) # %>% untangle("step2side")
686 dends %>% tanglegram(margin_inner = 7)
687
688 ```
689
690 We see that the two clusterings give similar results for: "Alabama", "Georgia", "Louisiana", "Arkansas", "Florida", "Texas", "South Carolina", "Mississippi".
691
692 There are also several other sub-trees which are identical between the two methods. The biggest difference lies in several "rouge" states that are placed differently in the two clustering algorithms. They are: Vermont, Michigan, Maine, Hawaii, New Jersey, West Virginia, and Oklahoma.
693
694
695 A better understanding of the data requires a much more in-depth historical perspective than is within the scope of the current analysis.
696
697
698
699 ## animals - Attributes of Animals
700
701
702 ### Background
703
704 > This data set considers 6 binary attributes for 20 animals.
705
706 > see Struyf, Hubert & Rousseeuw (1996), in agnes.
707
708
709
710
711 Define variables:
712
713 ```{r}
714 animals <- cluster::animals
715
716 colnames(animals) <- c("warm-blooded",
717 "can fly",
718 "vertebrate",
719 "endangered",
720 "live in groups",
721 "have hair")
722 ```
723
724
725 ### Heatmap
726
727 This is a good example for using a heatmap + colored branches.
728
729
730 ```{r, fig.width=9, fig.height=9}
731
732 dend_r <- animals %>% dist(method = "man") %>% hclust(method = "ward.D") %>% as.dendrogram %>% ladderize %>%
733 color_branches(k=4)
734
735 dend_c <- t(animals) %>% dist(method = "man") %>% hclust(method = "com") %>% as.dendrogram %>% ladderize%>%
736 color_branches(k=3)
737
738
739 # some_col_func <- function(n) rev(colorspace::heat_hcl(n, c = c(80, 30), l = c(30, 90), power = c(1/5, 1.5)))
740 # some_col_func <- colorspace::diverge_hcl
741 # some_col_func <- colorspace::sequential_hcl
742 some_col_func <- function(n) (colorspace::diverge_hcl(n, h = c(246, 40), c = 96, l = c(65, 90)))
743
744
745
746 # par(mar = c(3,3,3,3))
747 # library(gplots)
748 gplots::heatmap.2(as.matrix(animals-1),
749 main = "Attributes of Animals",
750 srtCol = 35,
751 Rowv = dend_r,
752 Colv = dend_c,
753 trace="row", hline = NA, tracecol = "darkgrey",
754 margins =c(6,3),
755 key.xlab = "no / yes",
756 denscol = "grey",
757 density.info = "density",
758 col = some_col_func
759 )
760
761 ```
762
763 We see that we have several groups of variables: the "can fly" and "endangered" (which usually are both "no"), the "have hair", and the "warm-blooded", "vertebrate", and "live in groups".
764
765 We see that within the animals there are (roughly!) the following 4 groups:
766
767 1. The cold-blooded non-vertebrates, which are mostly not endangered.
768 2. The warm-blooded vertebrates, which live in groups, have hair, cannot fly, and mostly are not endangered.
769 3. The cold-blooded vertebrates, without hair, cannot fly, and are not endangered.
770 4. The (mostly) warm-blooded vertebrates, without hair, some can fly, and some are endangered.
771
772
773 How much of a difference would we get if we used another clustering algorithm?
774
775 We first calculate the clustering using 8 different methods:
776
777 ```{r}
778
779 hclust_methods <- c("ward.D", "single", "complete", "average", "mcquitty",
780 "median", "centroid", "ward.D2")
781 animals_dendlist <- dendlist()
782
783 for(i in seq_along(hclust_methods)) {
784 tmp_dend <- animals %>% dist(method = "man") %>%
785 hclust(method = hclust_methods[i]) %>% as.dendrogram
786 animals_dendlist <- dendlist(animals_dendlist, tmp_dend)
787 }
788 names(animals_dendlist) <- hclust_methods
789 # votes.repub_dendlist
790 ```
791
792 Next, we can look at the cophenetic correlation between each clustering result using `cor.dendlist` (This can be nicely plotted using the `corrplot` function from the _corrplot_ package):
793
794 ```{r, fig.width=8, fig.height=8}
795 cophenetic_cors <- cor.dendlist(animals_dendlist)
796 corrplot::corrplot(cophenetic_cors, "pie", "lower")
797 ```
798
799 We see that the different methods (other than ward.D and ward.D2), all give quite different results. So would the above analysis be different if we had used another clustering algorithm?
800
801 For this purpose, we compare the clustering solution of each algorithm with one another, when cut to k=4 clusters, using the Fowlkes-Mallows Index. This measure is similar to rand (or rand adjusted) index, and gives a value of 1 when the two clusters conform, and 0 when they do not:
802
803 ```{r}
804 remove_median <- dendlist(animals_dendlist, which = c(1:8)[-6] )
805 FM_cors <- cor.dendlist(remove_median, method = "FM_index", k = 4)
806 corrplot::corrplot(FM_cors, "pie", "lower")
807 ```
808
809 We removed the "median" method since it did not have k=4 possible. In general, the results seems sensitive to the algorithm used, and the different algorithm methods do not seem to agree with one another (with regards to k=4), so further analyses may be in place in order to decide on which algorithm and interpretation are most appropriate for these data.
810
811
812
813 (Other possible data sets for the future: chorSub, flower, plantTraits, pluton, ruspini, agriculture)