Packages and Datasets

library(cluster)
library(factoextra)
library(ggplot2)
library(dplyr)

Preamble

Introduction to Clustering

Consider data consisting of \(n\) measurements (observations) of \(p\) variables, represented by the matrix \(\mathbf{X}\):

\[ \mathbf{X} = \begin{pmatrix} x_{1,1} & x_{1,2} & \cdots & x_{1,p} \\ x_{2,1} & x_{2,2} & \cdots & x_{2,p} \\ \vdots & \vdots & \ddots & \vdots \\ x_{n,1} & x_{n,2} & \cdots & x_{n,p} \end{pmatrix} \]

  • PCA can be used to identify relationships in the columns of \(\mathbf{X}\) (ie: groupings/patterns among variables).
  • Clustering can be used to identify relationships in the rows of \(\mathbf{X}\) (ie: groupings/patterns among observations).

Clustering approaches fall into two broad categories:

  • Hierarchical Clustering organizes the data-points into a nested subsets (tree-like structures)
  • Partitional Clustering divides the data-points into non-overlapping subsets (regions in space)

In this lab, we will focus on one partitional clustering method: \(k\)-means clustering.

\(~\)

Distance

Good clusters contain data-points that are similar to each other (cohesive), and also dissimilar from the members of other clusters (distinct).

To assess “similarity” we’ll use distance (sometimes called a metric). There are many possible ways to define distance, one of the most popular is Euclidean distance:

\[d_{a,b} = \sqrt{\sum_{i = 1}^{p} (x_{ai} - x_{bi})^2}\]

In words, the Euclidean distance between two data-points, \(x_a\) and \(x_b\), is the square root of the sum of squared differences in their values across each variable (we index these variables by \(i \in \{1, \ldots, p\}\)).

\(~\)

K-means

Perhaps the most well-known clustering approach is k-means clustering, which groups \(n\) observations into \(k\) distinct groups (clusters) such that within cluster variation is minimized.

The goal of \(k\)-means is to find the \(k\) cluster centroids (\(\mu_1, \ldots, \mu_k\)) that minimize “total within-cluster sum of squares” (you do not need to memorize the following):

\[ \text{Total Within-Cluster Sum of Squares} = \sum_{j=1}^{k} W(C_j) = \sum_{j=1}^{k} \sum_{x_i \in C_j} \|x_i - \mu_j\|^2 \]

  • \(x_i\) is a data-point belonging to cluster \(j\)
  • \(\mu_j\) is the centroid (multi-dimensional mean) of cluster \(j\)
  • \(W(C_j)\) is the within-cluster sum of squares of cluster \(j\), measuring the total squared distance of members to the cluster center

To apply \(k\)-means, we must specify \(k\), the number of clusters, then the \(k\)-means algorithm is used to group the observations such that total squared distance from each data point to the center of its assigned cluster is minimized.

Figuring out which value of k to use is another problem entirely (which we will look at).

Lab

Motivating Example: Clustering States

As a motivating example, consider the USArrests data from the PCA lab. The graph below shows two clusters (red and blue) based on murder arrest rates and urban population percentages. Virginia’s cluster assignment has been hidden.

Question 1: Which cluster should contain Virginia? Why? Briefly explain.

\(~\)

The \(k\)-means Algorithm

To find clusters with low total within-cluster sum of squares, \(k\)-means uses an iterative procedure:

  1. Initialize the positions of \(k\) centroids (random starting point)
  2. Calculate the distance between each data-point and each centroid (using Euclidean distance)
  3. Assign data-points to the nearest centroid
  4. Update the cluster centroids (to the mean of its assigned data-points)
  5. Repeat (2) - (4) until there is no change

The algorithm repeatedly reassigns observations and updates the centroids until the cluster assignments stabilize. The animation below illustrates this process for \(k = 2\):

\(~\)

K-means in R

In R, the kmeans() function is used to perform \(k\)-means clustering. For example, we can use the code below to assign states in the USArrests data into two clusters:

data("USArrests")
set.seed(230)
k2 = kmeans(USArrests, centers = 2, nstart = 25)

The centers argument is the number of clusters we want (ie: \(k\)), while nstart specifies how many random initial configurations the algorithm tries, retaining the best result. Because different starting points can lead to different clusters, we can use set.seed() to make our results reproducible.

Next, notice that kmeans() outputs a list containing 9 different objects. The code below prints the coordinates of the cluster centroids (multi-dimensional means), which are stored in the centers object within that list:

k2$centers
##      Murder  Assault UrbanPop     Rape
## 1  4.841379 109.7586 64.03448 16.24828
## 2 11.857143 255.0000 67.61905 28.11429

These centroids are often called prototypes since each of them is a central point that can be used to describe the average characteristics of that cluster’s members.

