library(cluster)
library(dbscan)
library(factoextra)
library(tidyverse)
library(patchwork)
library(ggrepel)Activity 4.2 - Kmeans, PAM, and DBSCAN clustering
SUBMISSION INSTRUCTIONS
- Render to html
- Publish your html to RPubs
- Submit a link to your published solutions
Loading required packages:
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.\)
plot_knn <- function(df, minPts = 4){
kNNdistplot(df, k = minPts)
abline(h = 0, col = "white")
}plot_knn(three_spheres, minPts = 4)
abline(h = 0.25, col="red", lwd=2) plot_knn(ring_moon_sphere, minPts = 4)
abline(h = 0.18, col="red", lwd=2) plot_knn(two_spirals_sphere, minPts = 4)
abline(h = 0.22, col="red", lwd=2) 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 theepsandminPtsvalues; - 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
epsandminPtsused 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){
num_cols <- df %>% select(where(is.numeric)) %>% names()
# rename them to X and Y
df2 <- df %>%
select(all_of(num_cols[1:2])) %>%
setNames(c("X", "Y"))
db <- dbscan(df2, eps = eps, minPts = minPts)
# Add cluster assignment
df2$cluster <- factor(db$cluster)
# plot
ggplot(df2, aes(x = X, y = Y, color = cluster)) +
geom_point(size = 2) +
labs(title = paste0("DBSCAN (eps = ", eps, ", minPts = ", minPts, ")")) +
theme_minimal()
}p1_db <- plot_dbscan_results(three_spheres, eps = 0.25, minPts = 4)
p2_db <- plot_dbscan_results(ring_moon_sphere, eps = 0.18, minPts = 4)
p3_db <- plot_dbscan_results(two_spirals_sphere, eps = 0.22, minPts = 4)
p1_db; p2_db; p3_dbC)
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 <- function(df, centers = 3){
km <- kmeans(df, centers = centers)
df %>%
mutate(cluster = factor(km$cluster)) %>%
ggplot(aes(x = .[,1], y = .[,2], color = cluster)) +
geom_point(size = 2) +
labs(title = "k-means (k = 3)") +
theme_minimal()
}
plot_pam <- function(df, k = 3){
pm <- pam(df, k)
df %>%
mutate(cluster = factor(pm$clustering)) %>%
ggplot(aes(x = .[,1], y = .[,2], color = cluster)) +
geom_point(size = 2) +
labs(title = "PAM (k = 3)") +
theme_minimal()
}p1_k <- plot_kmeans(three_spheres)
p2_k <- plot_kmeans(ring_moon_sphere)
p3_k <- plot_kmeans(two_spirals_sphere)
p1_p <- plot_pam(three_spheres)
p2_p <- plot_pam(ring_moon_sphere)
p3_p <- plot_pam(two_spirals_sphere)(p1_k | p1_p | p1_db) /
(p2_k | p2_p | p2_db) /
(p3_k | p3_p | p3_db)K-means and PAM only work well on the simple spherical clusters (top row). They fail on the ring and spiral shapes because they assume round, center-based clusters. DBSCAN is the only method that correctly captures the curved and nested structures, making it the most accurate across all three datasets.
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 birthgdp: GDP per capita, in 2015 USDco2: CO2 emissions, in metric tons per capitafert_rate: annual births per 1000 womenhealth: percentage of GDP spent on health careimportsandexports: imports and exports as a percentage of GDPinternetandelectricity: percentage of population with access to internet and electricity, respectivelyinfant_mort: infant mortality rate, infant deaths per 1000 live birthsinflation: consumer price inflation, as annual percentageincome: 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.
wdi_num <- wdi %>%
select(where(is.numeric))
set.seed(123)
fviz_nbclust(wdi_num, kmeans, method = "wss") +
labs(title = "Elbow Plot")fviz_nbclust(wdi_num, kmeans, method = "silhouette") +
labs(title = "Silhouette Plot")gap_stats <- clusGap(wdi_num, FUN = kmeans, K.max = 10, B = 50)
fviz_gap_stat(gap_stats)These methods both suggest that around 3–5 clusters is reasonable. The gap statistic rises steadily and reaches its highest values between k = 4–7, with a clear improvement by k = 4. Overall, the evidence supports your claim that 3–5 clusters is an appropriate range for this dataset.
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_num, centers = 4, nstart = 25)
wdi$cluster4 <- factor(km4$cluster)
pca <- prcomp(wdi_num, scale. = TRUE)
fviz_pca_ind(
pca,
geom.ind = "point",
col.ind = wdi$cluster4,
palette = "Set1",
addEllipses = TRUE,
legend.title = "Cluster"
)cluster_summary <- wdi %>%
select(country, cluster4, everything()) %>%
group_by(cluster4) %>%
summarise(across(where(is.numeric), mean, .names = "mean_{col}"))
cluster_summary# A tibble: 4 × 13
cluster4 mean_life_expectancy mean_gdp mean_co2 mean_fert_rate mean_health
<fct> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 81.8 46905. 10.9 1.60 10.4
2 2 82.7 86527. 7.92 1.48 9.06
3 3 68.9 3850. 2.29 2.98 6.20
4 4 78.3 19840. 8.01 1.60 7.86
# ℹ 7 more variables: mean_internet <dbl>, mean_infant_mort <dbl>,
# mean_electricity <dbl>, mean_imports <dbl>, mean_inflation <dbl>,
# mean_exports <dbl>, mean_income <dbl>
Cluster 1 (red) developed high-income nations (US, Germany, Japan)
Cluster 2 (blue) wealthy outliers (Singapore, Luxembourg, Ireland)
Cluster 3 (green) middle-income countries (Brazil, Turkey, South Africa)
Cluster 4 (purple) low-income developing countries (Chad, Afghanistan, Haiti)
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?
wdi_trim <- wdi %>%
filter(!(country %in% c("Ireland", "Singapore", "Luxembourg")))
wdi_trim_num <- wdi_trim %>%
select(where(is.numeric))
set.seed(123)
km4_trim <- kmeans(wdi_trim_num, centers = 4, nstart = 25)
wdi_trim$cluster4_trim <- factor(km4_trim$cluster)
pca_trim <- prcomp(wdi_trim_num, scale. = TRUE)
fviz_pca_ind(
pca_trim,
geom.ind = "point",
col.ind = wdi_trim$cluster4_trim,
palette = "Set1",
addEllipses = TRUE,
legend.title = "Cluster (Trimmed)"
)After removing Ireland, Singapore, and Luxembourg, the 4-cluster solution becomes more stable. The “wealthy outlier” group disappears, and those extreme values no longer pull the PCA axes. The remaining clusters separate more cleanly into high-income, middle-income, and low-income groups, with boundaries that are easier to interpret. Overall, removing the outliers makes the clustering more balanced and meaningful.