Skip to content

Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 39 of 62 · 30 min

Other clustering methods and dimensionality reduction

Explanation

Hierarchical clustering builds a tree of groups you can cut at any level. DBSCAN finds dense regions of any shape and marks lonely points as noise. PCA reduces many columns to a few new ones that keep most of the variation, which helps visualisation and speed. t-SNE and UMAP make pictures of high-dimensional data, but only for looking.

Beyond k-means

k-means is fast and simple, but it needs k in advance and expects round clusters. Real data may have groups of odd shapes, outliers that belong to no group, or a natural hierarchy (city → area → street). Different methods suit these cases.

Hierarchical (agglomerative) clustering

Start with every point as its own cluster. Repeatedly merge the two closest clusters until only one remains. The record of merges is a tree called a dendrogram. Cutting it at a chosen height gives any number of clusters. It is useful when you want to see structure at several levels, but it is slow on very large datasets.

DBSCAN: density-based clustering

DBSCAN groups points that have many neighbours within a radius (eps). A core point has at least min_samples neighbours. Clusters grow from core points, and points that are not near any dense region are labelled noise (−1). It finds clusters of any shape, does not need k, and naturally flags outliers, which makes it handy for things like grouping GPS pings into delivery hotspots. It struggles when clusters have very different densities.

python
from sklearn.cluster import DBSCAN, AgglomerativeClustering

db = DBSCAN(eps=0.5, min_samples=5).fit(X_scaled)
print(set(db.labels_))          # e.g. {0, 1, 2, -1}; -1 means noise

agg = AgglomerativeClustering(n_clusters=4, linkage="ward").fit(X_scaled)
Shown only. eps is measured in the units of the (scaled) features.

Dimensionality reduction

Datasets can have hundreds of columns. Many are related: height in cm and height in inches carry the same information. Dimensionality reduction creates a smaller set of new columns that keep most of the useful information. Benefits: faster models, less overfitting, and the ability to draw the data in 2-D.

PCA in plain words

Principal component analysis (PCA) finds the direction in which the data varies most; that is the first principal component. The second component is the direction of most remaining variation, at right angles to the first, and so on. Projecting the data onto the first few components gives new features. The explained variance ratio says what share of the total variation each component keeps, such as "the first 3 components keep 85%". PCA needs scaled features, and its components are mixtures of the original columns, so they are harder to explain.

python
from sklearn.decomposition import PCA

pca = PCA(n_components=0.90)       # keep enough components for 90% of the variance
X_small = pca.fit_transform(X_scaled)
print(X_small.shape, pca.explained_variance_ratio_.round(2))
Passing a fraction asks PCA to choose the number of components. Shown only.

t-SNE and UMAP

t-SNE and UMAP squeeze high-dimensional data into 2-D pictures that keep nearby points nearby. They make beautiful plots for exploring, for example of embeddings of support tickets. But distances and cluster sizes in the picture can be misleading, and the result changes with settings. Use them to look, not as features for models or as proof of groups.

Common mistakes

  • Running PCA without scaling, so the column with the largest units dominates the first component.
  • Fitting PCA on all data before the train/test split (leakage). Fit on training data only.
  • Reading clusters in a t-SNE plot as real, measured groups.
  • Using DBSCAN with a default eps on unscaled data and getting everything as noise.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Other clustering methods and dimensionality reduction · 1/6

Beyond k-means

k-means is not the only way to cluster. Let us meet two others, and PCA.

Prefer a video by a teacher? Find free videos on “PCA explained simply DBSCAN hierarchical clustering” on YouTube ↗

In real life: Finding delivery hotspots

A quick-commerce company runs DBSCAN on the GPS locations of last month's orders in a city. Dense clusters show where to open new dark stores, and points marked as noise (scattered single orders) are left out. Because DBSCAN finds clusters of any shape, it follows neighbourhoods along roads and rivers better than round k-means clusters would.

Practice (0/2 done)

Task 1 · Code · Python

Write top_variance_features(columns, k) where columns is a dict mapping a feature name to its list of values. Return the names of the k features with the highest POPULATION variance (statistics.pvariance), largest first; ties by name A→Z. (Low-variance features carry little information.)

Task 2 · Code · Python

PCA projects points onto a direction. Write project(points, direction) that first turns direction into a unit vector (divide by its length), then returns the dot product of each point with it, rounded to 4 decimal places.

Quick quiz

Question 1

1.Which method labels outliers as noise and finds clusters of any shape?

Question 2

2.What does a dendrogram show?

Question 3

3.What is the first principal component?

Question 4

4.Why scale features before PCA?

Question 5

5.What is the right use of a t-SNE plot?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which method labels outliers as noise and finds clusters of any shape?

Answer: DBSCAN

DBSCAN is density-based and marks sparse points as −1.

What does a dendrogram show?

Answer: The order in which hierarchical clustering merged groups

Cut it at a height to get a number of clusters.

What is the first principal component?

Answer: The direction of greatest variation in the data

PCA orders directions by how much variance they capture.

Why scale features before PCA?

Answer: Otherwise the column with the largest units dominates the components

Variance depends on units.

What is the right use of a t-SNE plot?

Answer: To explore and visualise high-dimensional data

t-SNE distorts distances; it is for looking.

Which shape of clusters is hardest for k-means?Related

Answer: Long, curved or very unequal clusters

k-means assumes roughly spherical, similar-sized clusters.

From Clustering with k-means

Which component decides which node a new pod should run on?Related

Answer: kube-scheduler

The scheduler watches for pods with no node assigned and picks a node based on resources and rules.

From Why Kubernetes, and how a cluster works

Which isolation level prevents dirty reads but still allows non-repeatable reads?Related

Answer: Read Committed

Read Committed only shows committed data, but a row can change between two reads.

From Theory questions you will be asked

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Clustering, dimensionality reduction and feature engineering” before its exam: Encoding categories and dates, Scaling and transforming numbers, Feature selection, leakage and pipelines.
  2. Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.

← Previous: Clustering with k-means