If we are interested in the cluster assignments of individual data-points, we can find them in the cluster object returned by kmeans(). The code below demonstrates how to find the assigned clusters for the states “Iowa” and “Illinois”, which were row names in USArrests data frame.

k2$cluster[c("Iowa", "Illinois")]
##     Iowa Illinois 
##        1        2

Question 2: Apply \(k\)-means clustering with \(k = 4\) to the USArrests data. Then, find the centroid prototype of the cluster that contains Minnesota. How does the cluster containing Minnesota compare to the other clusters (in terms of labels you derive from the cluster centroids)?

\(~\)

Visualizing K-means

We can visualize the results of \(k\)-means using fviz_cluster(), which displays the clusters on a scatter plot that uses the first two principal component scores as the X-Y coordinates for each observation.

k2 = kmeans(USArrests, centers = 2, nstart = 25)
fviz_cluster(k2, data = USArrests)

Notice that fviz_cluster() labels each data-point using the rownames of the data object. You should recall that you can change these using the rownames() function. It’s also worth knowing that you can also use the argument repel = TRUE (in fviz_cluster()) to prevent overlapping labels.

Finally, instead of using PC1 and PC2, you can specify any of the original variables:

fviz_cluster(k2, data = USArrests, choose.vars = c("UrbanPop", "Murder"), stand = FALSE, repel = TRUE, title = "Without Standardization")

If fviz_cluster() does not display the original-variable view correctly with your package versions, we can create a scatterplot of the cluster assignments directly using ggplot2:

USArrests |>
  mutate(cluster = factor(k2$cluster)) |>
  ggplot(aes(x = UrbanPop, y = Murder, color = cluster)) +
  geom_point(size = 3) +
  geom_point(data = as.data.frame(k2$centers),
             aes(x = UrbanPop, y = Murder),
             color = "black", size = 5, shape = 8) +
  labs(title = "Without Standardization") +
  theme_minimal()

You should note that clusters will generally appear most distinct when viewed using the PC1 and PC2 axes.

Question 3 (Part A): Use the scale() function to standardize the USArrests data, then use fviz_cluster() to graph the \(k\)-means clusters (for \(k = 2\)) found using the standardized data with “UrbanPop” and “Murder” as the \(X\) and \(Y\) variables (similar to the graph in the previous example).

Question 3 (Part B): Explain why the clusters are somewhat different after standardizing the data. Do you think the data should be standardized prior to clustering? Briefly explain.

\(~\)

Choosing \(k\)

As previously mentioned, the \(k\)-means algorithm requires the user to supply the value of \(k\) before the algorithm can be run.

As a general guideline, \(k\) should be large enough that clusters are relatively homogeneous, but it should also be small enough to avoid unnecessary complexity. The next sections will cover two methods for choosing a reasonable value of \(k\).

\(~\)

The Elbow Method

The \(k\)-means algorithm solves for centroids that minimize the total within-cluster sum of squares. This quantity never increases as \(k\) increases, but there are diminishing returns. Eventually, adding more cluster centroids won’t lead to much improvement in Total Withiness.

With this relationship in mind, we can graph the total within-cluster sum of squares, abbreviated “wss”, versus different choices of \(k\) using the fviz_nbclust() function:

fviz_nbclust(USArrests, FUNcluster = kmeans, method = "wss", k.max = 8)

The Elbow Method suggests the optimal number of clusters corresponds with this plot’s “elbow”, or the point where the curve starts flatting/bending towards more gradual decreases in wss as \(k\) increases.

For the USArrests data (shown in this example), the elbow method suggests either 2 or 3 clusters would be reasonable, as going further doesn’t lead to much of a decrease in wss.

\(~\)

The Silhouette Method

The Silhouette Method measures the fit of observations within their assigned clusters using quantities known as silhouette values, which are a comparison of the similarity of an observation to its assigned cluster (cohesion) relative to its similarity to other clusters (separation).

  • Cohesion is defined as the mean distance of a data-point to the other members of its assigned cluster
  • Separation is defined as the smallest average distance between a data-point and the observations belonging to another cluster.

The difference between these two quantities (the measure of cohesion and the measure of separation) is standardized to produce a silhouette value between -1 to +1, with high values indicating an observation has “good fit” in its assigned cluster, and low values indicating “poor fit” within the assigned cluster.

If you’d like a more mathematical description of how silhouette values are calculated, the Wikipedia page is fairly accessible.

The average silhouette (across the entire data set) can be used to evaluate the effectiveness of different values of \(k\) in creating clusters that are distinctive and cohesive. We can visualize this relationship by supplying the “silhouette” method to fviz_nbclust().

fviz_nbclust(USArrests, FUNcluster = kmeans, method = "silhouette", k.max = 8)

For the USArrest data, the average silhouette metric suggests that \(k = 2\) is optimal.

