Machine Learning Concepts, Clustering, Part: 1
By Gencay
Published: 2024-03-02
URL: https://www.learnwithmeai.com/p/clustering-essentials-here-is-how

Welcome to our #LearnAI series. Today, we're talking about Clustering, a key technique in Machine Learning.
Our article is here to help you get good at Clustering with Python, regardless of your skill level.
We'll cover what Clustering is, why it's useful, and show you how to do it with Python examples and more.
You can again replicate what you learn in this article with our LearnAIWithMe GPT, which is available for our paid subscribers. Let’s start!
Here is the link to LearnAIWithMe GPT.
Step 1: Overview of Clustering
Clustering is a technique used in unsupervised machine learning, where the goal is to group a set of objects so that objects in the same cluster are more similar to each other than objects in other clusters.
The criteria for similarity are often distance, frequency, or a form of statistical distribution.
Step 2: Most Used Clustering Algorithms
K-Means is one of the simplest and most popular clustering algorithms. It aims to partition a set of observations into a predefined number of clusters. Here's how it works:
- Initialization: Choose K points as initial centroids (the K in K-Means represents the number of clusters).
- Assignment: Assign each data point to the nearest centroid. These steps form K clusters.
- Update: Calculate the new centroids (mean) of the clusters formed in the assignment step.
- Repeat: Repeat the assignment and update steps until convergence (i.e., centroids do not change in subsequent iterations).
Key Features of K-Means Clustering:
- It's efficient for large datasets.
- It often works well, even with some assumptions being broken.
- The shape of the clusters is hyper-spherical (around centroids).
K-Means Clustering
K-Means is one of the most popular and simple clustering algorithms. It aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster.
Key aspects of K-Means Clustering:
- Centroids: The algorithm randomly initializes k centroids, where k is a user-defined number of clusters.
- Assignment Step: Each data point is assigned to its nearest centroid based on the squared Euclidean distance.
- Update Step: The centroids are recomputed as the mean of all data points belonging to the cluster.
- Iteration: The assignment and update steps are repeated iteratively until convergence, which occurs when the assignments no longer change.
K-Means is best suited for datasets where the clusters have a spherical shape, and it's relatively efficient on large datasets.
Where K-Means Clustering Can Be Used?
K-Means clustering is versatile and can be applied in various domains. Some of the key areas where K-Means is commonly used include:
- Market Segmentation: Businesses use K-Means to segment customers based on similarities in purchasing behavior, preferences, or demographics. This helps in targeting marketing strategies more effectively.
- Document Clustering: In text mining, K-Means is used to group similar documents, which aids in organizing large volumes of digital data and improving information retrieval systems.
- Image Segmentation: K-Means can be applied in image analysis for segmenting digital images into distinct regions. This is useful in medical imaging, traffic control systems, and satellite image analysis.
- Inventory Categorization: Grouping products in an inventory based on sales activity or other characteristics to optimize the supply chain.
- Anomaly Detection: In cybersecurity, K-Means can help identify unusual patterns that might indicate fraudulent activity.
- Cluster Analysis in Social Networking: Analyzing social networks to identify groups of friends or communities with common interests or connections.
This list is not exhaustive but highlights some of the most common applications of K-Means clustering.
Hierarchical Clustering (Agglomerative Clustering)
Hierarchical clustering is another popular method used in data analysis, which seeks to build a hierarchy of clusters. There are two types of hierarchical clustering: Agglomerative and Divisive. Agglomerative is the more commonly used approach, often called hierarchical clustering.
Key aspects of Hierarchical Clustering:
- Bottom-Up Approach: In agglomerative clustering, each observation starts in its cluster, and pairs of clusters are merged as one moves up the hierarchy.
- Dendrogram: The result of hierarchical clustering can be represented as a tree-like diagram called a dendrogram, which shows the arrangement of the clusters produced by the respective algorithm.
- Distance Metrics and Linkage Criteria: The choice of distance metrics (like Euclidean or Manhattan distance) and linkage criteria (like Ward’s method, average linkage, complete linkage) can significantly affect the outcomes of the clusters.
- No Need to Specify Number of Clusters: Unlike K-means, hierarchical clustering does not require the user to specify the number of clusters beforehand. The number of clusters can be decided by looking at the dendrogram.
Hierarchical clustering is particularly useful for understanding the data structure or when the number of clusters is unknown a priori.
Where Hierarchical Clustering Can Be Used?
Hierarchical clustering is versatile and can be applied in various fields and scenarios. Some of the key applications include:
- Biological Sciences: It's widely used for genetic and ecological data analysis. For example, it can help understand the evolutionary relationships between different species or strains of organisms.
- Document Clustering: Similar to K-Means, hierarchical clustering can also be used for grouping documents based on similarities in content. It's particularly useful when the structure or the number of document clusters is not known in advance.
- Customer Segmentation: In marketing, hierarchical clustering helps in segmenting customers based on various factors like buying behavior, preferences, demographics, etc., but with more flexibility in defining the number of segments.
- Social Network Analysis: It can identify communities or groups within social networks based on the strength and pattern of connections.
- Healthcare Data Analysis: Hierarchical clustering finds use in analyzing patient data, identifying groups of patients with similar symptoms or medical histories, which can aid in diagnosis and treatment planning.
- Financial Analysis: It can be used for portfolio management, identifying groups of stocks that move together, which is important for risk management and investment strategy formulation.
The hierarchical structure of the clusters can provide additional insights into the data, which is particularly useful in exploratory data analysis.
DBSCAN (Density-Based Spatial Clustering of Applications with Noise)
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a popular clustering algorithm known for its ability to identify clusters of arbitrary shapes and handle noise and outliers.
Key aspects of DBSCAN:
- Density-Based: Unlike centroid-based algorithms like K-Means, DBSCAN works on the idea of density. A cluster in DBSCAN is defined as a maximum set of densely connected points.
- Two Parameters: DBSCAN primarily requires ε (eps) and the minimum number of points required to form a dense region (minPts). ε defines the radius around each data point to search for neighboring points, and minPts specifies the minimum number of points required to form a cluster.
- Handles Noise: DBSCAN can identify and separate noise points (outliers) from clusters' core and border points, making it robust to outliers.
- No Need to Specify Number of Clusters: DBSCAN does not require specifying the number of clusters a priori, which is advantageous in many real-world scenarios.
DBSCAN is particularly useful in scenarios where the data contains clusters of varying shapes and densities.
Where DBScan Can Be Used?
DBSCAN's unique approach to clustering makes it suitable for various applications, especially where the data is complex or irregular. Some of the key use cases include:
- Geospatial Analysis: DBSCAN is ideal for spatial data analysis, such as identifying geographical areas of similar land use or clustering regions based on points of interest.
- Anomaly Detection: Its ability to separate noise or outliers from core points of a cluster makes it suitable for anomaly detection in various domains, including fraud detection in financial transactions and fault detection in industrial settings.
- Astronomy: DBSCAN is used for star cluster identification in astronomical datasets, where the clusters may be of arbitrary shapes and sizes.
- Environmental Studies: In environmental science, DBSCAN can identify natural phenomena, like clusters of similar environmental conditions or habitats.
- Molecular Biology: It analyzes spatial data in molecular biology, such as clustering proteins or genes with similar expression patterns.
- Traffic Analysis: In urban planning and traffic management, DBSCAN can help identify clusters of traffic hotspots or accident-prone areas.
DBSCAN's flexibility in dealing with different shapes and sizes of clusters and its tolerance for noise make it a powerful tool for these and many other applications.
Application of Clustering Algorithms
To demonstrate and compare the three clustering methods – K-Means, Hierarchical Clustering, and DBSCAN – we'll use a prebuilt dataset from the Scikit-Learn library. Here's the plan:
- Load a Dataset: We'll choose an appropriate dataset from Scikit-Learn's collection.
- Apply Clustering Algorithms:
- K-Means
- Hierarchical Clustering (Agglomerative Clustering)
- DBSCAN
- Visualize the Clusters: We'll visualize the clusters formed for each method.
- Evaluate and Compare: We'll use some of the evaluation metrics to compare the performance of these clustering algorithms on the dataset.
Let's start by loading a dataset and applying these clustering methods. I'll proceed with the coding part to execute these steps. Here is the code;
from sklearn import datasets
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
import numpy as np
# Load a dataset
X, y = datasets.make_moons(n_samples=300, noise=0.05, random_state=42)
# Apply K-Means Clustering
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans_labels = kmeans.fit_predict(X)
# Apply Hierarchical Clustering
hierarchical = AgglomerativeClustering(n_clusters=2)
hierarchical_labels = hierarchical.fit_predict(X)
# Apply DBSCAN
dbscan = DBSCAN(eps=0.2, min_samples=5)
dbscan_labels = dbscan.fit_predict(X)
# Plotting the clusters
plt.figure(figsize=(18, 5))
# K-Means Clustering
plt.subplot(1, 3, 1)
plt.scatter(X[:, 0], X[:, 1], c=kmeans_labels, cmap='viridis', s=50)
plt.title('K-Means Clustering')
# Hierarchical Clustering
plt.subplot(1, 3, 2)
plt.scatter(X[:, 0], X[:, 1], c=hierarchical_labels, cmap='viridis', s=50)
plt.title('Hierarchical Clustering')
# DBSCAN
plt.subplot(1, 3, 3)
plt.scatter(X[:, 0], X[:, 1], c=dbscan_labels, cmap='viridis', s=50)
plt.title('DBSCAN')
plt.show()
# Evaluating the clustering performance using Silhouette Score
kmeans_silhouette = silhouette_score(X, kmeans_labels)
hierarchical_silhouette = silhouette_score(X, hierarchical_labels)
dbscan_silhouette = silhouette_score(X, dbscan_labels)
(kmeans_silhouette, hierarchical_silhouette, dbscan_silhouette)
Now, let’s see the output;

