# Hierarchical K-Means Clustering: Optimize Clusters 
# https://www.datanovia.com/en/lessons/hierarchical-k-means-clustering-optimize-clusters/

# Install factoextra package if needed
if(!require(factoextra)) install.packages("factoextra", repos = "http://cran.us.r-project.org")

# Load factoextra library
library(factoextra)

res.hk <-hkmeans(data.frame(som.model$codes), k)

# Elements returned by hkmeans()
names(res.hk)

# Print the results
str(res.hk)

# Visualize the tree
fviz_dend(res.hk, cex = 0.6, palette = "jco", 
          rect = TRUE, rect_border = "jco", rect_fill = TRUE)

# Visualize the hkmeans final clusters
fviz_cluster(res.hk, palette = "jco", repel = TRUE,
             ggtheme = theme_classic())

plot(som.model,
     main = '',
     type = "property",
     property = res.hk$hclust$order,
     palette.name = topo.colors)

add.cluster.boundaries(som.model, res.hk$hclust$order)