Silhouettes are also useful for evaluating the cluster membership of individual observations:

k2 = kmeans(USArrests, centers = 2, nstart = 25)
sil = silhouette(k2$cluster, dist(USArrests), ordered = FALSE)
row.names(sil) = row.names(USArrests) # Needed to use label option
fviz_silhouette(sil, label = TRUE)
##   cluster size ave.sil.width
## 1       1   29          0.60
## 2       2   21          0.58

Here we see there are a handful of states that aren’t great fits in their assigned clusters, so we’d want to avoid over-interpreting their assignments when sharing our results.

If we’d like to take a closer look, we can always filter the silhouette information:

## Filter to show low sil states
as.data.frame(sil) |> filter(sil_width < 0.3)
##              cluster neighbor  sil_width
## Arkansas           2        1 0.11160017
## Missouri           1        2 0.06586521
## Rhode Island       1        2 0.17099027
## Tennessee          2        1 0.09530834

Note that the output of the silhouette() function is not a data frame, so we must coerce it before filtering.

Question 4: For each part of the following question you should use cds, which is a standardized subset of the college scorecard data created by the code given below:

## Keep this code as pre-processing
colleges = read.csv("https://NFriedrichsen.github.io/data/Colleges2019.csv")
cd = colleges |> filter(State == "IA") |>
  select(Name, Enrollment, Adm_Rate, ACT_median,
         Net_Tuition, FourYearComp_Males, FourYearComp_Females,
        Debt_median, Salary10yr_median)
cd = cd[complete.cases(cd),]  ## Keeps only complete cases (no missing values)
rownames(cd) = cd$Name

## Use the data below for this question
cds = scale(select(cd, -Name))

Part A: Using the Elbow Method, determine an appropriate number of \(k\)-means clusters for these data. Then, report the centroids of each cluster. Note: because the data have been standardized, the units describing these centroids are standard deviations.

Part B: Use the Silhouette Method to determine an appropriate number of \(k\)-means clusters for these data.

Part C: Create a silhouette plot using the value of \(k\) selected in Part B. Which college(s) have negative silhouettes? Briefly explain what these values say about these colleges and their cluster membership.

\(~\)

\(~\)

Question 5: Continue using the standardized Iowa college data (cds) from Question 4. For the following questions, use the value of \(k\) selected by the Silhouette Method in Question 4, Part B.

Part A: Use fviz_cluster() to visualize your \(k\)-means clustering results. Describe any patterns you observe. Do the clusters appear to be well separated?

Part B: Identify the clusters containing Grinnell College and Iowa State University. Using the cluster centroids, describe the typical characteristics of colleges in each cluster. How do these clusters differ?

Part C: Identify all colleges belonging to the same cluster as Grinnell College. Do these colleges appear to have similar characteristics? Briefly explain.

Part D: Recall your PCA analysis of the college data from the previous lab. Examine the first two principal components and their loadings. What characteristics of colleges do these components represent? Using this information, explain how the clusters in your visualization from Part A differ from one another.


Lab: Day 2

Distance for Categorical Variables

K-means reliance on using Euclidean distance to describe how near/far data points are from each other and is restrictive because euclidean distance is not defined for categorical variables.

An alternative distance measure is Gower distance: \[d_{Gower}(a,b) = \tfrac{1}{p}\sum_{i = 1}^{p} h_i( x_{a,i}, x_{b,i})\]

The function \(h_i()\) differs depending upon whether \(X_i\) is numeric or categorical

  • For numeric variables, \(h_i(x_{a,i}, x_{b,i}) = \tfrac{|x_{a,i} - x_{b,i}|}{R_i}\), where \(R_i\) is the observed range of \(X_i\)
  • For categorical variables, \(h_i(x_{a,i}, x_{b,i}) = 0\) if the \(x_{a,i}\) and \(x_{b,i}\) are the same category, and \(h_i(x_{a,i}, x_{b,i}) = 1\) otherwise

Notice that \(h_i()\) has a range of \([0,1]\) regardless of whether \(X_i\) is categorical or numeric, so Gower distance implicitly standardizes our data (so we generally don’t need to worry about using scale() function when clustering using Gower distance).

\(~\)

Distance Matrices

A distance matrix, sometimes called a dissimilarity matrix, is an \(n\) by \(n\) matrix containing the pairwise distances between all pairs of data-points.

To better understand Gower distance and distance matrices, let’s look at a simple data set consisting of 6 yes/no questions that describe \(n = 20\) different animal species:

