Activity 4.2 - Kmeans, PAM, and DBSCAN clustering

SUBMISSION INSTRUCTIONS

  1. Render to html
  2. Publish your html to RPubs
  3. Submit a link to your published solutions

Loading required packages:

library(cluster)
library(dbscan)
library(factoextra)
library(tidyverse)
library(patchwork)
library(ggrepel)

Question 1

Reconsider the three data sets below. We will now compare kmeans, PAM, and DBSCAN to cluster these data sets.

three_spheres <- read.csv('Data/cluster_data1.csv')
ring_moon_sphere <- read.csv('Data/cluster_data2.csv')
two_spirals_sphere <- read.csv('Data/cluster_data3.csv')

A)

With kmeans and PAM, we can specify that we want 3 clusters. But recall with DBSCAN we select minPts and eps, and the number of clusters is determined accordingly. Use k-nearest-neighbor distance plots to determine candidate epsilon values for each data set if minPts = 4. Add horizontal line(s) to each plot indicating your selected value(s) of \(\epsilon.\)

minPts <- 4

plot_knn_distance <- function(data, title, epsilon_values) {
  knn_dist <- kNNdist(data, k = minPts)
  
  knn_dist_sorted <- sort(knn_dist, decreasing = TRUE)
    plot_data <- data.frame(
    index = 1:length(knn_dist_sorted),
    distance = knn_dist_sorted
  )
  
  p <- ggplot(plot_data, aes(x = index, y = distance)) +
    geom_line(color = "blue", linewidth = 0.8) +
    labs(
      title = paste("k-NN Distance Plot:", title),
      subtitle = paste("minPts =", minPts),
      x = "Points (sorted by distance)",
      y = paste(minPts, "-NN Distance")
    ) +
    theme_minimal() +
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          plot.subtitle = element_text(hjust = 0.5))
  
  for (eps in epsilon_values) {
    p <- p + geom_hline(yintercept = eps, 
                        color = "red", 
                        linetype = "dashed", 
                        linewidth = 1) +
      annotate("text", x = max(plot_data$index) * 0.8, y = eps, 
               label = paste("ε =", round(eps, 3)), 
               vjust = -0.5, color = "red", fontface = "bold")
  }
  
  return(p)
}


p1 <- plot_knn_distance(three_spheres, "Three Spheres", epsilon_values = c(0.11))
p2 <- plot_knn_distance(ring_moon_sphere, "Ring, Moon, Sphere", epsilon_values = c(0.15))
p3 <- plot_knn_distance(two_spirals_sphere, "Two Spirals and Sphere", epsilon_values = c(0.13))

print(p1)

print(p2)

print(p3)

B)

Write a function called plot_dbscan_results(df, eps, minPts). This function takes a data frame, epsilon value, and minPts as arguments and does the following:

  • Runs DBSCAN on the inputted data frame df, given the eps and minPts values;
  • Creates a scatterplot of the data frame with points color-coded by assigned cluster membership. Make sure the title of the plot includes the value of eps and minPts used to create the clusters!!

Using this function, and your candidate eps values from A) as a starting point, implement DBSCAN to correctly identify the 3 cluster shapes in each of the three data sets. You will likely need to revise the eps values until you settle on a “correct” solution.

plot_dbscan_results <- function(df, eps, minPts) {
  # Run DBSCAN
  dbscan_result <- dbscan(df, eps = eps, minPts = minPts)
  
  # Create data frame with cluster assignments
  plot_data <- data.frame(
    x = df[, 1],
    y = df[, 2],
    cluster = as.factor(dbscan_result$cluster)
  )
  
  # Create scatterplot
  p <- ggplot(plot_data, aes(x = x, y = y, color = cluster)) +
    geom_point(size = 2, alpha = 0.7) +
    labs(
      title = paste0("DBSCAN (eps = ", eps, ", minPts = ", minPts, ")"),
      x = "X",
      y = "Y",
      color = "Cluster"
    ) +
    theme_minimal() +
    theme(
      plot.title = element_text(hjust = 0.5, face = "bold", size = 10),
      legend.position = "right"
    ) +
    coord_equal()
  
  # Print number of clusters found (excluding noise = 0)
  n_clusters <- length(unique(dbscan_result$cluster)) - sum(dbscan_result$cluster == 0)
  n_noise <- sum(dbscan_result$cluster == 0)
  cat(paste0("eps = ", eps, ", minPts = ", minPts, 
             ": Found ", n_clusters, " clusters, ", n_noise, " noise points\n"))
  
  return(p)
}

