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
- 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.\)
#| fig-width: 12
#| fig-height: 4
par(mfrow = c(1, 3))
kNNdistplot(three_spheres %>% select(x, y), minPts = 4)
abline(h = 0.1, lty = 2, col = 'red')
title('Three spheres')
kNNdistplot(ring_moon_sphere %>% select(x, y), minPts = 4)
abline(h = 0.055, lty = 2, col = 'red')
title('Ring, moon, sphere')
kNNdistplot(two_spirals_sphere %>% select(x, y), minPts = 4)
abline(h = 0.1, lty = 2, col = 'red')
title('Two spirals, sphere')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.
library(tidyverse)
library(dbscan)
library(patchwork)
plot_dbscan_results <- function(df, eps, minPts) {
numeric_only <- df %>%
select(x, y)
dbscan_clusters <- dbscan(numeric_only,
eps = eps,
minPts = minPts
)
df$dbscan_clusters <- factor(dbscan_clusters$cluster)
ggplot(data = df, aes(x = x, y = y, color = dbscan_clusters)) +
geom_point() +
labs(title = paste0('DBSCAN: eps = ', eps, ', minPts = ', minPts),
color = 'Cluster') +
theme_classic(base_size = 16)
}
plot_dbscan_results(three_spheres, eps = 0.2, minPts = 4) +
plot_dbscan_results(ring_moon_sphere, eps = 0.3, minPts = 4) +
plot_dbscan_results(two_spirals_sphere, eps = 1.25, minPts = 4)3 spheres - 0.2
ring, moon, sphere - 0.3
spiral 1, spiral 2, the center sphere - 1.25
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.
library(cluster)
plot_partition_results <- function(df, method) {
numeric_only <- df %>%
select(x, y)
if (method == 'kmeans') {
clusters <- kmeans(numeric_only, centers = 3, iter.max = 20, nstart = 10)$cluster
} else {
clusters <- pam(numeric_only, k = 3, nstart = 10)$clustering
}
df$clusters <- factor(clusters)
ggplot(data = df, aes(x = x, y = y, color = clusters)) +
geom_point() +
labs(title = paste0(method, ': k = 3'), color = 'Cluster') +
theme_classic(base_size = 16)
}
(plot_partition_results(three_spheres, 'kmeans') |
plot_partition_results(three_spheres, 'PAM') |
plot_dbscan_results(three_spheres, eps = 0.2, minPts = 4)) /
(plot_partition_results(ring_moon_sphere, 'kmeans') |
plot_partition_results(ring_moon_sphere, 'PAM') |
plot_dbscan_results(ring_moon_sphere, eps = 0.3, minPts = 4)) /
(plot_partition_results(two_spirals_sphere, 'kmeans') |
plot_partition_results(two_spirals_sphere, 'PAM') |
plot_dbscan_results(two_spirals_sphere, eps = 1.25, minPts = 4))For the three spheres, k-means, PAM, and DBSCAN all get the correct clusters, although DBSCAN labels a few outlying points as noise. For the ring/moon/sphere and two spirals/sphere data, k-means and PAM aren’t as accurate because they split the data into sections based on distance to the nearest center rather than following the actual shapes. DBSCAN gets both right because it groups points based on density. Overall, k-means and PAM work best for round, well-separated clusters, while DBSCAN is better for more unusual shapes. The downside is that DBSCAN requires adjusting eps for each dataset, and the spirals are sensitive to that setting.
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') 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_scaled <- wdi %>%
select(where(is.numeric)) %>%
scale()
fviz_nbclust(wdi_scaled,
FUNcluster = kmeans,
method = 'wss',
) +
labs(title = 'WSS vs k using kmeans') +
fviz_nbclust(wdi_scaled,
FUNcluster = kmeans,
method = 'silhouette',
) +
labs(title = 'Avg silhouette vs k using kmeans')The plots support the claim. 3–5 clusters could work, but 3 or 4 seem like the best choices. The WSS plot has a elbow at k = 3, where the big drops start to level off. The average silhouette is highest at k = 2 (about 0.36), but k = 3 (0.34) and k = 4 (0.35) are very close.
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.
library(FactoMineR)
wdi <- read.csv('Data/wdi_extract_clean.csv') %>%
column_to_rownames('country') %>%
mutate(across(everything(), as.numeric)) %>%
drop_na()
wdi_scaled <- scale(wdi)
set.seed(415)
kmeans4 <- kmeans(wdi_scaled, centers = 4, iter.max = 20, nstart = 10)
wdi_pca <- PCA(wdi, graph = FALSE)
#| fig-width: 14
#| fig-height: 10
options(ggrepel.max.overlaps = 5)
fviz_pca(wdi_pca,
habillage = factor(kmeans4$cluster),
labelsize = 3,
repel = TRUE) +
ggtitle('K-means 4-cluster solution')Cluster 1: Middle-income developing countries, such as Brazil, China, India and Mexico, with moderate development levels.
Cluster 2: Least developed countries, mostly in sub-Saharan Africa, with high infant mortality and fertility and limited access to electricity and internet. Djibouti stands out for its high trade.
Cluster 3: High-income developed countries with strong economic and health indicators, including the U.S., Japan and Denmark. Gulf states also fall here, with higher emissions.
Cluster 4: Luxembourg, Singapore and Ireland. These wealthy countries stand out because of extremely high imports and exports relative to GDP.
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_sub <- wdi[!rownames(wdi) %in% c('Ireland', 'Singapore', 'Luxembourg'), ]
wdi_sub_scaled <- scale(wdi_sub)
set.seed(415)
kmeans4_sub <- kmeans(wdi_sub_scaled, centers = 4, iter.max = 20, nstart = 10)
wdi_sub_pca <- PCA(wdi_sub, graph = FALSE)
fviz_pca(wdi_sub_pca,
habillage = factor(kmeans4_sub$cluster),
labelsize = 3,
repel = TRUE) +
ggtitle('K-means 4-cluster solution (Ireland, Singapore, Luxembourg removed)')wdi_sub %>%
mutate(cluster = factor(kmeans4_sub$cluster)) %>%
summarize(across(everything(), mean), n = n(), .by = cluster) %>%
arrange(cluster) cluster life_expectancy gdp co2 fert_rate health internet
1 1 72.50608 6261.859 3.0113133 2.202493 6.783840 66.96312
2 2 81.80814 46296.403 9.9726252 1.590214 10.606571 92.17902
3 3 76.50701 17417.137 8.8863414 1.709909 6.850037 85.48740
4 4 62.36323 1276.314 0.4811455 4.538581 5.620048 25.92590
infant_mort electricity imports inflation exports income n
1 15.017910 96.05224 35.37165 5.056925 28.20976 5171.0139 67
2 3.219048 100.00000 33.96523 0.608895 36.29665 38945.3620 21
3 7.331818 98.36364 68.86432 1.003245 70.50575 14692.7329 22
4 46.338710 47.28065 32.18364 28.861006 23.10507 936.1228 31
Removing Ireland, Singapore and Luxembourg barely changes the PCA axes. Dim1 still represents development, and Dim2 still represents trade openness. The clusters do change, though. Instead of a small cluster of extreme trade hubs, k-means creates a larger trade-oriented cluster (cluster 3). It includes countries like Czechia, Hungary, Poland, UAE, Bahrain, Malaysia, Belgium, Viet Nam and Djibouti. These countries move out of the middle-income and high-income clusters, making those groups more focused on development level rather than trade. The least developed cluster (cluster 4) stays mostly the same, except Djibouti moves out. This shows how much those three outliers affected the original clustering.