The aim of this lab is to acquire basic familiarity with dimension reduction and clustering.
By the end of this lab session, students should be able to
Visualize multi-dimensional data by a pairs plot and a correlation plot.
Perform Principal Component Analysis
Perform t-SNE
Perform \(K\)-means clustering
Perform hierarchical clustering
Please run the R chunks one by one, look at the output and make sure that you understand how it is produced. There will be questions that either require a short answer - then you type your answer right in this document - or modifying R codes - then you modify the R codes here. In either case, you can discuss your work with the lab instructor.
First we will load the libraries and show a sample of the data:.
library(ISLR) # for data
library(tidyverse) # for manipulation with data
library(Rtsne) # for t-SNE.
# The rest of algorithms featured in this lab are a part of base R
# These libraries are built on top of basic tidyverse to provide additional
# visualization functionality
library(GGally) # Plot of the whole dataset
library(ggfortify) # Principal components
library(ggdendro) # Hierarchical clustering
head(Auto)
To get a more comprehensive information about the Auto
dataset, just type ?Auto
in the R command line.
We will first do some simple transformation of the dataset.
origins <- c("American", "European", "Japanese")
names(origins) <- 1:3
A <- Auto %>%
mutate(origin = recode_factor(origin, !!!origins))
head(A)
Here is a pairs plot with the library GGally
:
A %>%
select(-name) %>%
ggpairs()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Sometimes we want to visualize just the correlation matrix. Below is the correlation matrix itself.
A %>%
select_if(is.numeric) %>%
cor %>% round(3)
## mpg cylinders displacement horsepower weight acceleration
## mpg 1.000 -0.778 -0.805 -0.778 -0.832 0.423
## cylinders -0.778 1.000 0.951 0.843 0.898 -0.505
## displacement -0.805 0.951 1.000 0.897 0.933 -0.544
## horsepower -0.778 0.843 0.897 1.000 0.865 -0.689
## weight -0.832 0.898 0.933 0.865 1.000 -0.417
## acceleration 0.423 -0.505 -0.544 -0.689 -0.417 1.000
## year 0.581 -0.346 -0.370 -0.416 -0.309 0.290
## year
## mpg 0.581
## cylinders -0.346
## displacement -0.370
## horsepower -0.416
## weight -0.309
## acceleration 0.290
## year 1.000
Here is how we do it with the library GGally
(it just ignores non-numeric columns, so there is no need to explicitly remove them):
A %>%
ggcorr(palette = "RdBu", label = TRUE)
Column names in our data are very long and it may not be desirable that they overlap with the boxes of the correlation plot. Replace long names with shorter ones before doing the correlation plot. For example, you can rename the column “horsepower” to “hp”.
A %>%
rename(hp = horsepower, ncyl = cylinders,
disp = displacement, acc = acceleration) %>%
ggcorr(palette = "RdBu", label = TRUE)
Now we will do principal component analysis (PCA). Below is the loadings matrix denoted \(\Phi\) in the lecture:
auto_pca <- A %>%
select_if(is.numeric) %>%
prcomp(scale = TRUE)
auto_pca$rotation %>% round(3)
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## mpg 0.398 0.207 0.257 -0.751 -0.341 -0.210 0.092
## cylinders -0.416 0.199 -0.139 -0.477 0.493 0.333 0.432
## displacement -0.429 0.180 -0.100 -0.298 0.057 -0.143 -0.813
## horsepower -0.423 0.085 0.170 0.042 -0.711 0.523 0.064
## weight -0.414 0.225 -0.276 0.108 -0.265 -0.697 0.367
## acceleration 0.285 -0.007 -0.893 -0.121 -0.231 0.224 -0.053
## year 0.230 0.910 0.037 0.302 0.089 0.128 -0.051
The first principal component is associated with general engine size and performance since horsepower, the number of cylinders, displacement, and weight contribute into PC1 in opposite manner than fuel efficiency does. The second is almost entirely assiciated with the year of manufacture, and the third with acceleration, i.e. efficiency of the engine given its power.
Below we visualize our dataset as a scatterplot in terms of the first two principal components. Note that we used the function autoplot
— it works because we loaded the library ggfortify
.
autoplot(auto_pca, loadings = TRUE, loadings.colour = 'blue',
loadings.label = TRUE, loadings.label.size = 3)
If we just want the scores, here is how we extract them:
auto_pca$x %>%
as_tibble %>%
head
As a sanity check, let us print the correlation matrix of the scores to make sure that it is the identity matrix:
auto_pca$x %>%
cor %>%
round(3)
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## PC1 1 0 0 0 0 0 0
## PC2 0 1 0 0 0 0 0
## PC3 0 0 1 0 0 0 0
## PC4 0 0 0 1 0 0 0
## PC5 0 0 0 0 1 0 0
## PC6 0 0 0 0 0 1 0
## PC7 0 0 0 0 0 0 1
Standard deviations of principal components can be extracted directly from the prcomp
object:
auto_pca$sdev %>% round(3)
## [1] 2.238 0.930 0.853 0.429 0.349 0.233 0.188
Variances are
auto_pca$sdev^2 %>% round(3)
## [1] 5.011 0.866 0.728 0.184 0.122 0.054 0.035
Again, for sanity check, let us print the covariance matrix of our scores. It should be a diagonal matrix with variances of principal components along the diagonal:
auto_pca$x %>%
cov %>%
round(3)
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## PC1 5.011 0.000 0.000 0.000 0.000 0.000 0.000
## PC2 0.000 0.866 0.000 0.000 0.000 0.000 0.000
## PC3 0.000 0.000 0.728 0.000 0.000 0.000 0.000
## PC4 0.000 0.000 0.000 0.184 0.000 0.000 0.000
## PC5 0.000 0.000 0.000 0.000 0.122 0.000 0.000
## PC6 0.000 0.000 0.000 0.000 0.000 0.054 0.000
## PC7 0.000 0.000 0.000 0.000 0.000 0.000 0.035
And now we will produce the scree plot that shows variance explained by principal components:
var_exp <- tibble(pc = paste("PC", 1:7, sep = ""),
variance = auto_pca$sdev^2) %>%
mutate(`Variance Explained` = variance / sum(variance)) %>%
mutate(`Cumulative Variance Explained` = cumsum(variance / sum(variance)))
var_exp %>%
pivot_longer(`Variance Explained`:`Cumulative Variance Explained`) %>%
ggplot(aes(pc, value, group = name)) +
geom_point() +
geom_line() +
facet_wrap(~name, scales = "free_y") +
theme_bw() +
lims(y = c(0, 1)) +
labs(y = "Variance",
title = "Variance explained by each principal component")
Plot our data as a scatterplot in principal components 3 and 4 coloured according to the country of origin.
auto_pca$x %>%
as_tibble() %>%
cbind(A) %>%
ggplot(aes(x = PC3, y = PC4, color = origin)) +
geom_point()
Here is how we run t-SNE with default hyperparamter values:
tsne <- Auto %>%
select_if(is.numeric) %>%
as.matrix() %>%
normalize_input %>%
Rtsne()
The output is a list containing all necessary information. The matrix of new features in the lower dimensional space can be extracted from this list as follows:
tsne$Y %>%
as_tibble() %>%
head
## Warning: The `x` argument of `as_tibble.matrix()` must have unique column names if `.name_repair` is omitted as of tibble 2.0.0.
## Using compatibility `.name_repair`.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
Plot the 2-dimensional representation of our data produced by t-SNE with points coloured according to the country of origin.
tsne$Y %>%
as_tibble %>%
cbind(Auto) %>%
ggplot(aes(x = V1, y = V2, color = as.factor(origin))) +
geom_point() + xlab("C1") + ylab("C2") +
theme(legend.position = "none")
Now we will perform \(K\)-means clustering with 3 clusters. Note that we need to explicitly tell R to only use numeric variables.
auto_kclust <- A %>%
select_if(is.numeric) %>%
kmeans(3)
auto_kclust
## K-means clustering with 3 clusters of sizes 90, 180, 122
##
## Cluster means:
## mpg cylinders displacement horsepower weight acceleration year
## 1 14.63556 7.866667 344.1444 157.81111 4236.322 13.46333 74.01111
## 2 29.65167 4.038889 107.2083 77.16667 2222.828 16.33444 76.71111
## 3 20.78934 5.819672 212.6148 105.40164 3162.582 15.90410 76.35246
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 3 1 3 3 3 1 1 1 1 1 3 3 1 3 2 3 3 2 2 2
## 21 22 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39 40 41
## 2 2 2 2 2 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1
## 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
## 1 1 1 1 3 2 3 3 2 2 2 2 2 2 2 2 2 2 2 2
## 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
## 2 1 1 1 1 3 1 1 1 1 2 1 1 1 1 3 2 3 2 2
## 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
## 2 2 2 2 1 3 1 1 1 1 1 1 1 1 1 1 3 3 3 3
## 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
## 3 2 1 1 1 1 3 2 2 2 2 2 2 2 1 1 2 2 2 3
## 122 123 124 125 126 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
## 3 2 3 3 3 3 3 2 2 2 2 1 3 3 1 1 1 1 1 2
## 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 2 2 2 2 2 2 2 2 2 2 3 3 3 3 1 1 1 1 1 1
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
## 1 1 3 3 3 2 2 3 2 3 2 2 3 2 3 2 3 3 2 2
## 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
## 2 2 2 2 2 1 1 1 1 3 3 3 3 2 2 2 2 3 3 3
## 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
## 3 2 2 2 2 3 1 3 3 1 1 1 1 1 2 2 2 2 2 1
## 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
## 1 1 1 3 3 3 3 1 1 1 1 2 3 2 3 2 2 2 2 3
## 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
## 2 3 2 2 2 2 2 3 1 3 3 3 3 3 3 3 3 3 3 3
## 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
## 3 3 3 1 2 2 2 2 2 3 3 2 3 3 3 3 2 2 3 3
## 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
## 3 3 3 1 1 1 1 1 1 3 1 2 2 2 2 3 1 3 3 2
## 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
## 2 2 2 2 2 3 2 2 2 2 2 2 3 3 3 2 3 2 2 2
## 323 324 325 326 327 328 329 330 332 333 334 335 336 338 339 340 341 342 343 344
## 2 3 2 2 2 3 3 2 2 2 3 2 2 2 2 2 2 3 2 2
## 345 346 347 348 349 350 351 352 353 354 356 357 358 359 360 361 362 363 364 365
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 1
## 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
## 3 3 2 2 2 2 2 3 3 2 2 2 2 2 2 2 2 2 2 2
## 386 387 388 389 390 391 392 393 394 395 396 397
## 3 3 2 3 2 2 3 3 2 2 2 3
##
## Within cluster sum of squares by cluster:
## [1] 11029122 12164071 10655835
## (between_SS / total_SS = 88.2 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss" "tot.withinss"
## [6] "betweenss" "size" "iter" "ifault"
Let us check if clusters correspond to countries of origin. We will print the contingency table with the country of origin:
table(A$origin, auto_kclust$cluster)
##
## 1 2 3
## American 89 60 96
## European 1 50 17
## Japanese 0 70 9
Apparently, European and Japanese cars tend to sit in cluster 2 and while American cars are evenly distributed between the three clusters. Now we will plot our clusters on the PC1, PC2 - plane. Note that we changed clusters to character
class to get a nice colour palette:
auto_pca$x %>%
as_tibble %>%
mutate(cluster = auto_kclust$cluster) %>%
mutate(cluster = as.character(cluster)) %>%
ggplot(aes(x = PC1, y = PC2, group = cluster, color = cluster)) +
geom_point()
Note that we did not normalize the data before doing clustering and that is (usually) wrong. Repeat the clustering analysis with normalized data.
Hint: explore the function scale
.
auto_kclust <- A %>%
select_if(is.numeric) %>%
scale %>%
kmeans(3)
auto_pca$x %>%
as_tibble %>%
mutate(cluster = auto_kclust$cluster) %>%
mutate(cluster = as.character(cluster)) %>%
ggplot(aes(x = PC1, y = PC2, group = cluster, color = cluster)) +
geom_point()
Hierarchical clustering is done in two steps:
We construct a matrix of mutual dissimilarities between our data points.
We construct and plot a dendrogram.
For convenience, we will restrict ourselves to just Japanese cars (otherwise, there will be too many datapoints and the plots will become too messy).
First, we compute pairwise dissimilarities and print dissimilarities between the first four points
dd_auto <- A %>%
filter(origin == "Japanese") %>%
select_if(is.numeric) %>%
scale %>%
dist(method = "euclidean")
as.matrix(dd_auto)[1:4, 1:4]
## 15 19 30 32
## 15 0.0000000 1.2290748 1.2592305 0.7520168
## 19 1.2290748 0.0000000 0.2739280 0.9870192
## 30 1.2592305 0.2739280 0.0000000 0.9482459
## 32 0.7520168 0.9870192 0.9482459 0.0000000
Now we will construct our hierarchical clusters and plot them. Note that we had to explicitly specify data labels. If our dataset had row names, then row names would serve as data labels for the hierarchical clustering object. Also note that we rotated the plot. Usually, dendrograms are plotted vertically rather than horizontally.
japan_car_names <- A %>%
filter(origin == "Japanese") %>%
pull(name) %>%
as.character
auto_hclust <- dd_auto %>%
hclust()
auto_hclust$labels <- japan_car_names
ggdendrogram(auto_hclust, rotate = TRUE)
Now let’s say we want to choose 6 clusters. This is done with the function cutree
as follows:
auto_hclust_6clusters <- cutree(auto_hclust, 6)
head(auto_hclust_6clusters)
## toyota corona mark ii datsun pl510 datsun pl510
## 1 1 1
## toyota corona toyota corolla 1200 datsun 1200
## 1 2 2
Now we will plot our Japanese cars on the axes PC1, PC2 coloured according to these 6 hierarchical clusters
auto_pca$x %>%
as_tibble %>%
cbind(A) %>%
filter(origin == "Japanese") %>%
mutate(cluster = as.character(auto_hclust_6clusters)) %>%
ggplot(aes(x = PC1, y = PC2, group = cluster, color = cluster)) +
geom_point()
Do hierarchical clustering with correlation dissimilarity between points instead of Euclidean distance dissimilarity and average linkage instead of complete linkage. Plot the resulting dendrogram.
dd_auto_cor <- A %>%
filter(origin == "Japanese") %>%
select_if(is.numeric) %>%
scale %>%
t %>%
cor
dd_auto_cor <- as.dist(1 - dd_auto_cor)
auto_hclust_cor <- dd_auto_cor %>%
hclust(method = "average")
auto_hclust_cor$labels <- japan_car_names
ggdendrogram(auto_hclust_cor, rotate = TRUE)
A collection of correlation plots with ggcorr
:
Corrplot
library. It has more sophisticated correlation plots, but it is not built on top of tidyverse ecosystem:
How to choose hyperparameters of t-SNE: