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

Lab Due: Monday 11/23 at 11:59pm. We will not continue working on it in class that day, however.

Types of Clustering

Review: Distance Matrix and Gower Distance

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

Hierarchical Clustering

Some clustering algorithms can use the distance matrix, rather than the raw data, to identify clusters. In this part we’ll introduce hierarchical clustering, which can be applied to any distance matrix.

In contrast with prototype-based approaches like \(k\)-means or PAM (partitioning around mediods), hierarchical clustering organizes observations into a nested sets. These sets can be displayed using a tree-like structure known as a dendrogram:

ag <- agnes(D)  ## Apply a hierarchical clustering algorithm
fviz_dend(ag) + labs(title = "Clustering Animals")  ## Display the dendrogram

We can always obtain partitional clusters by “cutting” a dendrogram:

fviz_dend(ag, k = 4) + labs(title = "Clustering Animals (k = 4)")

In this example, we asked for \(k = 4\) clusters, so the dendrogram was cut at a height of approximately 0.4. This indicates that the members of these clusters differ by an average Gower distance of around 0.4, so we can say that they’re relatively different when considering the scale of Gower distance.


Lab

Hierarchical Clustering Algorithms

To begin, we’ll introduce two basic philosophies behind different types of hierarchical clustering algorithms:

  • Agglomerative, or “bottom-up” approaches, that start with each data-point as its own cluster (leaf) and combine similar clusters (branches) until all of the data-points are grouped together in single cluster (root).
  • Divisive, or “top-down” approaches, that start all data-points in a single cluster (root), then divide that cluster into smaller clusters (branches). The resulting branches are further divided until each data-point is its own cluster (leaf).

The acronyms AGNES (AGglomerative NESting) and DIANA (DIvisive ANAlysis) describe two of the most popular methods. The code below gives an example of each:

D <- daisy(animals, metric = "gower")

ag <- agnes(D)
fviz_dend(ag, k = 3) + labs(title = "Clustering Animals (AGNES)")

di <- diana(D)
fviz_dend(di, k = 3) + labs(title = "Clustering Animals (DIANA)")

AGNES and DIANA are considered greedy algorithms (meaning each cluster merge/split is locally optimal, without any consideration of the overall hierarchy optimality). Consequently, agglomerative and divisive approaches will usually produce different dendrograms.

Specific details of the AGNES and DIANA algorithms are summarized below:

AGNES Algorithm:

AGNES begins with each observation in its own cluster. At each step, it identifies the two most similar clusters according to a selected linkage method:

  • method = "average" - the average distance between all data-points in one cluster relative to those in another cluster
  • method = "single" - the smallest distance between a single data-point in one cluster relative to another cluster (nearest neighbor)
  • method = "complete" - the smallest instance of the largest distance between a single data-point in one cluster relative to another cluster (furthest neighbor)

The two clusters with the smallest distance according to the selected linkage method are merged. This process repeats until all observations belong to a single cluster.

DIANA Algorithm:

DIANA begins with all observations in a single cluster and repeatedly divides clusters using the following procedure:

  • Select the cluster with the largest diameter (maximum pairwise distance).
  • Identify the observation with the largest average distance from the others and move it into a new “splinter group.”
  • Move additional observations into the splinter group if they are, on average, more dissimilar to the original cluster than to the splinter group.

Repeat until every observation belongs to its own cluster.

The algorithm repeats this procedure until every observation belongs to its own cluster.

Which algorithm should we use?

Neither AGNES nor DIANA is guaranteed to produce better clusters for a particular dataset, so comparing their results can be useful. In practice, AGNES is more commonly used because it is generally less computationally expensive, especially for larger datasets. Its different linkage methods also provide additional flexibility.

\(~\)

Question #1: The code below applies the AGNES algorithm with method = "single" to the USArrests data using the matrix of euclidean distances calculated after the data are standardized. For this question, use the provided code and its output to answer the following questions:

Part A: How many clusters were present at the initialization (start) of this clustering algorithm?

Part B: What was the first merge/split that occurred? Use the distance matrix, D, to briefly justify why this merge/split happened first. Hint: min(D) will return the distance between the closest two data-points. You can confirm that this distance corresponds to the merge/split you identified by using View(as.matrix(D)).

Part C: If this dendrogram were cut to obtain \(k = 3\) clusters, how many members would belong to the largest of these clusters? Note: You may answer this question by inspecting the given output without writing any of your own code.

data("USArrests")
USArrests_std <- scale(USArrests)
D <- daisy(USArrests_std, metric = "euclidean")

