How to do Agglomerative Clustering in R?

This recipe helps you do Agglomerative Clustering in R

Recipe Objective

Organised logical groups of information is preferred over unorganised data by people. For example, anyone finds it easier to remember information when it is clustered together by taking its common characteristics into account.

Likewise, A machine learning technique that provides a way to find groups/clusters of different observations within a dataset is called Clustering. In this technique due to the absence of response variable, it is considered to be an unsupervised method. This implies that the relationships between 'n' number of observations is found without being trained by a response variable. The few applications of Clustering analysis are ​

  1. Customer segmentation: process for dividing customers into groups based on similar characteristics.
  2. Stock Market Clustering based on the performance of the stocks
  3. Reducing Dimensionality

There are two most common Clustering algorithm that is used: ​

  1. KMeans Clustering: commonly used when we have large dataset
  2. Heirarchical or Agglomerative Clustering: commonly used when we have small dataset

Agglomerative Clustering is an unsupervised machine learning technique that aims to groups the unlabeled dataset by building a heirarcy of clusters. It is relatively slow compared to heirarchichal clustering. There are two types of Heirarchical clustering algorithm: Divisive (top-down appraoch) and Agglomerative (bottom-up approach). ​

The most commonly used is the agglomerative algorithm. In this algorithm, data is split into n clusters where n is the observations in the dataset initially. The next step is the calculation of euclidean distances between data points. Then, the number of clusters are reduced because the two clusters merges into one in an iterative manner considering the distances between them. This process of merging stops when only one cluster remains. The hierarchy of clusters is represented by Dendrogram (a tree-like structure) ​

This recipe demonstrates Heirarchical Clustering using Agglomerative algorithm on a real-life Mall dataset to carry out customer segmentation in R-language. ​

STEP 1: Importing Necessary Libraries

# For Data Manipulation library(tidyverse) # For Clustering algorithm library(cluster)

STEP 2: Loading the Dataset

Dataset description: It is a basic data about the customers going to the supermarket mall. This can be used for customer segmentation. There are 200 observations(customers) and no missing data.

It consists of four columns ie. measured attrutes: ​

  1. CustomerID is the customer identification number.
  2. Gender is Female and Male.
  3. Age is the age of customers.
  4. Annual Income (k) is the annual income of clients in thousands of dollars.
  5. Spending Score (1-100) is the spending score assigned by the shopping center according to the customer's purchasing behavior
# creating a dataframe customer_seg customer_seg = read.csv('R_348_Mall_Customers.csv') # getting the required information about the dataset glimpse(customer_seg)
Observations: 200
Variables: 5
$ CustomerID              1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1...
$ Gender                  Male, Male, Female, Female, Female, Female, ...
$ Age                     19, 21, 20, 23, 31, 22, 35, 23, 64, 30, 67, ...
$ Annual.Income..k..      15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, ...
$ Spending.Score..1.100.  39, 81, 6, 77, 40, 76, 6, 94, 3, 72, 14, 99,...

For the simplicity of demonstrating heirarchichal Clustering with visualisation, we will only consider two measured attributes (Age and Annual Income). ​

# assigning columns 3 and 4 to a new dataset customer_prep customer_prep = customer_seg[3:4]

STEP 3: Data Preprocessing (Scaling)

This is a pre-modelling step. In this step, the data must be scaled or standardised so that different attributes can be comparable. Standardised data has mean zero and standard deviation one. we do thiis using scale() function

Note: Scaling is an important pre-modelling step which has to be mandatory

# scaling the dataset customer_prep = scale(customer_prep) customer_prep %>% head()
Age		Annual.Income..k..
-1.4210029	-1.734646
-1.2778288	-1.734646
-1.3494159	-1.696572
-1.1346547	-1.696572
-0.5619583	-1.658498
-1.2062418	-1.658498

STEP 4: Calculating the distances between the observations/datapoints

We use the dist() function to carry this out task. It calculates the euclidean distances between the datapoints. We create an object 'distances' to store this information.

distances = dist(customer_prep, method = 'euclidean') distances %>% head()
0.143174096235284 0.0810822191043143 0.288868323164455 0.862412934253182 0.227861432257651 1.15107392658714

STEP 5: Performing Heirarchical clustering

We will use hclust() function in cluster library in R to perform this. The two arguements used below are:

  1. Distances between the point
  2. method of evaluation: Ward's method (Ward.D)
# This is an assignment of random state set.seed(50) # creation of an object km which store the output of the function kmeans h_clust = hclust(distances, method = 'ward.D') # plotting the dendrogram to represent Heirarchical Clustering plot(h_clust, main = paste('Dendrogram'), xlab = 'Customers', ylab = 'Euclidean distances')

STEP 6: Data Visualization using scatter plot with specified number of clusters

We use cutree() function in cluster library to specify the number of clusters to be formed. This function cuts the dendrogram in such a way that only the specified number of clusters are obtained. In our case, we will use 5 number of clusters.

y = cutree(h_clust, 5) # y is a vector of integers that showcases the cluster in which each observation lies.

We use clusplot to plot theclusters in a scatter plot w.r.t Age and Income

# using clusplot() function with various arguements to plot the clusters clusplot(customer_prep, y, shade = TRUE, color = TRUE, span = TRUE, main = paste('Clusters of customers'), xlab = 'Age', ylab = 'Annual Income')

This plot helps us to analyse the different clusters of customers formed so that we can target the respective clusters seperately in our marketing strategy.

What Users are saying..

profile image

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

Create Your First Chatbot with RASA NLU Model and Python
Learn the basic aspects of chatbot development and open source conversational AI RASA to create a simple AI powered chatbot on your own.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Build a Collaborative Filtering Recommender System in Python
Use the Amazon Reviews/Ratings dataset of 2 Million records to build a recommender system using memory-based collaborative filtering in Python.