forked from fels-bioinformatics/fels_bioinformatics_meetup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek9_practice_clustering_ANSWERS.Rmd
405 lines (283 loc) · 12.2 KB
/
week9_practice_clustering_ANSWERS.Rmd
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
---
output: html_document
---
```{r setup, include=FALSE}
# load libraries
library(tidyverse)
library(conflicted)
library(viridis)
library(broom)
library(magrittr)
library(nycflights13)
library(Rtsne)
# configure knit settings
knitr::opts_chunk$set(echo = TRUE, fig.width = 6, fig.height = 4)
# resolve package conflicts
filter <- dplyr::filter
select <- dplyr::select
```
# Practice: Clustering
For this week's practice on clustering, we'll use two datasets from previous weeks, the wine and biopsy datasets, to try out all the algorithms discussed this week. Just like in the clustering demo for this week, we'll try to recover a categorical variable from the dataset using clustering.
<br>
Download the tables from the meetup website and stick them in the same folder as your practice R Markdown file for easy read-in.
## wine.csv
In the wine dataset, Cultivar is a categorical variable that we'll try to recover. All the information about the dataset is repeated below (from week 7) for reference.
The wine dataset contains the results of a chemical analysis of wines grown in a specific area of Italy. Three types of wine are represented in the 178 samples, with the results of 13 chemical analyses recorded for each sample. The Type variable has been transformed into a categoric variable. The tidy wine dataset contains the following columns:
- **Cultivar** = the number factor indicating the grape cultivar the wine was made from
- **Alcohol** = the alcohol concentration in the wine sample (g/L)
- **MalicAcid** = the malic acid concentration in the wine sample (g/L)
- **Ash** = the ash concentration in the wine sample (g/L)
- **Magnesium** = the magnesium concentration in the wine sample (g/L)
- **TotalPhenol** = the total amount of all phenol compounds in the wine sample (g/L)
- **Flavanoids** = the concentration of all flavanoids in the wine sample (g/L)
- **NonflavPhenols** = the concentration of all non-flavanoid phenols in the wine sample (g/L)
- **Color** = wine color (spectrophotometric measure?)
<br>
### Read and Wrangle
Read in the wine.csv file in the chunk below and do any wrangling you might need to. Save the file read in as an object to use later.
```{r}
read_csv('wine.csv', col_types = list('Cultivar' = col_factor(levels = c('1', '2', '3')))) -> wine
```
<br>
### Kmeans
#### Plot
Pick two numeric variables and plot a scatterplot colored by Cultivar. You'll use this plot for comparison purposes after running kmeans clustering.
```{r}
ggplot(wine, aes(x = Alcohol, y = Magnesium, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'alcohol (g/L)', y = 'magnesium (g/L)', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
#### Pick Number of Clusters for Kmeans
Using the code from meetup as a guide, pick the best number of clusters for kmeans.
```{r}
# drop the categorial columns from the data
wine %>% select(-Cultivar) -> wine_num
# do a bunch of kmeans
tibble(k = 2:15) %>%
group_by(k) %>%
do(kclust = kmeans(wine_num, .$k)) %>%
glance(kclust) -> wine_kmeans_params
# plot to see the inflection point and pick number of clusters
wine_kmeans_params %>%
mutate(group = 1) %>% # just do this (add a grouping variable) to make geom_line() happy
ggplot(aes(x = as.factor(k), y = tot.withinss, group = group)) +
geom_point(size = 3) +
geom_line(size = 1) +
labs(x = 'Number of Clusters', y = 'Goodness of Fit \n (within cluster sum of squares)') +
theme_classic() +
theme(axis.title = element_text(size = 14))
```
<br>
How many clusters are you going to use? **Write your answer here**
<br>
#### Run Kmeans
Now run `kmeans()` with the number of clusters you selected and plot the cluster results with whichever numeric variables you want.
```{r}
# run the kmeans
wine %>%
select(-Cultivar) %>%
kmeans(4) %>%
augment(wine) -> wine_kmeans4
```
<br>
#### Plot Clustering Results
Using the same numeric variables as above, plot them colored by kmeans cluster.
```{r}
ggplot(wine_kmeans4, aes(x = Alcohol, y = Magnesium, color = .cluster)) +
geom_point(size = 3) +
labs(x = 'alcohol (g/L)', y = 'magnesium (g/L)', color = 'kmeans clusters') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
**Questions to Consider:** Did the kmeans recapitulate the cultivar? Did it seem to find an other underlying pattern/structure in the data?
<br>
### PCA
#### Run a PCA
Run a PCA on the wine dataset and add the PCs back to the wine table with `augment()`. Don't forget to remove categorical columns first!
```{r}
wine %>% select(-Cultivar) %>% prcomp() %>% augment(wine) -> wine_pca
```
<br>
#### Plot Results
Plot PC1 vs PC2 from your results, colored by cultivar
```{r}
ggplot(wine_pca, aes(x = .fittedPC1, y = .fittedPC2, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC1', y = 'PC2', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
It doesn't really discriminate between cultivars does it? Try plotting at least two combinations of other PCs in the chunk below to see if other PCs discriminate between cultivars.
```{r}
# PC1 vs PC3
ggplot(wine_pca, aes(x = .fittedPC1, y = .fittedPC3, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC1', y = 'PC3', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
# PC1 vs PC4
ggplot(wine_pca, aes(x = .fittedPC1, y = .fittedPC3, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC1', y = 'PC3', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
# PC2 vs PC3
ggplot(wine_pca, aes(x = .fittedPC2, y = .fittedPC3, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC2', y = 'PC3', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
# PC2 vs PC4
ggplot(wine_pca, aes(x = .fittedPC2, y = .fittedPC4, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC2', y = 'PC4', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
# PC3 vs PC4
ggplot(wine_pca, aes(x = .fittedPC3, y = .fittedPC4, color = Cultivar)) +
geom_point(size = 3) +
labs(x = 'PC1', y = 'PC3', color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
**Questions to Consider:** Did the PCA create distinct clusters? Do some combinations of PCs create better clusters than others?
<br>
### tSNE
#### Run a tSNE
Run a tSNE on the wine dataset. Don't forget to remove categorical columns first and set `check_duplicates = FALSE`.
```{r}
wine %>% select(-Cultivar) %>% Rtsne(check_duplicates = FALSE) -> wine_tsne
```
Add the tSNE results vectors back to the original data. Remember you can subset them from the tSNE using the `$` operator
```{r}
cbind(wine, wine_tsne$Y) %>% rename(tSNE1 = `1`, tSNE2 = `2`) -> wine_w_tsne
```
Plot your tSNE results colored by cultivar
```{r}
ggplot(wine_w_tsne, aes(x = tSNE1, y = tSNE2, color = Cultivar)) +
geom_point(size = 3) +
labs(color = 'grape cultivar') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br><br>
## biopsy.csv
In the biopsy dataset, outcome is the categorical variable that we'll try to recover. All the information about the dataset is below for reference.
The biopsy dataset contains the results of breast tumor biopsy results from 699 patients from the University of Wisconsin, Madison. Tumor biopsy attributes were measured on a scale of 1-10 and the diagnosis is given in the outcome column. The tidy biopsy dataset contains the following columns:
- **clump_thickness** = biopsy thickness on a scale from 1-10
- **uniform_cell_size** = uniformity of cell size on a scale from 1-10
- **marg_adhesion** = marginal adhesion on a scale from 1-10
- **epithelial_cell_size** = epithelial cell size on a scale from 1-10
- **bare_nuclei** = proportion of cells that are mainly nucleus on a scale from 1-10
- **bland_chromatin** = texture of chromatin on a scale from 1-10
- **normal_nucleoli** = proportion of cells with normal nucleoli on a scale from 1-10
- **mitoses** = proportion of mitoses on a scale from 1-10
- **outcome** = is the biopsy cancerous or not? character, either 'benign' or 'malignant'
<br>
### Read and Wrangle
Read in the biopsy.csv file in the chunk below and do any wrangling you might need to. Save the file read in as an object to use later.
```{r}
read_csv('biopsy.csv') -> biopsy
```
<br>
### Kmeans
#### Plot
Pick two numeric variables and plot a scatterplot colored by outcome. You'll use this plot for comparison purposes after running kmeans clustering.
```{r}
ggplot(biopsy, aes(x = clump_thickness, y = bland_chromatin, color = outcome)) +
geom_point(size = 3, alpha = 0.8) +
labs(x = 'clump thickness', y = 'bland chromatin') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
#### Pick Number of Clusters for Kmeans
Using the code from meetup as a guide, pick the best number of clusters for kmeans.
```{r}
# drop the categorial columns from the data
biopsy %>% select(-outcome) -> biopsy_num
# do a bunch of kmeans
tibble(k = 2:15) %>%
group_by(k) %>%
do(kclust = kmeans(biopsy_num, .$k)) %>%
glance(kclust) -> biopsy_kmeans_params
# plot to see the inflection point and pick number of clusters
biopsy_kmeans_params %>%
mutate(group = 1) %>% # just do this (add a grouping variable) to make geom_line() happy
ggplot(aes(x = as.factor(k), y = tot.withinss, group = group)) +
geom_point(size = 3) +
geom_line(size = 1) +
labs(x = 'Number of Clusters', y = 'Goodness of Fit \n (within cluster sum of squares)') +
theme_classic() +
theme(axis.title = element_text(size = 14))
```
<br>
How many clusters are you going to use? **Write your answer here**
<br>
#### Run Kmeans
Now run `kmeans()` with the number of clusters you selected and plot the cluster results with whichever numeric variables you want.
```{r}
# run the kmeans
biopsy %>%
select(-outcome) %>%
kmeans(6) %>%
augment(biopsy) -> biopsy_kmeans6
```
<br>
#### Plot Clustering Results
Using the same numeric variables as above, plot them colored by kmeans cluster.
```{r}
ggplot(biopsy_kmeans6, aes(x = clump_thickness, y = bland_chromatin, color = .cluster)) +
geom_point(size = 3, alpha = 0.8) +
labs(x = 'clump thickness', y = 'bland chromatin') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
**Questions to Consider:** How did the kmeans do at separating the set into clusters? Why did it turn out the way it did? Why should you have known from the first plot that kmeans was a bad idea?
<br>
### PCA
#### Run a PCA
Run a PCA on the biopsy dataset.
```{r}
biopsy %>% select(-outcome) %>% prcomp() %>% augment(biopsy) -> biopsy_pca
```
<br>
#### Plot Results
Plot PC1 vs PC2 from your results, colored by outcome
```{r}
ggplot(biopsy_pca, aes(x = .fittedPC1, y = .fittedPC2, color = outcome)) +
geom_point(size = 3) +
labs(x = 'PC1', y = 'PC2') +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
**Questions to Consider:** Why did the PCA do better at separating the data than kmeans?
<br>
### tSNE
#### Run a tSNE
Run a tSNE on the biopsy dataset.
```{r}
biopsy %>% select(-outcome) %>% Rtsne(check_duplicates = FALSE) -> biopsy_tsne
```
Add the tSNE results vectors back to the original data.
```{r}
cbind(biopsy, biopsy_tsne$Y) %>% rename(tSNE1 = `1`, tSNE2 = `2`) -> biopsy_w_tsne
```
Plot your tSNE results colored by cultivar
```{r}
ggplot(biopsy_w_tsne, aes(x = tSNE1, y = tSNE2, color = outcome)) +
geom_point(size = 3) +
theme_classic() +
theme(axis.title = element_text(size = 14), legend.title = element_text(size = 14))
```
<br>
**Questions to Consider:** How does the tSNE compare to the PCA? Which cluster method would you pick and why?
<br><br>