Warm_blooded? Can_fly? Vertebrate? Endangered? Lives_in_groups? Has_hair?
ant No No No No Yes No
bee No Yes No No Yes Yes
cat Yes No Yes No No Yes
cephalopod No No No No No Yes
chimp Yes No Yes Yes Yes Yes
cow Yes No Yes No Yes Yes
duck Yes Yes Yes No Yes No
eagle Yes Yes Yes Yes No No
elephant Yes No Yes Yes Yes No
fly No Yes No No No No
frog No No Yes Yes NA No
hermit No No Yes No Yes No
lion Yes No Yes NA Yes Yes
lizard No No Yes No No No
lobster No No No No NA No
human Yes No Yes Yes Yes Yes
rabbit Yes No Yes No Yes Yes
salamander No No Yes No NA No
spider No No No NA No Yes
whale Yes No Yes Yes Yes No

\(~\)

We can calculate a matrix of Gower distances using the daisy() function in the cluster package:

animals <- read.csv("https://NFriedrichsen.github.io/data/animals.csv", row.names = 1, stringsAsFactors = TRUE)
D <- daisy(animals, metric = "gower")  ## Calculate distance matrix
fviz_dist(D)  ## Visualize

We can then visualize the distance matrix using fviz_dist().

Question 6:

  • Why are all entries on the diagonal of this matrix exactly 0?
  • What must be true of lions (“lio”) and flies (“fly”) for their distance to be 1?
  • In general, why are distance matrices symmetric about the diagonal?

PAM Clustering

\(k\)-means clustering is a straightforward and widely used method, but it has a few weaknesses:

  1. As a measure of central tendency, the mean is sensitive to outliers, so \(k\)-means centroids tend to be strongly influenced by unusual data-points.
  2. The centroids found by \(k\)-means aren’t actual data-points, so using them to describe the typical members of a cluster isn’t always accurate, especially when the number of variables is large and the data contain outliers.
  3. Distances that rely upon \(x_i - \mu_k\) aren’t defined for categorical variables, so \(k\)-means will only work when all variables are numeric.

Partitioning Around Medoids (PAM) is an alternative clustering approach that searches for \(k\) data-points called medoids, which serve as cluster centers. The remaining data-points are assigned to the cluster defined by the nearest medoid.

usarrests_std <- scale(USArrests)
us_pam <- pam(usarrests_std, k = 3)  ## Apply PAM clustering
us_pam$medoids  ## Print the medoids
##                   Murder    Assault   UrbanPop       Rape
## New Mexico     0.8292944  1.3708088  0.3081225  1.1603196
## Oklahoma      -0.2727580 -0.2371077  0.1699510 -0.1315342
## New Hampshire -1.3059321 -1.3650491 -0.6590781 -1.2525644
fviz_cluster(us_pam) ## Plot the clusters

PAM addresses many of the drawbacks of \(k\)-means. It is more robust to outliers (not impervious), and the cluster centers are themselves data-points, making the results more interpretable. And, we’ll later see PAM can be used to cluster data with categorical variables.

The biggest weakness of PAM is its computational efficiency. PAM doesn’t scale well to large datasets due to the complex constraints on the medoid update step.


Question #7: Apply PAM clustering to the cds data set used in Questions #4 and #5. Your analysis should use the same value of \(k\) using one of the two approaches from the previous section, and you should report the prototypes (cluster medoids) for each cluster.

Question #8: For the college data in Question 7, compare the clusters produced by PAM using fviz_cluster with those obtained using k-means in Questions #4 and #5. Do the two methods produce similar groupings of colleges? Identify any notable differences in Grinnell membership. (Make sure you are using the same number of clusters for each method!)


Question #9 (Baseball Stuff): The “mlb” data set contains offensive statistics for all Major League Baseball players with at least 200 at bats during the 2022 season. Aside from the player ID and “AB” (number of at bats), all other columns are reported as rates (per at bat).

mlb <- read.csv("https://NFriedrichsen.github.io/data/mlb_hitters22.csv")

For those unfamiliar with baseball, here are some brief definitions of the remaining variables:

  • R - runs scored per at bat
  • H - hit rate (per at bat)
  • X2B - double rate (per at bat)
  • HR - home run rate (per at bat)
  • RBI - runs batted in per at bat
  • SB - stolen bases (scaled by number of batting attempts)
  • CS - caught stealing rate (per at bat)
  • BB - bases on balls (walks) per at bat
  • SO - strike outs per at at bat

Part A: Create a new data frame, mlb_std, where the player IDs are used as row names, the variable “AB” is removed, and all other variables have been standardized by the scale() function.

Part B: Use the Silhouette Method to determine the number of clusters that should be used when applying clustering to these data. Then, apply the \(k\)-means algorithm and print the cluster centroids.

Part C: Suppose a sports columnist wants to write an article titled “7 different types of hitters”. Use PAM clustering to find a prototype players to use in this article (you can just use their Player ID for this last part). Then, report the number of hitters belonging to each of these clusters.

Part D: Examine the offensive statistics of the seven medoids identified in Part E. Choose two of these players and briefly describe the types of hitters they represent. How do their hitting profiles differ?