Skip to main content

What is Clustering?

Clustering is an unsupervised machine learning technique used to group similar data points together.
  • Data points in the same cluster are similar.
  • Data points in different clusters are different.
  • It does not require labeled data.
Example: Suppose we have customers with their age and annual spending. We can group them into different customer segments.

1. K-Means Clustering

Definition

K-Means divides data into a fixed number (K) of clusters. It tries to keep data points within the same cluster as close to each other as possible.

Steps

  1. Choose the number of clusters K.
  2. Select K centroids.
  3. Assign each data point to the nearest centroid.
  4. Calculate new centroids.
  5. Repeat until the clusters become stable.

Simple Example

Suppose we have students based on study hours and exam marks: If K = 2:

Python Code

Output

Explanation

model.labels_ tells us which cluster each data point belongs to. model.cluster_centers_ gives the centroid of each cluster.

Important Points

  • K must be specified beforehand.
  • Uses centroids.
  • Works well when clusters are roughly spherical.
  • Sensitive to outliers.
  • Results can depend on initial centroids.

Applications

  • Customer segmentation
  • Market analysis
  • Image compression
  • Grouping similar products

2. Hierarchical Clustering

Definition

Hierarchical Clustering creates a tree-like structure of clusters called a dendrogram. The most common approach is Agglomerative Clustering.

Agglomerative Clustering

It follows a bottom-up approach. Initially:
Each point is its own cluster. Then similar points are merged:
Then:
Finally:
This process forms a dendrogram.

Simple Example

We can cut the dendrogram at a particular level to get the required number of clusters.

Python Code

Output

Explanation

The algorithm identifies two groups:
Unlike K-Means, it doesn’t use centroids. It merges the closest clusters step by step.

Important Points

  • Creates a dendrogram.
  • Uses a bottom-up merging process in Agglomerative Clustering.
  • Number of clusters can be selected by cutting the hierarchy.
  • Can be computationally expensive for large datasets.

Applications

  • Gene analysis
  • Document classification
  • Customer segmentation
  • Social network analysis

3. DBSCAN

Full Form

DBSCAN = Density-Based Spatial Clustering of Applications with Noise

Definition

DBSCAN groups data points based on density.
Unlike K-Means, DBSCAN does not require K beforehand.

Important Parameters

1. eps

Maximum distance used to find neighboring points.
means points within a distance of approximately 2 can be considered neighbors.

2. min_samples

Minimum number of nearby points required to form a dense region.

Types of Points

Core Point Has enough neighboring points. Border Point Not dense enough itself but is close to a core point. Noise Point Does not belong to any cluster.

Simple Example

The isolated × can be detected as noise.

Python Code

Output

Explanation

In DBSCAN:

Important Points

  • Does not require K.
  • Can find clusters with irregular shapes.
  • Can detect noise/outliers.
  • Based on density.
  • Can struggle when different clusters have very different densities.

Applications

  • Geographic/spatial data
  • Fraud detection
  • Anomaly detection
  • GPS/location analysis
  • Finding unusual data points

Quick Comparison

Easy way to remember

In one line:
K-Means = group around centers, Hierarchical = build a cluster tree, DBSCAN = find dense groups and detect noise.

Dimensionality Reduction

What is Dimensionality Reduction?

Dimensionality Reduction is the process of reducing the number of features (dimensions) in a dataset while keeping as much useful information as possible. Example: Suppose a dataset has:
If there are 10 features, dimensionality reduction can reduce them to:
This is useful for:
  • Visualizing high-dimensional data
  • Reducing computation
  • Removing redundant information
  • Improving model performance in some cases
  • Making datasets easier to analyze
Two common techniques:
  1. PCA
  2. t-SNE

1. Principal Component Analysis (PCA)

Definition

PCA (Principal Component Analysis) transforms many features into a smaller number of new features called Principal Components. The new components try to preserve the maximum variance (information) from the original data.

