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.\)

(kNNdistplot(three_spheres, minPts =4)
 + abline(h = 0.1) # original epsilon
 + abline(h = 0.19) # "correct" epsilon
)

integer(0)
(kNNdistplot(ring_moon_sphere, minPts =4)
 + abline(h = 0.13)
  +abline(h = 0.28)
)

integer(0)
(kNNdistplot(two_spirals_sphere, minPts =4)
 + abline(h = 0.1)
 + abline(h = 1.2)
)

integer(0)

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!!
plot_dbscan_results <- function(df,eps,minPts) {
dbscan_obj <- dbscan(df, eps = eps, minPts = minPts)

df$dbcluster <- factor(dbscan_obj$cluster)

plot <- (ggplot(data = df, aes(x = x, y = y, color=dbcluster))
         + geom_point()
         + labs(color='Cluster')
         + theme_classic()
         + labs(color = "Cluster",
                title = paste0("DBSCAN Results (","\u03B5 = ", eps,", minPts = ", minPts, ")")
    )
)

plot
}

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.

(db_spheres <- plot_dbscan_results(three_spheres[,1:2], 0.19, 4))

(db_rms <- plot_dbscan_results(ring_moon_sphere[,1:2], 0.28, 4))

(db_spirals <- plot_dbscan_results(two_spirals_sphere[,1:2], 1.2, 4))

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.

three_spheres$kmeans <- factor(kmeans(scale(three_spheres), 3, iter.max = 10, nstart = 1)$cluster)
ring_moon_sphere$kmeans <- factor(kmeans(scale(ring_moon_sphere), 3, iter.max = 10, nstart = 1)$cluster)
two_spirals_sphere$kmeans <- factor(kmeans(scale(two_spirals_sphere), 3, iter.max = 10, nstart = 1)$cluster)

three_spheres$pam <- factor(pam(three_spheres[,1:2], k=3, nstart=10)$cluster)
ring_moon_sphere$pam <- factor(pam(ring_moon_sphere[,1:2], k=3, nstart=10)$cluster)
two_spirals_sphere$pam <- factor(pam(two_spirals_sphere[,1:2], k=3, nstart=10)$cluster)

ts_k <- (ggplot(data=three_spheres)
         + geom_point(aes(x=x, y=y, color = kmeans))
         + theme_classic()
         + theme(legend.position = "none")
)

rms_k <- (ggplot(data=ring_moon_sphere)
         + geom_point(aes(x=x, y=y, color = kmeans))
         + theme_classic()
         + theme(legend.position = "none")
)

tss_k <- (ggplot(data=two_spirals_sphere)
         + geom_point(aes(x=x, y=y, color = kmeans))
         + theme_classic()
         + theme(legend.position = "none")
)

ts_pam <- (ggplot(data=three_spheres)
         + geom_point(aes(x=x, y=y, color = pam))
         + theme_classic()
         + theme(legend.position = "none")
)

rms_pam <- (ggplot(data=ring_moon_sphere)
         + geom_point(aes(x=x, y=y, color = pam))
         + theme_classic()
         + theme(legend.position = "none")
)

tss_pam <- (ggplot(data=two_spirals_sphere)
         + geom_point(aes(x=x, y=y, color = pam))
         + theme_classic()
         + theme(legend.position = "none")
)

plot_dbscan_results_notitle <- function(df,eps,minPts) {
dbscan_obj <- dbscan(df, eps = eps, minPts = minPts)

df$dbcluster <- factor(dbscan_obj$cluster)

plot <- (ggplot(data = df, aes(x = x, y = y, color=dbcluster))
         + geom_point()
         + labs(color='Cluster')
         + theme_classic()
         + theme(legend.position = "none")
)

plot
}

ts_db <- plot_dbscan_results_notitle(three_spheres[,1:2], 0.19, 4)
rms_db <- plot_dbscan_results_notitle(ring_moon_sphere[,1:2], 0.28, 4)
tss_db <- plot_dbscan_results_notitle(two_spirals_sphere[,1:2], 1.2, 4)

col_ts <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="Three Spheres")
col_rms <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="Ring Moon Sphere")
col_tss <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="Two Spirals Sphere")

