-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWeek8_Notes.Rpres
More file actions
636 lines (429 loc) · 25.1 KB
/
Week8_Notes.Rpres
File metadata and controls
636 lines (429 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
Week8 Notes
========================================================
author: Alexander Frieden
date: 3/31/2016
autosize: true
Class Notes
========================================================
* 4/22 we are set to have class, need to reschedule for a different night that week
* Remember homework is due next week
Last Week
========================================================
* We covered trees, what they are
* We experimented with naive approaches in how to cut it up.
K-Means Clustering
========================================================
* K-means clustering is a imple and elegant approach for partitioning a data set into K distinct and disjoint clusters.
* This means none of these elements have any overlap.
* Requires input parameter of number of clusters.
* Algorithm will assign each observation to exactly one of the K clusters.
K-Means Clustering Algorithm
========================================================
Let $C_1,C2,...C_K$ denote the sets containing the indices of the observations in each cluster. THese sets satisfy two properties:
$$
C_1\cup C_2 \cup\,...\,\cup\,C_K = \big\{1,...,n\big\}
$$
In other words, each observation belongs to at least one of the K clusters.
$$
C_k \cap C_{k^\prime} = \emptyset
$$
For all $k\neq k^\prime$. In other words, the clusters are non-overlapping. No observation belongs to more than one cluster.
K-Means Clustering Algorithm (part 2)
========================================================
For instance if the ith observation is in the kth cluster, then $i\in C_k$.
The idea behind K-means clustering is that a *good* clustering is one for which the *winthin-cluster variation* is as small as possible. The within-cluster variation.
The within-cluster variation for cluster $C_k$ is a measure $W(C_k)$ of the amount by which the observations within a cluster differ from each other. Hence we want to solve the problem.
$$
\tag{1}
\min_{C_1,...,C_k}\big\{\sum_{k=1}^{K}W(C_k)\big\}
$$
K-Means Clustering Algorithm (part 3)
========================================================
In other words, this formula says that we want to partition the observations into K clusters such that the total within-cluster variation, summed over all K clusters is as small as possible.
Solving (1) seems reasonable. However, in order to make it actionable we need to define the within-cluster variation. There are many possible ways to define this concept, but by far the most common choice involves *Squared Euclidean distance*. Thus:
$$
\tag{2}
W(C_k) = \frac{1}{|C_k|}\sum_{i,i^\prime\in C_k}\sum_{j=1}^p(x_{ij} - x_{i^\prime j})^2
$$
K-Means Clustering Algorithm (part 4)
========================================================
Where $|C_k|$ denotes the number of observations in the kth cluster. In other words, the within-cluster variation for the kth cluster is the sum of all the pairwise Euclidean distnaces between the observations in the kth cluster divided by the total number of observations in the kth cluster.
Combing (1) and (2) we arrive at the optimization that defines K-mean clustering.
$$
\tag{3}
\min_{C_1,...,C_k}\big\{\sum_{k=1}^{K}\frac{1}{|C_k|}\sum_{i,i^{\prime}\in C_k}\sum_{j=1}^p(x_{ij}-x_{i^{\prime}j})^2\big\}
$$
K-Means Clustering Algorithm (part 5)
========================================================
Some of the figures in this presentation are taken from "An Introduction to Statistical Learning, with applications in R" (Springer, 2013) with permission from the authors: G. James, D. Witten, T. Hastie and R. Tibshirani
The following is a simulated data set with 150 observations in 2-d space. Panels show K-means clustering with different values of K.
K-Means Clustering Algorithm (part 6)
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=1100}
knitr::include_graphics("pictures/10.5.pdf")
```
K-Means Clustering Algorithm (part 7)
========================================================
Now we want to find an algorithm to solve (3).
In general, this is very difficult to solve precisely. There are at most $K^n$ ways to partition n observations into K clusters.
Luckily, K-means clustering algorithm can proivde a local optimum.
K-means Cluster Algorithm Steps
========================================================
1. Randomly assin a number from 1 to $K$ to each of the observations. These serve as initial cluster assignments for the observations .
2. Iterate until the cluster asignments stop changing:
+ For each of the $K$ clusters, compute the cluster centroid. The kth cluster centroid is the vector of the p feature means for the observations in the kth cluster.
+ Assign each observation to the cluster whose centroid is closest (where closest is defined using Euclidean distance)
K-Means Clustering Algorithm (part 8)
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=900}
knitr::include_graphics("pictures/10.6.pdf")
```
K-Means Clustering Algorithm (part 9)
========================================================
The algorithm is guaranteed to decrease the value of objective (3) at each step.
To understand why, the following is illuminating:
$$
\tag{4}
\frac{1}{|C_k|}\sum_{i,i^{\prime}\in C_k}\sum_{j=1}^{p}(x_{ij} - x_{i^{\prime}j})^2 = 2\sum_{i\in C_k}\sum_{j=1}^p(x_ij - \bar{x}_{kj})^2
$$
K-Means Clustering Algorithm (part 10)
========================================================
Here $\,\bar{x}_{kj} = \frac{1}{|C_k|}\sum_{i\in C_k}x_{ij}$ is the mean for feature j in cluster $C_k$.
In step 2a of our algorithm the cluster means for each feature are teh contants that minimize the sum-of-squared deviations.
In step 2b reallocating the observations can only improve (4). This means that as the algorithm is run, the clustering will continue to improve a local optimum is reached.
The name of the algorithm's name comes from that in step 2a the cluster centroids are computed as the mean of the observations assigned to each cluster.
K-Means Clustering Algorithm Notes
========================================================
* Because the K-means algorithm finds a local rather than a global optimum, the results obtained are a function of the initial conditions, in particular the random cluster assignment.
* For this reason it is important to run your algorithm multiple times.
* It turns out that iteratively arriving at the optimum doesn't take very many iterations, thus finding the number of iterations takes some experimenting, as running some of these computations can take a very long time.
* After different initial conditions, one can select the best solution, i.e. one that minimizes (3).
K-Means Clustering Algorithm (part 11)
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=800}
knitr::include_graphics("pictures/10.7.pdf")
```
K-Means Clustering Algorithm (part 12)
========================================================
The previous is K-means clustering with K=3 from slide 10.5, each with different random value input from step 1.
Considerations
========================================================
Some decisions needs to be made when planning on clustering
* Should the observations or features first be standardized in some way? For instance, maybe the variables should be centered to have mean zero and scaled to have standard deviation one.
* In the case of K-means clustering, how many clusters should we look for in the data?
In practice we try several different choices and experiment with parameters for various data sets.
Considerations (part 2)
========================================================
Clustering methods are generally not very good at being robust against perturbations.
For example, suppose we cluster $n$ observaitons and then remove at random one of the clusters. We then perform K-means on our new dataset. We would expect the clusters to be the same minus the one removed.
However, this is not often the case.
K-means in R (part 1)
========================================================
The function **kmeans()** performs K-means clustering in R. We begin a simple simulated example in which there truly are two clusters in the data.
The first twenty five observations have a mean shift relative to the twenty five observations
```{r}
set.seed(2)
x=matrix(rnorm(50*2), ncol=2)
head(x)
```
K-means in R (part 2)
========================================================
Shift the entries
```{r}
x[1:25,1]=x[1:25,1] + 3
x[1:25,2]=x[1:25,2] - 4
```
K-means in R (part 3)
========================================================
Now perform K-means clustering with $K = 2$
```{r}
km.out=kmeans(x,2,nstart=20)
```
K-means in R (part 4)
========================================================
The cluster assignments of the 50 observations are contained in
```{r}
km.out$cluster
```
K-means in R (part 5)
========================================================
The K-means clustering perfectly seperated the observations into two clusters even though we did not supply any group information to **kmeans()**.
K-means in R (part 6)
========================================================
We can plot the data, with each observation colored according to its cluster assignment
```{r}
plot(x,col=(km.out$cluster+1), main="K-Means Clustering Results with K=2", xlab = "", ylab = "", pch=20, cex=2)
```
K-means in R (part 7)
========================================================
Here the we are able to plot this because our data is two dimensional.
If it was greater than two dimensional than we could instead run PCA and look at first two prinicpal components.
K-means in R (part 8)
========================================================
In general we don't know how many clusters, so lets try this with three clusters.
```{r}
set.seed(4)
km.out=kmeans(x,3,nstart=20)
```
K-means in R (part 9)
========================================================
```{r, echo=FALSE}
km.out
```
K-means in R (part 10)
========================================================
While its tough to see, when we set $K=3$, K-means clustering splits up the two clusters.
To run **kmeans()** with multple initial cluster assignments, we use the **nstart** argument.
If the nstart argument is greater than one, then K-means clustering will use multiple random assignments for intiial observation assignment.
K-means in R (part 11)
========================================================
Here we are comparing **nstart=1** vs **nstart=20**.
```{r}
set.seed(3)
km.out=kmeans(x,3,nstart=1)
km.out$tot.withinss
km.out=kmeans(x,3,nstart=20)
km.out$tot.withinss
```
K-means in R (part 12)
========================================================
Note that **km.out$tot.withinss** is the total within-cluster sum of squares which we seek to minimize by performing K-means clustering.
The individual within-cluster sum-of-squares are contaied in the vector **km.out$tot.withinss**
It is *always* recommended to run K-means clustering with a large value of **nstart** such as 20 or 50. Otherwise local optimums that are misrepresenting our data can be obtained.
It is also important to use the **set.seed()** function so that the results are reproducible.
Hierarchical Clustering
========================================================
One potential disadvantage of K-means clustering is that it requires us to pre-specify the number of clusteres K.
Hierarchial clustering is an alternative approach which does not require that we commit to a particular choice of K.
Hierarchial clustering has the added advantage over K-means clustering in that it results in an attractive tree-based representation of the observation, called a *dendrogram*.
Hierarchial Clustering (part 2)
========================================================
We will be looking at bottom up clustering which refers to the idea that the leaves are built first then we combine clusters to get the trunk.
Reading Dendrogram
========================================================
In the following figure, each leaf of the dendrogram respresents one of the 45 observations from our earlier example.
As we move up the tree, some leaves begin to fuse into branches. These correspond to observations that are similar to eacah other.
Fusions further down correspond to groupings that are similar, where as the higher up fusions correspond to groupings that are not similar.
Reading Dendrogram (part 2)
========================================================
We can make this precise:
For any two observations, we can look at the point in the tree where branches containing those two observations are first fused.
The height of the fusion, as measured on the vertical axis, indicates how different the two observations are.
Reading Dendrogram (part 3)
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=1100}
knitr::include_graphics("pictures/10.10.pdf")
```
Reading Dendrogram (part 4)
========================================================
We can read this by seeing that points 5 and 7 are close so they are branched together at a low point.
7 and 9 are far away from each other so they are branched very high, in fact at the trunk.
It is tempting but incorrect to conclude from the figure that observations 9 and 2 are quite similar to each other on the bais that they are located near each other on the dendrogram.
In fact, observation 9 is no more similar to observation 2 than it is to observations 8, 5, and 7.
Reading Dendrogram (part 5)
========================================================
There are $2^{n-1}$ possible reorderings of the denodrogram, where $n$ is the number of leafs.
This is because at each of the $n-1$ points where fusions occur the positions of the two fused branches could be swapped without affecting the meaning of the dendrogram.
We cannot draw conclusions based on their proximity along the horizontal axis. We have to use vertical axis.
Reading Dendrogram (part 6)
========================================================
In order to cluster the dendrogram, we perform a horizontal cut across the tree.
The height of the cut serves the same role as the K in K-means clustering. It controls how many clusters are available.
Reading Dendrogram (part 7)
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=1100}
knitr::include_graphics("pictures/10.9.pdf")
```
Hierarchial Clustering Algorithm part 1
========================================================
We begin by defining some sort of dissiilarity measure between each pair of observations. Most often Euclidean distance is used.
The algorithm proceeds iteratively. Starting out at the bottom of the dendrogram, each of the n observations is treated as its own cluster.
The two clusters that are the most similar to each other are then fused so that there now are $n-1$ clusters.
Do this again for the next two that are most similar. Now there are $n-2$ clusters. The algorithm proceeds in this fashion.
Hierarchial Clustering Algorithm part 2
========================================================
One potential problem: How do we determine if a cluster should be fused to a pair of observations? We need to extend our idea of dissimilarity to groups of observations.
We can do this by developing the notion of **linkage**, which defines the similarity between two groups of observations.
The four most commmon types of linkage: complete, average, single, and centroid. Average, complete, and single linkage are most popular among statisticians.
Hierarchial Clustering Algorithm part 3
========================================================
```{r, echo=FALSE, fig.retina=NULL, out.height=575, out.width=1100}
knitr::include_graphics("pictures/10.12.pdf")
```
Hierarchial Clustering Algorithm Steps
========================================================
1. Begin with $n$ observations and a measure (such as Euclidean) of all ${n \choose 2} = n(n-1)/2$ pairwise dissimilarities. Treat each observation as its own cluster.
2. For $i=n,n-1,...,2$
+ Examine all pairwise inter-cluster dissimilarities among the i clusters and identify the pair of clusters that are least dissimilar. Fuse those two clusters. The dissimilarity between these two clusters indicates the height in the dendrogram at which the fusion should be placed.
+ Computer the new pairwise inter-cluster dissimilarities among the i - 1 remaining clusters.
Complete Linkage
========================================================
Maximal Intercluster dissimilarity.
Compute all pairwise dissimilarities between the observations in cluster A and the observations in cluster B, and record the largest of these dissimilarities.
Single Linkage
========================================================
Minimal intercluster dissimilarity.
Compute all pairwise dissimilarities between the observations in cluster A and the observations in cluster B, and record the smallest of these dissimilarities.
Simple linkage can result in extended, trailing clusters in which single observations are fused one-at-a-time.
Average
========================================================
Mean intercluster dissimilarity.
Compute all pairewise dissimilarities between the observations in cluster A and the observations in cluster B, and record the *average* of these dissimilarities.
Centroid
========================================================
Dissimilarity between the centroid for cluster A (a mean vector of length $p$) and the centroid for cluster B.
Centroid linkage can result in undesriable inversions.
Choice of Dissimilarity Measure
========================================================
Choice of dissimilarity measure has a major role on what the dendrogram looks like and where our data clusters.
We can do things like Euclidean Distance, Correlation-based distance, etc. We will not go into how these are chosen and consequences of this.
Hierarchial Clustering in R (part 1)
========================================================
The **hclust()** function implements hierarchical clustering in R.
In the following example we are going to plot data using this method with the different types of linking.
The **dist()** function is used to to compute a matrix of inter-observation Euclidean distance matrix.
Hierarchial Clustering in R (part 2)
========================================================
Changing the method parameter would allow us to do average or single
```{r}
hc.complete = hclust(dist(x), method="complete")
hc.average = hclust(dist(x), method="average")
hc.single = hclust(dist(x), method="single")
hc.complete
```
Hierarchial Clustering in R (part 3)
========================================================
We can now plot the denodrograms obtained using the plot function.
The numbers at the bottom of the plot identify each observation.
Hierarchial Clustering in R (part 4)
========================================================
```{r, echo=FALSE, fig.height=11, fig.width=24}
par(mfrow=c(1,3))
plot(hc.complete,main = "Complete Linkage", xlab="",sub="",cex=0.9)
plot(hc.average,main = "Average Linkage", xlab="",sub="",cex=0.9)
plot(hc.single,main = "Single Linkage", xlab="",sub="",cex=0.9)
```
Hierarchial Clustering in R (part 5)
========================================================
To determine the cluster labels for each observation associated with a given cut of the denodrogram, we can use **cuttree()**
```{r}
cutree(hc.complete, 2)
cutree(hc.average, 2)
cutree(hc.single, 2)
```
Hierarchial Clustering in R (part 6)
========================================================
From this data, complete and average linkage generally seperate the observations into their correct group.
However, single linkage identifies one point as belonging to its own cluster. When we look to sort into four groups, there are still two singletons.
```{r}
cutree(hc.single,4)
```
Hierarchial Clustering in R (part 7)
========================================================
To scale the variables before HC, we use **scale()**
```{r}
xsc=scale(x)
plot(hclust(dist(xsc),method="complete"), main = "Hierarchial Clustering with Scaled Features")
```
NCI60 Data Example (part 1)
========================================================
Here we are going to use unsupervised methods to analyze genomic data.
NCI60 is a cancer cell line microarray data.
This data consists of 6830 gene expression measurements on 64 cancer cell lines
NCI60 Data Example (part 2)
========================================================
Add our data
```{r}
library(ISLR)
nci.labs=NCI60$labs
nci.data=NCI60$data
```
NCI60 Data Example (part 3)
========================================================
Note that every cell line is labeled with a cancer type.
One analysis we could perform is to run PCA on our data, then type if the groupings have anything to do with type and trying to filter down to get the types.
Since we have done a lot of PCA already, we are not going to do that.
NCI60 Data Example (part 4)
========================================================
We want to use hierarchical clustering to see if observations cluster into distinct types of cancer.
To start, we standardize the variables to have mean zero and standard deviation one. We do this because we don't want to weight any genes heavier than any other ones.
```{r}
sd.data = scale(nci.data)
```
NCI60 Data Example (part 5)
========================================================
We now perform hierarchical clustering using complete, single, and average linkage. Euclidean distance is used as our measure.
NCI60 Data Example (part 6)
========================================================
```{r, echo=FALSE, fig.height=13, fig.width=26}
par(mfrow=c(1,3))
data.dist=dist(sd.data)
plot(hclust(data.dist), labels=nci.labs, main = "Complete Linkage", xlab = "", sub = "", ylab = "")
plot(hclust(data.dist, method = "average"), labels=nci.labs, main = "Average Linkage", xlab = "", sub = "", ylab = "")
plot(hclust(data.dist, method = "single"), labels=nci.labs, main = "Single Linkage", xlab = "", sub = "", ylab = "")
```
NCI60 Data Example (part 7)
========================================================
Choice of linkage affects results obtained.
Typically Single linkage will yield *trailing clusters*. These are very large clusteres onto which individual observations attach one-by-one.
Complete and Average tend to be more balanced clusters. A priori, we would choose go with complete and average linkage.
NCI60 Data Example (part 8)
========================================================
Lets look at a cut of four on our dendrogram.
```{r}
hc.out=hclust(dist(sd.data))
hc.clusters=cutree(hc.out,4)
table(hc.clusters, nci.labs)
```
NCI60 Data Example (part 9)
========================================================
Some patterns emerge: All leukemia cell lines fall in cluster 3.
All breast cancer cell lines are spread out about evenly NOT in cluster 3.
Lets look at the plot next.
NCI60 Data Example (part 10)
========================================================
```{r, echo=FALSE, fig.height=12, fig.width=18}
par(mfrow=c(1,1))
plot(hc.out, labels=nci.labs)
abline(h=139,col = "red")
```
NCI60 Data Example (part 11)
========================================================
The **abline()** function draws a straight line on top of any existing plot.
The argument **h=139** is chosen to give four distinct clusters.
It can be verified that the resulting clusters are the same as the ones we obtained from **cutree(hc.out,4)**
NCI60 Data Example (part 12)
========================================================
Lets take a look at **hc.out**
```{r}
hc.out
```
NCI60 Data Example (part 13)
========================================================
Before we claimed that K-means clustering and hierarchial clustering with the dendrogram cut to obtain the same number of clusteres can yield very different results.
Lets run this exerise using the **NCI60** data set. How does our hierarchical clustering compare to what we get if we perform K-means clustering on $K=4$.
NCI60 Data Example (part 14)
========================================================
```{r}
set.seed(2)
km.out=kmeans(sd.data, 4, nstart=20)
km.clusters=km.out$cluster
table(km.clusters,hc.clusters)
```
NCI60 Data Example (part 15)
========================================================
We see the results using each method are somewhat different. What would this have looked like if these had been the same?
NCI60 Data Example (part 16)
========================================================
```{r}
table(hc.clusters,hc.clusters)
table(km.clusters,km.clusters)
```
NCI60 Data Example (part 17)
========================================================
Also note that cluster 2 in K-means is identical to cluster 3 in hierarchical clustering. However the rest different.
NCI60 Data Example (part 18)
========================================================
Sometimes performing hierarchical clustering on the first few principal component score vectors can give better results.
PCA can remove a lot of the noise from our data and give us a cleaner dendrogram.
Similarly for K-means.