cat("1: three spheres")
1: three spheres
plot_dbscan_results(three_spheres, eps = 0.14, minPts = 4)
eps = 0.14, minPts = 4: Found -14 clusters, 20 noise points

plot_dbscan_results(three_spheres, eps = 0.12, minPts = 4)
eps = 0.12, minPts = 4: Found -27 clusters, 32 noise points

plot_dbscan_results(three_spheres, eps = 0.11, minPts = 4)
eps = 0.11, minPts = 4: Found -29 clusters, 36 noise points

cat("\n2: Ring, moon sphere")

2: Ring, moon sphere
plot_dbscan_results(ring_moon_sphere, eps = 0.3, minPts = 4)
eps = 0.3, minPts = 4: Found 3 clusters, 1 noise points

plot_dbscan_results(ring_moon_sphere, eps = 0.15, minPts = 4)
eps = 0.15, minPts = 4: Found -24 clusters, 47 noise points

cat("\n3: two spirals and sphere")

3: two spirals and sphere
plot_dbscan_results(two_spirals_sphere, eps = 0.13, minPts = 4)
eps = 0.13, minPts = 4: Found -507 clusters, 510 noise points

plot_dbscan_results(two_spirals_sphere, eps = 0.12, minPts = 4)
eps = 0.12, minPts = 4: Found -508 clusters, 511 noise points

plot_dbscan_results(two_spirals_sphere, eps = 0.10, minPts = 4)
eps = 0.1, minPts = 4: Found -513 clusters, 515 noise points

C)

Compare your DBSCAN solutions to the 3-cluster solutions from k-means and PAM. Use the patchwork package and your function from B) to produce a 3x3 grid of plots: one plot per method/data set combo. Comment on your findings.

plot_kmeans_results <- function(df, title_suffix = "") {
  kmeans_result <- kmeans(df, centers = 3, nstart = 25)
  plot_data <- data.frame(
    x = df[, 1],
    y = df[, 2],
    cluster = as.factor(kmeans_result$cluster)
  )
  
  ggplot(plot_data, aes(x = x, y = y, color = cluster)) +
    geom_point(size = 2, alpha = 0.7) +
    labs(
      title = paste0("K-means (k=3)", title_suffix),
      x = "X",
      y = "Y",
      color = "Cluster"
    ) +
    theme_minimal() +
    theme(
      plot.title = element_text(hjust = 0.5, face = "bold", size = 10),
      legend.position = "right"
    ) +
    coord_equal()
}

# Helper function for PAM plotting
plot_pam_results <- function(df, title_suffix = "") {
  pam_result <- pam(df, k = 3)
  plot_data <- data.frame(
    x = df[, 1],
    y = df[, 2],
    cluster = as.factor(pam_result$clustering)
  )
  
  ggplot(plot_data, aes(x = x, y = y, color = cluster)) +
    geom_point(size = 2, alpha = 0.7) +
    labs(
      title = paste0("PAM (k=3)", title_suffix),
      x = "X",
      y = "Y",
      color = "Cluster"
    ) +
    theme_minimal() +
    theme(
      plot.title = element_text(hjust = 0.5, face = "bold", size = 10),
      legend.position = "right"
    ) +
    coord_equal()
}

eps1 <- 0.11  # Three Spheres
eps2 <- 0.15  # Ring, Moon, Sphere
eps3 <- 0.13  # Two Spirals and Sphere

p1_kmeans <- plot_kmeans_results(three_spheres)
p1_pam <- plot_pam_results(three_spheres)
p1_dbscan <- plot_dbscan_results(three_spheres, eps = eps1, minPts = 4)
eps = 0.11, minPts = 4: Found -29 clusters, 36 noise points
p2_kmeans <- plot_kmeans_results(ring_moon_sphere)
p2_pam <- plot_pam_results(ring_moon_sphere)
p2_dbscan <- plot_dbscan_results(ring_moon_sphere, eps = eps2, minPts = 4)
eps = 0.15, minPts = 4: Found -24 clusters, 47 noise points
p3_kmeans <- plot_kmeans_results(two_spirals_sphere)
p3_pam <- plot_pam_results(two_spirals_sphere)
p3_dbscan <- plot_dbscan_results(two_spirals_sphere, eps = eps3, minPts = 4)
eps = 0.13, minPts = 4: Found -507 clusters, 510 noise points
comparison_grid <- (p1_kmeans | p1_pam | p1_dbscan) /
                   (p2_kmeans | p2_pam | p2_dbscan) /
                   (p3_kmeans | p3_pam | p3_dbscan)