row_k <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="k-means")
row_pam <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="PAM")
row_db <- ggplot() + theme_void() + annotate("text", 0.5, 0.5, label="DB Scan")
((plot_spacer() + col_ts + col_rms + col_tss
  + row_k + ts_k + rms_k + tss_k
  + row_pam + ts_pam + rms_pam + tss_pam
  + row_db + ts_db + rms_db + tss_db)
  + plot_layout(ncol = 4, heights = c(1, 1, 1))
  + plot_layout(nrow = 4, heights = c(1, 1, 1))
  )

All three methods are good at placing the three spheres into their clusters, but for the ring moon sphere and the two spirals sphere the DB scan is the only method that places them into the “correct” clusters.

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.

(fviz_nbclust(wdi[,-1], FUNcluster = kmeans, method='wss')
 + fviz_nbclust(wdi[,-1], FUNcluster = kmeans, method='silhouette')
)

I would disagree. The plots using the silhouette method indicate that the optimal number of clusters is 2, potentially 3. We see a significant drop off in average silhouette width when we increase to 4 or 5 clusters. The wss method plots tell a similar story, with 2-3 clusters being best for kmeans and 2-4 clusters being best for pam.

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.

rownames(wdi) <- wdi[,1]

wdi_pca <- prcomp(wdi[,-1], center=TRUE, scale. = TRUE)

kmeans_wdi <- kmeans(scale(wdi[,-1]), centers=4, iter.max = 10, nstart = 5)

pca_coords <- as.data.frame(wdi_pca$x)
pca_coords$country <- rownames(wdi)
pca_coords$cluster <- factor(kmeans_wdi$cluster)
pca_coords$dist <- sqrt(pca_coords$PC1^2 + pca_coords$PC2^2)

top5_each_cluster <- (pca_coords
                      %>% group_by(cluster)
                      %>% arrange(desc(dist))
                      %>% slice(1:5)
                      %>% ungroup()
)

(fviz_pca_biplot(wdi_pca, habillage = pca_coords$cluster, label = "var", repel = TRUE)
  + geom_text_repel(data = top5_each_cluster, aes(x = PC1, y = PC2, label = country, color = cluster), size = 3, show.legend = FALSE)
  + ggtitle("4-cluster solution (labelled the top 5 furthest from (0,0) in each cluster)")
  + guides(color = "none", shape = "none")
)

The first / red cluster contains countries with a high fertility rate and high infant mortality rate, these seem to be mostly African countries. The second / green cluster contains countries with middling levels of all variables. The third / blue cluster contains countries with high healthcare, access to electricity, life expectancy, access to internet, and income. Countries like the US, UAE, Switzerland, and Norway. The fourth / purple cluster contains only the countries Ireland, Singapore, and Luxembourg. These countries have really high exports and imports.

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?

wdi2 <- wdi[!rownames(wdi) %in% c("Ireland", "Singapore", "Luxembourg"), ]

wdi2_pca <- prcomp(wdi2[,-1], center=TRUE, scale. = TRUE)

kmeans_wdi2 <- kmeans(scale(wdi2[,-1]), centers=4, iter.max = 10, nstart = 5)

pca2_coords <- as.data.frame(wdi2_pca$x)
pca2_coords$country <- rownames(wdi2)
pca2_coords$cluster <- factor(kmeans_wdi2$cluster)
pca2_coords$dist <- sqrt(pca2_coords$PC1^2 + pca2_coords$PC2^2)

top5_each_cluster2 <- (pca2_coords
                      %>% group_by(cluster)
                      %>% arrange(desc(dist))
                      %>% slice(1:5)
                      %>% ungroup()
)

(fviz_pca_biplot(wdi2_pca, habillage = pca2_coords$cluster, label = "var", repel = TRUE)
  + geom_text_repel(data = top5_each_cluster2, aes(x = PC1, y = PC2, label = country, color = cluster), size = 3, show.legend = FALSE)
  + ggtitle("4-cluster solution (top 5 furthest from (0,0) in each cluster)")
  + guides(color = "none", shape = "none")
)

The first / blue cluster is the same as before. The second / purple and the third / red clusters are slightly smaller than before because they were absorbed into the new fourth cluster, which Djibouti and UAE now lead with high imports and exports.