


Understanding hierarchical clustering in one article (Python code)
First of all, clustering belongs to unsupervised learning of machine learning, and there are many methods, such as the well-known K-means. Hierarchical clustering is also a type of clustering and is also very commonly used. Next, I will briefly review the basic principles of K-means, and then slowly introduce the definition and hierarchical steps of hierarchical clustering, which will be more helpful for everyone to understand.
What is the difference between hierarchical clustering and K-means?
The working principle of K-means can be briefly summarized as:
- Determine the number of clusters (k)
- Randomly select k points from the data as centroids
- Assign all points to the nearest cluster centroid
- Calculate the centroid of the newly formed cluster
- Repeat steps 3 and 4
This is an iteration process until the centroids of newly formed clusters remain unchanged or the maximum number of iterations is reached.
But K-means has some shortcomings. We must decide the number of clusters K before the algorithm starts. But actually we don’t know how many clusters there should be, so we usually base it on our own understanding. Set a value first, which may lead to some deviations between our understanding and the actual situation.
Hierarchical clustering is completely different. It does not require us to specify the number of clusters at the beginning. Instead, it first completely forms the entire hierarchical clustering, and then by determining the appropriate distance, the corresponding cluster number and sum can be automatically found. clustering.
What is hierarchical clustering?
Let’s introduce what hierarchical clustering is from shallow to deep. Let’s start with a simple example.
Suppose we have the following points and we want to group them:
We can assign each of these points to a separate cluster, Just 4 clusters (4 colors):
Then based on the similarity (distance) of these clusters, the most similar (closest) points are grouped together and Repeat this process until only one cluster remains:
The above is essentially building a hierarchy. Let’s understand this first, and we will introduce its layering steps in detail later.
Types of hierarchical clustering
There are two main types of hierarchical clustering:
- Agglomerative hierarchical clustering
- Split hierarchical clustering
Agglomerative hierarchical clustering
First let all points become a separate cluster, and then continue to combine them through similarity until there is only one cluster in the end. This is agglomerative hierarchical clustering. The process is consistent with what we just said above.
Split hierarchical clustering
Split hierarchical clustering is just the opposite. It starts from a single cluster and gradually splits it until it cannot be split, that is, each point is a cluster.
So it doesn’t matter whether there are 10, 100, or 1000 data points, these points all belong to the same cluster at the beginning:
Now, Split the two furthest points in the cluster at each iteration, and repeat this process until each cluster contains only one point:
#The above process is splitting Hierarchical clustering.
Steps to perform hierarchical clustering
The general process of hierarchical clustering has been described above, but now comes the key point, how to determine the similarity between points?
This is one of the most important issues in clustering. The general method of calculating similarity is to calculate the distance between the centroids of these clusters. The points with minimum distance are called similar points and we can merge them or we can call it distance based algorithm.
Also in hierarchical clustering, there is a concept called proximity matrix, which stores the distance between each point. Below we use an example to understand how to calculate similarity, proximity matrix, and the specific steps of hierarchical clustering.
Case Introduction
Suppose a teacher wants to divide students into different groups. Now I have the scores of each student on the assignment, and I want to divide them into groups based on these scores. There is no set goal here as to how many groups to have. Since the teacher does not know which type of students should be assigned to which group, it cannot be solved as a supervised learning problem. Below, we will try to apply hierarchical clustering to classify students into different groups.
The following are the results of 5 students:
Create a proximity matrix
First, we need to create a proximity matrix, which stores the distance between each point, so we can get a shape of n Square matrix of X n.
In this case, the following 5 x 5 proximity matrix can be obtained:
There are two points to note in the matrix:
- The diagonal elements of a matrix are always 0 because the distance of a point from itself is always 0
- Use the Euclidean distance formula to calculate the distance of non-diagonal elements
For example, if we want to calculate the distance between points 1 and 2, the calculation formula is:
Similarly, fill in the remaining elements of the proximity matrix after completing this calculation method.
Perform hierarchical clustering
This is implemented using agglomerative hierarchical clustering.
Step 1: First, we assign all points into a single cluster:
Here different colors represent different clusters, 5 of them in our data point, that is, there are 5 different clusters.
Step 2: Next, we need to find the minimum distance in the proximity matrix and merge the points with the smallest distance. Then we update the proximity matrix:
The minimum distance is 3, so we will merge points 1 and 2:
With a dendrogram, we can clearly visualize the steps of hierarchical clustering. The farther apart the vertical lines in the dendrogram are, the greater the distance between clusters.
With this dendrogram, it is much easier for us to determine the number of clusters.
Now we can set a threshold distance and draw a horizontal line. For example, we set the threshold to 12 and draw a horizontal line as follows:
As you can see from the intersection point, the number of clusters is the intersection of the threshold horizontal line and the vertical line quantity (red line intersects 2 vertical lines, we will have 2 clusters). Corresponding to the abscissa, one cluster will have a sample set (1,2,4), and the other cluster will have a sample set (3,5).
In this way, we solve the problem of determining the number of clusters in hierarchical clustering through a dendrogram.
Python code practical case
The above is the theoretical basis, and anyone with a little mathematical foundation can understand it. Here's how to implement this process using Python code. Here is a customer segmentation data to show.
The data set and code are in my GitHub repository:
https://github.com/xiaoyusmd/PythonDataScience
If you find it helpful, please give it a star!
This data comes from the UCI machine learning library. Our aim is to segment wholesale distributors’ customers based on their annual spend on different product categories such as milk, groceries, regions, etc.
First standardize the data to make all data in the same dimension easy to calculate, and then apply hierarchical clustering to segment customers.
from sklearn.preprocessing import normalize data_scaled = normalize(data) data_scaled = pd.DataFrame(data_scaled, columns=data.columns) import scipy.cluster.hierarchy as shc plt.figure(figsize=(10, 7)) plt.title("Dendrograms") dend = shc.dendrogram(shc.linkage(data_scaled, method='ward'))
The x-axis contains all samples, and the y-axis represents the distance between these samples. The vertical line with the largest distance is the blue line. Suppose we decide to cut the dendrogram with a threshold of 6:
plt.figure(figsize=(10, 7)) plt.title("Dendrograms") dend = shc.dendrogram(shc.linkage(data_scaled, method='ward')) plt.axhline(y=6, color='r', linestyle='--')
Now that we have two clusters, we need to Apply hierarchical clustering on clusters:
from sklearn.cluster import AgglomerativeClustering cluster = AgglomerativeClustering(n_clusters=2, affinity='euclidean', linkage='ward') cluster.fit_predict(data_scaled)
Since we have defined 2 clusters, we can see the values of 0 and 1 in the output. 0 represents a point belonging to the first cluster, and 1 represents a point belonging to the second cluster.
plt.figure(figsize=(10, 7)) plt.scatter(data_scaled['Milk'], data_scaled['Grocery'], c=cluster.labels_)
At this point we have successfully completed clustering.
The above is the detailed content of Understanding hierarchical clustering in one article (Python code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
