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.\)
ts_scaled <- scale(three_spheres)
rms_scaled <- scale(ring_moon_sphere)
tss_scaled <- scale(two_spirals_sphere)
kNNdistplot(ts_scaled, minPts = 4)
abline(h = 0.3)kNNdistplot(rms_scaled, minPts = 4)
abline(h = 0.18)kNNdistplot(tss_scaled, minPts = 4)
abline(h = 0.03)
abline(h = 0.22)There Spheres seems to have a clear elbow right around 0.3, Ring, Moon, Sphere seems to also have a clear elbow around 0.18, however Two Spiral Sphere seems to be two places that could be the correct elbow, one at 0.03 and the other at 0.22.
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){
db <- dbscan::dbscan(df, eps = eps, minPts = minPts)
plot_df <- as_tibble(df) %>%
mutate(cluster = factor(db$cluster)) %>%
rename(x = 1, y = 2)
g <- ggplot(plot_df, aes(x = x, y = y, color = cluster)) +
geom_point(size = 2, alpha = 0.8) +
labs(
title = paste("DBSCAN"),
color = "Cluster"
) +
theme_minimal()
return(g)
}plot_dbscan_results(ts_scaled, eps = 0.42, minPts = 4)plot_dbscan_results(rms_scaled, eps = 0.267, minPts = 4)plot_dbscan_results(tss_scaled, eps = 0.27, minPts = 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.
plot_kmeans <- function(df, k){
km <- kmeans(df, centers = k, nstart = 10)
as_tibble(df) %>%
mutate(cluster = factor(km$cluster)) %>%
rename(x = 1, y = 2) %>%
ggplot(aes(x, y, color = cluster)) +
geom_point(size = 2, alpha = 0.8) +
labs(title = paste("K-means" ),
color = "Cluster") +
theme_minimal()
}
plot_pam <- function(df, k, nstart = 10){
pam_res <- cluster::pam(df, k)
as_tibble(df) %>%
mutate(cluster = factor(pam_res$clustering)) %>%
rename(x = 1, y = 2) %>%
ggplot(aes(x, y, color = cluster)) +
geom_point(size = 2, alpha = 0.8) +
labs(title = paste("PAM"),
color = "Cluster") +
theme_minimal()
}
ts_db <- plot_dbscan_results(ts_scaled, eps = 0.42, minPts = 4)
rms_db <- plot_dbscan_results(rms_scaled, eps = 0.267, minPts = 4)
tss_db <- plot_dbscan_results(tss_scaled, eps = 0.27, minPts = 4)
ts_km <- plot_kmeans(ts_scaled, 3)
ts_pam <- plot_pam(ts_scaled, 3)
rms_km <- plot_kmeans(rms_scaled, 3)
rms_pam <- plot_pam(rms_scaled, 3)
tss_km <- plot_kmeans(tss_scaled, 3)
tss_pam <- plot_pam(tss_scaled, 3)
(ts_db| rms_db | tss_db ) /
(ts_km| rms_km |tss_km ) /
(ts_pam| rms_pam |tss_pam )Three Spheres:
- All three methods found the known clusters within the data
Ring, Moon, Sphere:
- DBSCAN did much better at identifying the 3 main clusters, both k-means and PAM reported similar results
Two Spiral Sphere:
- DBSCAN did the best at identifying the groupings, k-means made groupings in pizza shaped groups where PAM made stripes within the points
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_numeric <- wdi %>% select(-country)
wdi_scaled <- scale(wdi_numeric)
fviz_nbclust(wdi_scaled,
FUNcluster = kmeans,
method='wss',
) +
labs(title = 'Plot of WSS vs k using kmeans') +
fviz_nbclust(wdi_scaled,
FUNcluster = kmeans,
method='silhouette',
)+
labs(title = 'Plot of avg silhouette vs k using kmeans')I support your claim because the silhouette plot shows that the highest average silhouette width is at k=4, the WSS shows an elbow but it is hard to tell if it starts at 3,4, or 5 all which support your claim.
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.
wdi_numeric1 <- wdi %>%
column_to_rownames("country")
wdi_km <- kmeans(wdi_scaled, centers = 4, nstart = 10)
wdi$cluster <- factor(wdi_km$cluster)
wdi_pca <- prcomp(wdi_numeric1, center=TRUE, scale. = TRUE)
kmeans_biplot <- fviz_pca(wdi_pca,
habillage = factor(wdi_km$cluster),
repel = TRUE) +
ggtitle('K-means 4-cluster solution') +
guides(color='none',shape='none')Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
ℹ The deprecated feature was likely used in the ggpubr package.
Please report the issue at <https://github.com/kassambara/ggpubr/issues>.
kmeans_biplotOrange Cluster:
- Countries within the orange cluster have high fertility rate, infant mortality and inflation. Some countries that follow these characteristics are many countries in Africa like Angola, Niger, Zambia and many others.
Green Cluster:
- The green cluster tends to be countries that have either high or low amounts of imports and export and not large amounts of the other factors. Some countries that follow these characteristics are countries like China, Philippines, Cabo, Thailand and much more.
Purple Cluster:
- The purple cluster is the smallest cluster of them all only have 3 countries within it, Ireland, Singapore, and Luxembourg. These countries all have very high amounts of imports and exports.
Blue Cluster:
- The blue cluster are countries that have high life expectancy, income, GDP, electricity and other factors. Some countries that follow these characteristics are countries like Denmark, Iceland, Netherlands, and Norway.
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_less <- wdi %>%
select(-cluster) %>%
filter(!country %in% c("Ireland", "Singapore", "Luxembourg")) %>%
column_to_rownames("country")
less_scaled <- scale(wdi_less)
less_km <- kmeans(less_scaled, centers = 4, nstart = 10)
wdi_less$cluster <- factor(less_km$cluster)
less_pca <- prcomp(less_scaled, center = TRUE, scale. = TRUE)
kmeans_biplot <- fviz_pca(less_pca,
habillage = factor(less_km$cluster),
#label = "none",
repel = TRUE) +
ggtitle('K-means 4-cluster solution') +
guides(color='none',shape='none')
kmeans_biplotThe cluster definitions changed a lot because it got rid of the small 3 country cluster and remade the 4 clusters. It kept the two left most groups very similar but the right grouping or blue cluster above it split it into two. It split them based on if they had high imports and exports or if their health, income, or GDP were high.