Path: blob/master/Part 4 - Clustering/Hierarchical Clustering/hc.R
1009 views
# Hierarchical Clustering12# Importing the dataset3dataset = read.csv('Mall_Customers.csv')4dataset = dataset[4:5]56# Splitting the dataset into the Training set and Test set7# install.packages('caTools')8# library(caTools)9# set.seed(123)10# split = sample.split(dataset$DependentVariable, SplitRatio = 0.8)11# training_set = subset(dataset, split == TRUE)12# test_set = subset(dataset, split == FALSE)1314# Feature Scaling15# training_set = scale(training_set)16# test_set = scale(test_set)1718# Using the dendrogram to find the optimal number of clusters19dendrogram = hclust(d = dist(dataset, method = 'euclidean'), method = 'ward.D')20plot(dendrogram,21main = paste('Dendrogram'),22xlab = 'Customers',23ylab = 'Euclidean distances')2425# Fitting Hierarchical Clustering to the dataset26hc = hclust(d = dist(dataset, method = 'euclidean'), method = 'ward.D')27y_hc = cutree(hc, 5)2829# Visualising the clusters30library(cluster)31clusplot(dataset,32y_hc,33lines = 0,34shade = TRUE,35color = TRUE,36labels= 2,37plotchar = FALSE,38span = TRUE,39main = paste('Clusters of customers'),40xlab = 'Annual Income',41ylab = 'Spending Score')4243