ag1 <- agnes(D, method = "single")
fviz_dend(ag1, cex = 0.25) + labs(title = 'AGNES, Method = "Single"')

\(~\)

Question 2: The code below applies the DIANA algorithm to the distance matrix calculated from the standardized USarrests data. Using the code and output provided below, answer the following questions:

Part A: How many clusters were present at the initialization (start) of this algorithm?

Part B: Briefly describe the merge/split resulting from the first step of the algorithm.

Part C: Which observation do you believe was the initial member of the “splinter group” in the first step of the algorithm? Justify your answer. Hint: DIANA begins by identifying the observation with the largest average dissimilarity from the other observations in its cluster. You might examine the row or column means of the distance matrix, D, after converting it into a matrix using as.matrix().

di1 <- diana(D)
fviz_dend(di1, cex = 0.25) + labs(title = 'DIANA')

\(~\)

Where to cut?

Dendrograms provide a unique perspective on the relationships between data-points, but oftentimes we’d still like to report cluster membership for an optimized choice of \(k\).

Fortunately, all of the methods described in our previous clustering lab can also be applied to hierarchical methods. Unfortunately, some of them will require all of our variables are numeric.

The code below demonstrates these three methods using DIANA clustering on the USArrests data used in Questions 1 and 2.

### The elbow method
fviz_nbclust(USArrests_std, FUNcluster = hcut, hc_func = "diana", method = "wss")

### The average silhouette method
fviz_nbclust(USArrests_std, FUNcluster = hcut, hc_func = "diana", method = "silhouette")

The argument FUNcluster = hcut indicates the use of hierarchical clustering that is to be cut into clusters, while the argument hc_func specifies the specific hierarchical clustering algorithm that should be used.

Question 3: The code below creates cds, a standardized subset of the Colleges 2019 data set that was used in the partitional clustering portion of the lab. For this question, use the average silhouette method to find the optimal value of \(k\) for AGNES clustering performed on these data. Then, create a dendrogram displaying the AGNES clustering results with branches colored according to the value of \(k\) you selected. You should use euclidean distance for this analysis.

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
cds <- scale(select(cd, -Name))

Question 4: Repeat Question 3 using DIANA clustering. Do you notice any differences?

Hierarchical Clustering Practice (Required)

The aim of this section is to provide you an opportunity to apply clustering algorithms to new data sets in order to practice identifying scenarios where clustering might be a useful analysis approach.

Question 5: The “European foods” data set summarizes the results of a household survey administered to 16 European nations in 1975. The survey asked households whether they had various foods in their house at the time of the questionnaire. The data below display the percentage of households in each country that had the food in question (expressed as a numeric value between 0 and 100).

euro <- read.csv("https://NFriedrichsen.github.io/data/europeanfoods.csv", row.names = 1, stringsAsFactors = TRUE)

Part A: Create a distance matrix using euclidean distance without standardizing (since all variables are already on a 0-100 scale). Then, visualize this matrix using fviz_dist(). Which country’s household food habits are most similar to Britain’s?

Part B: Use AGNES clustering with average distance as the merging method to create a dendrogram displaying these data.

Part C: Use DIANA clustering to create a dendrogram displaying these data.

Part D: Sweden, Norway, Denmark, and Finland are commonly grouped together as a region known as the Nordic Countries. Which algorithm, AGNES or DIANA, seems to do a better job capturing this grouping? Briefly explain your answer.

Part E: Use the average silhouette method to determine an optimal number of clusters for the application of AGNES clustering in Part B. Then, use this value to color the dendrogram you created in Part B.


Question 6: The “starwars” data set documents the attributes of major characters in the Star Wars film series. For this question, you will perform a cluster analysis on the subset created below. The variables definitions are largely self-explanatory, but you can run ?starwars in the console for descriptions.

data("starwars")
sw <- starwars %>%
  select(name, height, mass, hair_color, skin_color, eye_color, birth_year, sex, gender, homeworld, species) %>%
  mutate_if(is.character, as.factor)
sw <- as.data.frame(sw[complete.cases(sw),])
rownames(sw) <- sw$name
sw <- select(sw, -name)

Part A: After inspecting the contents of sw, briefly explain why Gower distance should be used to cluster these data.

Part B: Create a distance matrix and visualize it using fviz_dist().

Part C: Using the AGNES algorithm, create a dendrogram displaying these data.

Part D (optional, not graded): If you are familiar with Star Wars, do any relationships displayed in the dendrogram from Part C stand out as particularly interesting?