Let’s see the evaluation of it.
- K-Means Clustering:
- Visualization: The clusters are distinctly separated, but the circular nature of K-Means is apparent in how it assigns clusters.
- Silhouette Score: 0.488
- Hierarchical Clustering (Agglomerative):
- Visualization: Similar to K-Means, Agglomerative Clustering has formed two distinct clusters.
- Silhouette Score: 0.441
- DBSCAN:
- Visualization: DBSCAN has identified the two moon shapes more effectively, thanks to its ability to handle arbitrary shapes and densities.
- Silhouette Score: 0.331
From the visualizations, it's evident that DBSCAN performs better in capturing the non-linear structure of the data (the two moon shapes). However, the Silhouette Score is lower for DBSCAN than for K-Means and Hierarchical Clustering. This discrepancy is because the Silhouette Score may favor more globular (spherical) clusters, which suits K-Means and Hierarchical Clustering.
In summary, while K-Means and Hierarchical Clustering achieved higher silhouette scores, DBSCAN more accurately captured the true structure of the dataset. This comparison highlights the importance of choosing the right clustering algorithm based on the data's characteristics and the problem.
Clustering Evaluation Metrics

Step 3: Initial Steps in Clustering
Data Preprocessing
- Handling Missing Values: It’s important to address missing data through imputation or removal, as missing values can skew the clustering results.
- Normalizing Data: Feature scaling (like normalization or standardization) is crucial, especially in algorithms sensitive to the distance between data points (like K-Means and Hierarchical clustering).
- Encoding Categorical Variables: Transforming non-numeric categories into numeric values (e.g., using one-hot encoding) is necessary for most clustering algorithms.
Feature Selection and Engineering
- Choosing Relevant Features: Selecting the features that contribute most to the clustering can significantly improve results.
- Creating New Features: Sometimes, deriving new features from existing ones (feature engineering) can provide better insight and improve clustering quality.
Splitting Data for Training and Testing
- Unlike supervised learning, clustering usually doesn’t involve a distinct training and testing phase. However, in some cases, especially for validating the robustness of the clustering model, the dataset may be split.
- The clustering algorithm is applied separately to the training and testing sets to verify if similar clusters emerge.
Here are advanced steps in Clustering.

How to Learn These By Using LearnAIWithME GPT
Let’s learn these by using LearnAIWithMe GPT.
Here is the prompt you can use;
let's start learning clustering, give me the curriculum
Here is the output;

You can ask where to start, or if you can't understand some part of this article, continue asking and it will clarify everything!
Final Thoughts
Now, if you see the subtitle of this article,
Machine Learning Concepts, Clustering, Part: 1
You may have a question on your mind about it. If you haven’t read this article, you might not know about it; let me explain again. If you have any questions about this article, you can ask the LearnAIWithMe GPT.