Simple Example

Suppose we have:
Instead of using 4 features, we can use only 2 principal components.

Important Terms

Principal Component 1 (PC1) Captures the maximum possible variance. Principal Component 2 (PC2) Captures the next highest variance and is perpendicular to PC1.

Python Example

Output

The exact component values can vary slightly depending on numerical precision, but the output will look like:

Explanation

Original dataset:
n_components=2 means we want 2 principal components. explained_variance_ratio_ tells us how much information/variance each component captures. For example:
means the two components preserve about 95% of the variance.

Important Points

  • PCA is a linear dimensionality reduction technique.
  • It creates new features called principal components.
  • Components are combinations of the original features.
  • Usually, data should be standardized before PCA.
  • PCA is useful for visualization and reducing features.
  • PCA does not use target labels.

Applications

  • Data visualization
  • Image compression
  • Feature reduction
  • Noise reduction
  • Preprocessing for machine learning

2. t-SNE

Full Form

t-SNE = t-Distributed Stochastic Neighbor Embedding

Definition

t-SNE is a dimensionality reduction technique mainly used to visualize high-dimensional data in 2D or 3D. Its main goal is to keep similar data points close together in the reduced space.

Simple Idea

Suppose we have 50-dimensional data:
Now we can plot the data:
Points that are similar tend to appear close together.

Python Example

Output

The exact values can differ depending on the version and parameters.

Explanation

The Iris dataset originally contains:
After t-SNE:
So:
These 2 dimensions can then be plotted to visually inspect groups.

Important Points

  • Mainly used for visualization.
  • Excellent at showing local relationships.
  • Can reduce data to 2D or 3D.
  • Results can change depending on parameters and random initialization.
  • Computationally expensive for large datasets.
  • Unlike PCA, t-SNE is non-linear.

Applications

  • Visualizing image datasets
  • Visualizing word embeddings
  • Exploring clusters
  • Analyzing high-dimensional datasets

PCA vs t-SNE

Easy way to remember

One-line summary

PCA = reduce dimensions by preserving variance. t-SNE = reduce dimensions mainly to visualize similar data points.

Cluster Evaluation

What is Cluster Evaluation?

Cluster Evaluation is used to check how good the clusters are after applying a clustering algorithm. For example, after K-Means creates 3 clusters, we need to know:
  • Is K = 3 a good choice?
  • Are the clusters well separated?
  • Are points inside a cluster similar?
Two common methods are:
  1. Elbow Method
  2. Silhouette Score

1. Elbow Method

Definition

The Elbow Method is used to find a suitable value of K in K-Means clustering. It uses WCSS (Within-Cluster Sum of Squares), also called inertia.

Idea

Run K-Means with different values of K:
Calculate the WCSS for each K and plot it.
The point where the decrease starts becoming slower is called the Elbow. That K is usually selected as a good number of clusters.

Why does WCSS decrease?

When we increase K, clusters become smaller, so points become closer to their cluster centroids. Therefore:
But using too many clusters is not useful. We look for the point where the improvement becomes relatively small.

Python Example

Output

Here, the large improvement happens until approximately:
So we would consider 3 clusters a good choice.

Important Point

Elbow Method → Find the suitable K for K-Means.

2. Silhouette Score

Definition

The Silhouette Score measures how well each data point fits within its cluster. It considers two things:
  • How close a point is to points in its own cluster
  • How far it is from points in other clusters

Score Range

Interpretation

Therefore:
Higher Silhouette Score = Better clustering

Formula

For a data point:
Where:
  • a = average distance from the point to its own cluster
  • b = average distance from the point to the nearest other cluster

Python Example

Output

The highest score is:
Therefore, K = 3 is a good choice for this dataset.

Elbow Method vs Silhouette Score

Easy way to remember

One-line summary

Elbow Method finds a suitable number of clusters, while Silhouette Score measures how well-separated and cohesive those clusters are.