comparison_grid <- comparison_grid + 
  plot_annotation(
    title = "Clustering Method Comparison: K-means vs PAM vs DBSCAN",
    theme = theme(plot.title = element_text(hjust = 0.5, face = "bold", size = 14))
  )

print(comparison_grid)

Question 2

In this question we will apply cluster analysis to analyze economic development indicators (WDIs) from the World Bank. The data are all 2020 indicators and include:

  • life_expectancy: average life expectancy at birth
  • gdp: GDP per capita, in 2015 USD
  • co2: CO2 emissions, in metric tons per capita
  • fert_rate: annual births per 1000 women
  • health: percentage of GDP spent on health care
  • imports and exports: imports and exports as a percentage of GDP
  • internet and electricity: percentage of population with access to internet and electricity, respectively
  • infant_mort: infant mortality rate, infant deaths per 1000 live births
  • inflation: consumer price inflation, as annual percentage
  • income: annual per-capita income, in 2020 USD
wdi <- read.csv('Data/wdi_extract_clean.csv') 
head(wdi)
      country life_expectancy        gdp      co2 fert_rate    health internet
1 Afghanistan        61.45400   527.8346 0.180555     5.145 15.533614  17.0485
2     Albania        77.82400  4437.6535 1.607133     1.371  7.503894  72.2377
3     Algeria        73.25700  4363.6853 3.902928     2.940  5.638317  63.4727
4      Angola        63.11600  2433.3764 0.619139     5.371  3.274885  36.6347
5   Argentina        75.87800 11393.0506 3.764393     1.601 10.450306  85.5144
6     Armenia        73.37561  4032.0904 2.334560     1.700 12.240562  76.5077
  infant_mort electricity  imports inflation  exports    income
1        55.3        97.7 36.28908  5.601888 10.42082  475.7181
2         8.1       100.0 36.97995  1.620887 22.54076 4322.5497
3        20.4        99.7 24.85456  2.415131 15.53520 2689.8725
4        42.3        47.0 27.62749 22.271539 38.31454 1100.2175
5         8.7       100.0 13.59828 42.015095 16.60541 7241.0303
6        10.2       100.0 39.72382  1.211436 29.76499 3617.0320

Focus on using kmeans for this problem.

A)

My claim: 3-5 clusters appear optimal for this data set. Support or refute my claim using appropriate visualizations.

library(factoextra)
library(cluster)

# Scale the data
wdi_scaled <- scale(wdi[, -1])  # Exclude country names

# Elbow method
fviz_nbclust(wdi_scaled, kmeans, method = "wss") +
  geom_vline(xintercept = 3:5, linetype = 2)

# Silhouette method  
fviz_nbclust(wdi_scaled, kmeans, method = "silhouette")

B)

Use k-means to identify 4 clusters. Characterize the 4 clusters using a dimension reduction technique. Provide examples of countries that are representative of each cluster. Be thorough.

set.seed(123)
km4 <- kmeans(wdi_scaled, centers = 4, nstart = 25)
wdi$cluster <- km4$cluster
library(ggplot2)
pca <- prcomp(wdi_scaled)
pca_data <- data.frame(pca$x[,1:2], cluster = factor(km4$cluster), 
                        country = wdi$country)

ggplot(pca_data, aes(PC1, PC2, color = cluster, label = country)) +
  geom_point(size = 3) +
  geom_text(vjust = -0.5, size = 2.5)

# Cluster means
# aggregate(. ~ cluster, data = wdi, FUN = mean)

# Size of each cluster
# table(wdi$cluster)

C)

Remove Ireland, Singapore, and Luxembourg from the data set. Use k-means to find 4 clusters again, with these three countries removed. How do the cluster definitions change?

# Remove outliers
wdi_no_outliers <- wdi[!wdi$country %in% c("Ireland", "Singapore", "Luxembourg"), ]
wdi_no_outliers_scaled <- scale(wdi_no_outliers[, -1])

# Re-run k-means
set.seed(123)
km4_no_outliers <- kmeans(wdi_no_outliers_scaled, centers = 4, nstart = 25)

# Compare cluster characteristics