Professional Documents
Culture Documents
Hierarchical Clustering
Hierarchical Clustering
The Apriori algorithm uses frequent itemsets to generate association rules, and it is designed to work
on the databases that contain transactions. With the help of these association rule, it determines
how strongly or how weakly two objects are connected. This algorithm uses a breadth-first search and
Hash Tree to calculate the itemset associations efficiently. It is the iterative process for finding
the frequent itemsets from the large dataset.
This algorithm was given by the R. Agrawal and Srikant in the year 1994. It is mainly used for
market basket analysis and helps to find those products that can be bought together.
It can also be used in the healthcare field to find drug reactions for patients.
Frequent itemsets are those items whose support is greater than the threshold value or user-specified
minimum support. It means if A & B are the frequent itemsets together, then individually A and B should
also be the frequent itemset. Suppose there are the two transactions: A= {1,2,3,4,5}, and B= {2,3,7},
in these two transactions, 2 and 3 are the frequent itemsets.
Note: To better understand the apriori algorithm, and related term such as support and confidence,
it is recommended to understand the association rule learning.
Step-1: Determine the support of itemsets in the transactional database, and select the minimum
support and confidence.
Step-2: Take all supports in the transaction with higher support value than the minimum or selected
support value.
Step-3: Find all the rules of these subsets that have higher confidence value than the threshold
or minimum confidence.
Solution:
o In the first step, we will create a table that contains support count (The frequency of each
itemset individually in the dataset) of each itemset in the given dataset.
This table is called the Candidate set or C1.
o Now, we will take out all the itemsets that have the greater support count that the
Minimum Support (2). It will give us the table for the frequent itemset L1.
Since all the itemsets have greater or equal support count than the minimum support, except the E,
so E itemset will be removed.
o In this step, we will generate C2 with the help of L1. In C2, we will create the pair of the itemsets
of L1 in the form of subsets.
o After creating the subsets, we will again find the support count from
the main transaction table of datasets, i.e., how many times these pairs have occurred
together in the given dataset. So, we will get the below table for C2:
o Again, we need to compare the C2 Support count with the minimum support count,
and after comparing, the itemset with less support count will be eliminated from the table C2.
It will give us the below table for L2
o For C3, we will repeat the same two processes, but now we will form the C3
table with subsets of three itemsets together, and will calculate the support count from the dataset.
o Now we will create the L3 table. As we can see from the above C3 table, there is only one
combination of itemset that has support count equal to the minimum support count.
So, the L3 will have only one combination, i.e., {A, B, C}.
Step-4: Finding the association rules for the subsets:
To generate the association rules, first, we will create a new table with the possible rules from
the occurred combination {A, B.C}. For all the rules, we will calculate the Confidence using formula
sup( A ^B)/A. After calculating the confidence value for all rules, we will exclude the rules that have
less confidence than the minimum threshold(50%).
As the given threshold or minimum confidence is 50%, so the first three rules
A ^B → C, B^C → A, and A^C → B can be considered as the strong association rules for the given problem.
The first step is data pre-processing step. Under this, first, we will perform the importing of the libraries.
Before importing the libraries, we will use the below line of code to install the apyori package to use
Below is the code to implement the libraries that will be used for different tasks of the model:
import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd
In the above code, the first line is showing importing the dataset into pandas format.
The second line of the code is used because the apriori() that we will use for training our model takes
the dataset in the format of the list of the transactions. So, we have created an empty list of the
transaction. This list will contain all the itemsets from 0 to 7500. Here we have taken 7501 because,
in Python, the last index is not considered.
To train the model, we will use the apriori function that will be imported from the apyroi package.
This function will return the rules to train the model on the dataset. Consider the below code:
from apyori import apriori
rules= apriori(transactions= tran
In the above code, the first line is to import the apriori function.
In the second line, the apriori function returns the output as the rules. It takes the following parameters:
Here we will follow some more steps, which are given below:
o Displaying the result of the rules occurred from the apriori function
results= list(rules)
results
By executing the above lines of code, we will get the 9 rules. Consider the below output:
Output:
As we can see, the above output is in the form that is not easily understandable. So, we will print all the
Output:
By executing the above lines of code, we will get the below output:
states that the light cream and chicken are bought frequently by most of the customers.
The support for this rule is 0.0045, and the confidence is 29%. Hence, if a customer buys light cream,
it is 29% chances that he also buys chicken, and it is .0045 times appeared in the transactions.
In this algorithm, we develop the hierarchy of clusters in the form of a tree, and this tree-shaped structure is
known as the dendrogram.
Sometimes the results of K-means clustering and hierarchical clustering may look similar, but they both differ
depending on how they work. As there is no requirement to predetermine the number of clusters as we did in the
K-Means algorithm.
1. Agglomerative: Agglomerative is a bottom-up approach, in which the algorithm starts with taking all data
points as single clusters and merging them until one cluster is left.
2. Divisive: Divisive algorithm is the reverse of the agglomerative algorithm as it is a top-down approach.
o Step-2: Take two closest data points or clusters and merge them to form one cluster. So, there will now be
N-1 clusters.
o Step-3: Again, take the two closest clusters and merge them together to form one cluster. There will be N-2
clusters.
o Step-4: Repeat Step 3 until only one cluster left. So, we will get the following clusters. Consider the below
images:
o Step-5: Once all the clusters are combined into one big cluster, develop the dendrogram to divide the
clusters as per the problem.
Note: To better understand hierarchical clustering, it is advised to have a look on k-means clustering
2. Complete Linkage: It is the farthest distance between the two points of two different clusters. It is one of
the popular linkage methods as it forms tighter clusters than single-linkage.
3. Average Linkage: It is the linkage method in which the distance between each pair of datasets is added up
and then divided by the total number of datasets to calculate the average distance between two clusters. It
is also one of the most popular linkage methods.
4. Centroid Linkage: It is the linkage method in which the distance between the centroid of the clusters is
calculated. Consider the below image:
From the above-given approaches, we can apply any of them according to the type of problem or business
requirement.
The working of the dendrogram can be explained using the below diagram:
In the above diagram, the left part is showing how clusters are created in agglomerative clustering, and the right
part is showing the corresponding dendrogram.
o As we have discussed above, firstly, the datapoints P2 and P3 combine together and form a cluster,
correspondingly a dendrogram is created, which connects P2 and P3 with a rectangular shape. The hight is
decided according to the Euclidean distance between the data points.
o In the next step, P5 and P6 form a cluster, and the corresponding dendrogram is created. It is higher than of
previous, as the Euclidean distance between P5 and P6 is a little bit greater than the P2 and P3.
o Again, two new dendrograms are created that combine P1, P2, and P3 in one dendrogram, and P4, P5, and
P6, in another dendrogram.
o At last, the final dendrogram is created that combines all the data points together.
We can cut the dendrogram tree structure at any level as per our requirement.
The dataset is containing the information of customers that have visited a mall for shopping. So, the mall owner
wants to find some patterns or some particular behavior of his customers using the dataset information.
1. Data Pre-processing
2. Finding the optimal number of clusters using the Dendrogram
3. Training the hierarchical clustering model
4. Visualizing the clusters
The above lines of code are used to import the libraries to perform specific tasks, such as numpy for the
Mathematical operations, matplotlib for drawing the graphs or scatter plot, and pandas for importing the dataset.
As discussed above, we have imported the same dataset of Mall_Customers_data.csv, as we did in k-means
clustering. Consider the below output:
Here we have extracted only 3 and 4 columns as we will use a 2D plot to see the clusters. So, we are considering
the Annual income and spending score as the matrix of features.
In the above lines of code, we have imported the hierarchy module of scipy library. This module provides us a
method shc.denrogram(), which takes the linkage() as a parameter. The linkage function is used to define the
distance between two clusters, so here we have passed the x(matrix of features), and method "ward," the popular
method of linkage in hierarchical clustering.
The remaining lines of code are to describe the labels for the dendrogram plot.
Output:
By executing the above lines of code, we will get the below output:
Using this Dendrogram, we will now determine the optimal number of clusters for our model. For this, we will find
the maximum vertical distance that does not cut any horizontal bar. Consider the below diagram:
In the above diagram, we have shown the vertical distances that are not cutting their horizontal bars. As we can
visualize, the 4th distance is looking the maximum, so according to this, the number of clusters will be 5(the
vertical lines in this range). We can also take the 2nd number as it approximately equals the 4th distance, but we will
consider the 5 clusters because the same we calculated in the K-means algorithm.
So, the optimal number of clusters will be 5, and we will train the model in the next step, using the same.
In the above code, we have imported the AgglomerativeClustering class of cluster module of scikit learn library.
Then we have created the object of this class named as hc. The AgglomerativeClustering class takes the following
parameters:
o n_clusters=5: It defines the number of clusters, and we have taken here 5 because it is the optimal number
of clusters.
o affinity='euclidean': It is a metric used to compute the linkage.
o linkage='ward': It defines the linkage criteria, here we have used the "ward" linkage. This method is the
popular linkage method that we have already used for creating the Dendrogram. It reduces the variance in
each cluster.
In the last line, we have created the dependent variable y_pred to fit or train the model. It does train not only the
model but also returns the clusters to which each data point belongs.
After executing the above lines of code, if we go through the variable explorer option in our Sypder IDE, we can
check the y_pred variable. We can compare the original dataset with the y_pred variable. Consider the below
image:
As we can see in the above image, the y_pred shows the clusters value, which means the customer id 1 belongs to
the 5th cluster (as indexing starts from 0, so 4 means 5th cluster), the customer id 2 belongs to 4th cluster, and so on.
Here we will use the same lines of code as we did in k-means clustering, except one change. Here we will not plot
the centroid that we did in k-means, because here we have used dendrogram to determine the optimal number of
clusters. The code is given below:
Output: By executing the above lines of code, we will get the below output: