library(tidyverse)
library(tidymodels)
library(factoextra)
library(proxy)
library(ISLR2)Chapter 12 Lab: Unsupervised Learning — Guided Assignment
This lab explores two major topics in unsupervised learning:
- Principal components analysis (PCA) for dimension reduction;
- Clustering using K-means and hierarchical clustering.
Unlike supervised learning, there is no response variable that the methods are trying to predict. The goal is to discover useful structure in the predictors themselves.
The worked examples provide the code patterns needed for the questions. In most questions you will modify or extend code that appears immediately before the question.
This is a modified version of the ISLR2 tidymodels lab for Chapter 12: Unsupervised Learning
Libraries
Principal Components Analysis
PCA on USArrests
The USArrests data contain four quantitative variables for the 50 U.S. states. We first convert the state names from row names into a regular column.
USArrests <- USArrests |>
as_tibble(rownames = "state")
USArrests |> glimpse()Rows: 50
Columns: 5
$ state <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Co…
$ Murder <dbl> 13.2, 10.0, 8.1, 8.8, 9.0, 7.9, 3.3, 5.9, 15.4, 17.4, 5.3, 2.…
$ Assault <int> 236, 263, 294, 190, 276, 204, 110, 238, 335, 211, 46, 120, 24…
$ UrbanPop <int> 58, 48, 80, 50, 91, 78, 77, 72, 80, 60, 83, 54, 83, 65, 57, 6…
$ Rape <dbl> 21.2, 44.5, 31.0, 19.5, 40.6, 38.7, 11.1, 15.8, 31.9, 25.8, 2…
Examine the means of the four quantitative variables.
USArrests |>
select(-state) |>
summarise(across(everything(), mean))# A tibble: 1 × 4
Murder Assault UrbanPop Rape
<dbl> <dbl> <dbl> <dbl>
1 7.79 171. 65.5 21.2
The variables are measured on different scales. Because PCA is sensitive to scale, we standardize the variables before performing PCA.
PCA using prcomp()
USArrests_pca <- USArrests |>
select(-state) |>
prcomp(center = TRUE, scale. = TRUE)
USArrests_pcaStandard deviations (1, .., p=4):
[1] 1.5748783 0.9948694 0.5971291 0.4164494
Rotation (n x k) = (4 x 4):
PC1 PC2 PC3 PC4
Murder -0.5358995 -0.4181809 0.3412327 0.64922780
Assault -0.5831836 -0.1879856 0.2681484 -0.74340748
UrbanPop -0.2781909 0.8728062 0.3780158 0.13387773
Rape -0.5434321 0.1673186 -0.8177779 0.08902432
The scores give the coordinates of the observations in principal-component space.
USArrests_pca |>
tidy(matrix = "scores") |>
slice_head(n = 12)# A tibble: 12 × 3
row PC value
<int> <dbl> <dbl>
1 1 1 -0.976
2 1 2 -1.12
3 1 3 0.440
4 1 4 0.155
5 2 1 -1.93
6 2 2 -1.06
7 2 3 -2.02
8 2 4 -0.434
9 3 1 -1.75
10 3 2 0.738
11 3 3 -0.0542
12 3 4 -0.826
The loadings describe how the original variables contribute to each principal component.
USArrests_pca |>
tidy(matrix = "loadings")# A tibble: 16 × 3
column PC value
<chr> <dbl> <dbl>
1 Murder 1 -0.536
2 Murder 2 -0.418
3 Murder 3 0.341
4 Murder 4 0.649
5 Assault 1 -0.583
6 Assault 2 -0.188
7 Assault 3 0.268
8 Assault 4 -0.743
9 UrbanPop 1 -0.278
10 UrbanPop 2 0.873
11 UrbanPop 3 0.378
12 UrbanPop 4 0.134
13 Rape 1 -0.543
14 Rape 2 0.167
15 Rape 3 -0.818
16 Rape 4 0.0890
Visualize the loadings. These are coefficients, so they should not be interpreted as percentages.
USArrests_pca |>
tidy(matrix = "loadings") |>
ggplot(aes(value, column)) +
facet_wrap(~ PC) +
geom_col() +
labs(
x = "Loading",
y = NULL
) +
theme_minimal()
Question 1: Interpret the first two principal components
Use the loading table and loading plot above.
- Which variables have the largest absolute loadings on PC1?
- Are the PC1 loadings mostly in the same direction or opposite directions?
- Which variable contributes most strongly to PC2?
- Based on the loadings, give a brief interpretation of what high PC1 scores and high PC2 scores tend to represent.
Helpful output: Use tidy(USArrests_pca, matrix = "loadings"). Focus on the sign and magnitude of the loadings for PC1 and PC2. The sign of an entire principal component can be reversed without changing its meaning, so focus mainly on relative directions and sizes.
Variance explained
The eigenvalue information includes the proportion of total variation explained by each component and the cumulative proportion.
USArrests_pca |>
tidy(matrix = "eigenvalues")# A tibble: 4 × 4
PC std.dev percent cumulative
<dbl> <dbl> <dbl> <dbl>
1 1 1.57 0.620 0.620
2 2 0.995 0.247 0.868
3 3 0.597 0.0891 0.957
4 4 0.416 0.0434 1
Create a scree plot.
USArrests_pca |>
tidy(matrix = "eigenvalues") |>
ggplot(aes(PC, percent)) +
geom_col() +
scale_y_continuous(labels = scales::percent) +
scale_x_continuous(breaks = 1:4) +
labs(
x = "Principal component",
y = "Proportion of variance explained"
) +
theme_minimal()
And plot cumulative variance explained.
USArrests_pca |>
tidy(matrix = "eigenvalues") |>
ggplot(aes(PC, cumulative)) +
geom_point(size = 2) +
geom_line() +
scale_y_continuous(labels = scales::percent) +
scale_x_continuous(breaks = 1:4) +
labs(
x = "Number of principal components",
y = "Cumulative variance explained"
) +
theme_minimal()
Question 2: How many components are needed?
Use the variance-explained table and plots above.
- What proportion of the total predictor variation is explained by PC1 alone?
- What cumulative proportion is explained by the first two PCs?
- What is the smallest number of PCs needed to explain at least 80% of the total variation?
- If the goal were dimension reduction, would reducing from four original variables to that number of PCs seem worthwhile? Explain briefly.
Helpful output: The percent column gives the contribution of each individual PC; cumulative gives the contribution of the first \(M\) PCs together.
PCA scores and state locations
augment() gives the PC coordinates for each state.
USArrests_scores <- USArrests_pca |>
augment(data = USArrests)
USArrests_scores |>
select(state, starts_with(".fittedPC")) |>
slice_head(n = 10)# A tibble: 10 × 5
state .fittedPC1 .fittedPC2 .fittedPC3 .fittedPC4
<chr> <dbl> <dbl> <dbl> <dbl>
1 Alabama -0.976 -1.12 0.440 0.155
2 Alaska -1.93 -1.06 -2.02 -0.434
3 Arizona -1.75 0.738 -0.0542 -0.826
4 Arkansas 0.140 -1.11 -0.113 -0.181
5 California -2.50 1.53 -0.593 -0.339
6 Colorado -1.50 0.978 -1.08 0.00145
7 Connecticut 1.34 1.08 0.637 -0.117
8 Delaware -0.0472 0.322 0.711 -0.873
9 Florida -2.98 -0.0388 0.571 -0.0953
10 Georgia -1.62 -1.27 0.339 1.07
Plot the states in the first two principal-component directions.
USArrests_scores |>
ggplot(aes(.fittedPC1, .fittedPC2, label = state)) +
geom_point() +
geom_text(check_overlap = TRUE, nudge_y = 0.08, size = 3) +
labs(
x = "PC1",
y = "PC2"
) +
theme_minimal()
Question 3: Find unusual states in PCA space
Use the PC1-versus-PC2 plot.
- Identify two states that are far from the main concentration of observations.
- Report their approximate PC1 and PC2 scores.
- Use the loadings from Question 1 to explain what their locations suggest about their original crime or urban-population variables.
- Choose one state near the center of the plot and explain why its standardized predictor profile may be less unusual.
Helpful output: Filter USArrests_scores for the states you choose and select state, .fittedPC1, and .fittedPC2. Then connect the signs of the scores to the loading directions from Question 1.
PCA using a recipe
Recipes are useful when PCA is part of a larger modeling or preprocessing workflow.
pca_rec <- recipe(~ ., data = USArrests) |>
step_normalize(all_numeric_predictors()) |>
step_pca(all_numeric_predictors(), id = "pca") |>
prep()Apply the trained recipe to the original data.
pca_rec |>
bake(new_data = NULL) |>
slice_head(n = 8)# A tibble: 8 × 5
state PC1 PC2 PC3 PC4
<fct> <dbl> <dbl> <dbl> <dbl>
1 Alabama -0.976 -1.12 0.440 0.155
2 Alaska -1.93 -1.06 -2.02 -0.434
3 Arizona -1.75 0.738 -0.0542 -0.826
4 Arkansas 0.140 -1.11 -0.113 -0.181
5 California -2.50 1.53 -0.593 -0.339
6 Colorado -1.50 0.978 -1.08 0.00145
7 Connecticut 1.34 1.08 0.637 -0.117
8 Delaware -0.0472 0.322 0.711 -0.873
The same recipe can retain only enough components to explain a chosen fraction of variance.
pca_80_rec <- recipe(~ ., data = USArrests) |>
step_normalize(all_numeric_predictors()) |>
step_pca(all_numeric_predictors(), threshold = 0.80) |>
prep()
pca_80_data <- pca_80_rec |>
bake(new_data = NULL)
pca_80_data |> glimpse()Rows: 50
Columns: 3
$ state <fct> Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connec…
$ PC1 <dbl> -0.97566045, -1.93053788, -1.74544285, 0.13999894, -2.49861285, …
$ PC2 <dbl> -1.12200121, -1.06242692, 0.73845954, -1.10854226, 1.52742672, 0…
Question 4: Change the PCA threshold
Repeat the recipe-based PCA using a threshold of 0.90 instead of 0.80.
- How many PC columns are retained?
- Compare this number with the 0.80-threshold result.
- Explain why increasing the threshold can only keep the same number or more principal components.
- Briefly describe the trade-off between retaining more variance and achieving stronger dimension reduction.
Helpful output: Copy pca_80_rec, change only threshold = 0.80 to threshold = 0.90, then prep() and bake(new_data = NULL). Use glimpse() or select(starts_with("PC")).
K-means Clustering
A simulated data set
We create a two-dimensional data set with two underlying groups. The group labels are shown only for visualization and are not supplied to the clustering algorithm.
set.seed(2)
x_df <- tibble(
V1 = rnorm(50, mean = rep(c(0, 3), each = 25)),
V2 = rnorm(50, mean = rep(c(0, -4), each = 25))
)
x_df |>
mutate(group = rep(c("A", "B"), each = 25)) |>
ggplot(aes(V1, V2, color = group)) +
geom_point(size = 2) +
theme_minimal()
Fit K-means using three clusters.
set.seed(1234)
res_kmeans_3 <- x_df |>
kmeans(centers = 3, nstart = 20)
res_kmeans_3K-means clustering with 3 clusters of sizes 11, 23, 16
Cluster means:
V1 V2
1 2.5355362 -2.48605364
2 0.2339095 0.04414551
3 2.8241300 -5.01221675
Clustering vector:
[1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 1 2 2 2 2 3 1 1 1 3 1 3 3 3 3 1 3 3
[39] 3 1 1 1 3 3 3 3 1 3 3 3
Within cluster sum of squares by cluster:
[1] 14.56698 54.84869 26.98215
(between_SS / total_SS = 76.8 %)
Available components:
[1] "cluster" "centers" "totss" "withinss" "tot.withinss"
[6] "betweenss" "size" "iter" "ifault"
tidy() gives cluster centers and sizes; glance() reports summary information including total within-cluster sum of squares.
res_kmeans_3 |> tidy()# A tibble: 3 × 5
V1 V2 size withinss cluster
<dbl> <dbl> <int> <dbl> <fct>
1 2.54 -2.49 11 14.6 1
2 0.234 0.0441 23 54.8 2
3 2.82 -5.01 16 27.0 3
res_kmeans_3 |> glance()# A tibble: 1 × 4
totss tot.withinss betweenss iter
<dbl> <dbl> <dbl> <int>
1 416. 96.4 320. 2
Visualize the assigned clusters.
res_kmeans_3 |>
augment(data = x_df) |>
ggplot(aes(V1, V2, color = factor(.cluster))) +
geom_point(size = 2) +
labs(color = "Cluster") +
theme_minimal()
Choosing \(K\) with the elbow method
Fit K-means models for \(K=1,\ldots,10\).
set.seed(1234)
multi_kmeans <- tibble(k = 1:10) |>
mutate(
model = map(k, ~ kmeans(x_df, centers = .x, nstart = 20)),
tot_withinss = map_dbl(model, ~ glance(.x)$tot.withinss)
)
multi_kmeans# A tibble: 10 × 3
k model tot_withinss
<int> <list> <dbl>
1 1 <kmeans> 416.
2 2 <kmeans> 127.
3 3 <kmeans> 96.4
4 4 <kmeans> 73.4
5 5 <kmeans> 57.4
6 6 <kmeans> 42.4
7 7 <kmeans> 32.4
8 8 <kmeans> 27.9
9 9 <kmeans> 23.5
10 10 <kmeans> 20.3
Plot total within-cluster sum of squares against \(K\).
multi_kmeans |>
ggplot(aes(k, tot_withinss)) +
geom_point(size = 2) +
geom_line() +
scale_x_continuous(breaks = 1:10) +
labs(
x = "Number of clusters K",
y = "Total within-cluster sum of squares"
) +
theme_minimal()
The main improvement occurs when moving from one to two clusters, with much smaller gains afterward. This is the elbow method.
Question 5: Compare \(K=2\) and \(K=3\)
Extract and compare the fitted K-means models for \(K=2\) and \(K=3\).
- Report total within-cluster sum of squares for each.
- Plot the cluster assignments for both values of \(K\).
- Why must the within-cluster sum of squares decrease when \(K\) increases?
- Even though \(K=3\) has the smaller numerical value, explain why the elbow plot favors \(K=2\) for these data.
Helpful output: Filter multi_kmeans for k == 2 and k == 3, then use pull(model) |> pluck(1) to extract each model. Use augment(data = x_df) for the plots.
Hierarchical Clustering
Fit complete-, average-, and single-linkage hierarchical clustering to the same data.
res_hclust_complete <- x_df |>
dist() |>
hclust(method = "complete")
res_hclust_average <- x_df |>
dist() |>
hclust(method = "average")
res_hclust_single <- x_df |>
dist() |>
hclust(method = "single")Visualize the dendrograms, cutting each into two clusters.
res_hclust_complete |>
fviz_dend(main = "Complete linkage", k = 2)
res_hclust_average |>
fviz_dend(main = "Average linkage", k = 2)
res_hclust_single |>
fviz_dend(main = "Single linkage", k = 2)
Question 6: Compare linkage methods
Compare the three dendrograms.
- Which linkage methods produce two reasonably balanced groups?
- Which method appears most affected by a chaining effect?
- Use
cutree(..., k = 2)to obtain the cluster assignments for complete and single linkage. - How many observations are placed in each cluster under the two methods?
- Explain briefly why different definitions of inter-cluster distance can lead to different dendrograms.
Helpful output: Use table(cutree(res_hclust_complete, k = 2)) and the corresponding code for res_hclust_single.
Why scaling matters
If predictors have very different scales, variables with larger numerical variation can dominate Euclidean distances.
x_df |>
scale() |>
dist() |>
hclust(method = "complete") |>
fviz_dend(k = 2, main = "Complete linkage after scaling")
The modified lab also demonstrates correlation distance, which focuses on similarity of pattern rather than ordinary Euclidean distance.
set.seed(2)
x_corr <- matrix(rnorm(30 * 3), ncol = 3)
x_corr |>
proxy::dist(method = "correlation") |>
hclust(method = "complete") |>
fviz_dend(main = "Correlation distance")
PCA on the NCI60 Data
The NCI60 data contain gene-expression measurements for 64 cancer cell lines. There are thousands of predictors, so this is a natural setting for dimension reduction.
nci60 <- NCI60$data |>
as_tibble(.name_repair = ~ paste0("V_", seq_along(.x))) |>
mutate(label = factor(NCI60$labs)) |>
relocate(label)
nci60 |> dim()[1] 64 6831
Although the labels are available for later interpretation, they are not used when computing the principal components.
nci60_pca_fit <- nci60 |>
select(-label) |>
prcomp(center = TRUE, scale. = TRUE)Add the known cancer-type labels back only for visualization.
nci60_pcs <- bind_cols(
augment(nci60_pca_fit),
nci60 |> select(label)
)Plot PC1 versus PC2.
nci60_pcs |>
ggplot(aes(.fittedPC1, .fittedPC2, color = label)) +
geom_point(size = 2) +
labs(
x = "PC1",
y = "PC2"
) +
theme_minimal() +
theme(legend.position = "bottom")
Plot PC1 versus PC3.
nci60_pcs |>
ggplot(aes(.fittedPC1, .fittedPC3, color = label)) +
geom_point(size = 2) +
labs(
x = "PC1",
y = "PC3"
) +
theme_minimal() +
theme(legend.position = "bottom")
Examine individual and cumulative variance explained.
nci60_pca_fit |>
tidy(matrix = "eigenvalues") |>
ggplot(aes(PC, percent)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = seq(0, 60, by = 5)) +
scale_y_continuous(labels = scales::percent) +
labs(
x = "Principal component",
y = "Proportion of variance explained"
) +
theme_minimal()
nci60_pca_fit |>
tidy(matrix = "eigenvalues") |>
ggplot(aes(PC, cumulative)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = seq(0, 60, by = 5)) +
scale_y_continuous(labels = scales::percent) +
labs(
x = "Number of principal components",
y = "Cumulative variance explained"
) +
theme_minimal()
Question 7: Interpret the NCI60 PCA
Use the two score plots and the variance-explained output.
- Do observations with the same cancer-type label tend to appear near one another in PC space?
- Identify one label that appears relatively concentrated and one that appears more dispersed.
- Approximately what percentage of total gene-expression variation is explained by the first three PCs together?
- Explain why PCA can reveal visible separation among some cancer types even though the labels were not used to construct the components.
Helpful output: Use tidy(nci60_pca_fit, matrix = "eigenvalues") to read the cumulative value at PC3. The PCA uses only the gene-expression measurements; label is added afterward for interpretation.
Clustering the NCI60 Data
Because the genes are on different scales, create a standardized version for clustering.
nci60_scaled <- recipe(~ ., data = nci60) |>
step_rm(label) |>
step_normalize(all_predictors()) |>
prep() |>
bake(new_data = NULL)Fit complete-linkage hierarchical clustering.
nci60_complete <- nci60_scaled |>
dist() |>
hclust(method = "complete")Plot a four-cluster solution.
nci60_complete |>
fviz_dend(
k = 4,
main = "Complete-linkage clustering of NCI60"
)
Inspect which known cancer type is most common inside each cluster.
nci60_cluster_summary <- tibble(
label = nci60$label,
cluster_id = cutree(nci60_complete, k = 4)
) |>
count(cluster_id, label) |>
group_by(cluster_id) |>
mutate(prop = n / sum(n)) |>
slice_max(order_by = prop, n = 1, with_ties = FALSE) |>
ungroup()
nci60_cluster_summary# A tibble: 4 × 4
cluster_id label n prop
<int> <fct> <int> <dbl>
1 1 MELANOMA 8 0.2
2 2 BREAST 3 0.429
3 3 LEUKEMIA 6 0.75
4 4 COLON 5 0.556
Now perform K-means clustering with four clusters.
set.seed(2)
nci60_kmeans <- nci60_scaled |>
kmeans(centers = 4, nstart = 50)
nci60_kmeans |>
tidy() |>
select(cluster, size, withinss)# A tibble: 4 × 3
cluster size withinss
<fct> <int> <dbl>
1 1 20 108801.
2 2 27 154545.
3 3 9 37150.
4 4 8 44071.
Compare the K-means and hierarchical-clustering assignments.
cluster_kmeans <- factor(nci60_kmeans$cluster)
cluster_hclust <- factor(cutree(nci60_complete, k = 4))
tibble(
kmeans = cluster_kmeans,
hclust = cluster_hclust
) |>
conf_mat(kmeans, hclust) |>
autoplot(type = "heatmap")
Remember that cluster numbers are arbitrary labels. Cluster 1 from K-means does not have to correspond to cluster 1 from hierarchical clustering.
PCA before clustering
One way to reduce noise and dimensionality is to cluster using a small number of principal components rather than all original genes.
nci60_pca5 <- recipe(~ ., data = nci60_scaled) |>
step_pca(all_predictors(), num_comp = 5) |>
prep() |>
bake(new_data = NULL)
nci60_pca5 |> glimpse()Rows: 64
Columns: 5
$ PC1 <dbl> -19.682447, -22.908120, -27.240769, -42.480978, -54.983868, -26.96…
$ PC2 <dbl> 3.527748, 6.390938, 2.445809, -9.691742, -5.158121, 6.727122, 3.83…
$ PC3 <dbl> -9.73543821, -13.37253777, -3.50534368, -0.88309211, -20.92910760,…
$ PC4 <dbl> 0.8177816, -5.5911088, 1.3311502, -3.4180227, -15.7253986, -13.732…
$ PC5 <dbl> -12.5110806, -7.9724713, -12.4662964, -41.9383699, -10.3613641, 7.…
Cluster the observations using only the first five PCs.
nci60_pca5_complete <- nci60_pca5 |>
dist() |>
hclust(method = "complete")
nci60_pca5_complete |>
fviz_dend(
k = 4,
main = "Complete linkage using the first five PCs"
)
Question 8: Compare clustering before and after PCA
Compare complete-linkage hierarchical clustering using:
- all standardized gene-expression predictors, and
- only the first five principal components.
For each approach:
- cut the dendrogram into four clusters;
- create a table showing the number of observations in each cluster;
- determine the most common known cancer label within each cluster;
- compare how concentrated the dominant labels are.
Then answer:
- Does clustering on five PCs appear to produce more interpretable groups than clustering on all standardized genes?
- Give one possible advantage and one possible disadvantage of applying PCA before clustering.
Helpful output: Use cutree(..., k = 4), combine the result with nci60$label, then count(cluster_id, label), group_by(cluster_id), and calculate prop = n / sum(n). Repeat once for nci60_complete and once for nci60_pca5_complete.
Summary
This lab illustrates several central ideas in unsupervised learning:
- PCA creates new orthogonal variables that summarize variation among the original predictors.
- Scaling matters whenever predictor units differ substantially.
- A scree/cumulative variance plot helps describe how much information is retained by a reduced set of PCs.
- K-means partitions observations by minimizing within-cluster variation.
- The elbow method is a heuristic for choosing the number of K-means clusters.
- Hierarchical clustering depends on both the distance measure and linkage rule.
- Cluster labels are arbitrary; the important issue is which observations are grouped together.
- PCA before clustering can reduce dimension and noise, but may also discard structure that matters for clustering.