1. Home
  2. Explore
  3. Computer Science
  4. Unsupervised Machine Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Unsupervised Machine Learning

Unsupervised Machine Learning

Introduction to Unsupervised Learning

Unsupervised machine learning is one of the two main classes of statistical learning, the other being supervised learning. In supervised learning, a data matrix X (n×pn \times pn×p with nnn observations and ppp features) is used to predict or detect associations with a response y. In unsupervised learning, there is no response variable y — only the data matrix X is available, and the goal is to identify patterns, structure, or signal within that data.

Key characteristics:

  • No outcome or label to guide learning

  • Aim is to find groupings, low-dimensional representations, or associations among features

  • Often used in exploratory data analysis (EDA) alongside data wrangling and visualization

  • Can generate new hypotheses that are later validated in independent data or in a confirmatory analysis pipeline

Other categories exist: semi-supervised learning (some labels available) and reinforcement learning, but these are not covered in this lecture.

Why Use Unsupervised Learning?

Despite lacking a response variable, unsupervised methods are essential because they:

  • Reveal natural structure in data (e.g., clusters)

  • Reduce dimensionality to aid visualization

  • Correct for artifacts (e.g., batch effects)

  • Improve the performance of downstream supervised methods when used as a preprocessing step

It is critical to remember that any hypotheses generated from unsupervised learning must be validated on independent data or via a train/test approach. Without such validation, findings remain purely exploratory and may not be reproducible.


Clustering

Overview and Objectives

The goal of clustering is to partition objects into meaningful groups such that objects within the same cluster are more similar to each other than to objects in other clusters.

Clustering aims to group objects into meaningful clusters such that objects within each cluster are more similar to each other than objects in other clusters.

However, this definition is inherently vague. Different definitions of “meaningful” can produce different numbers of clusters. For example, a dataset might reasonably be seen as having two, four, or six clusters depending on the chosen granularity. Similarly, the choice of similarity measure affects the outcome: curves, manifolds, or Euclidean distances can all give different results.

What Can Be Clustered?

  • Observations (samples) — most common, e.g., identifying cancer subtypes from gene expression profiles

  • Features (variables) — e.g., grouping genes with similar functions to infer biological pathways

  • Both simultaneously — known as biclustering

This lecture focuses on clustering observations, but the same principles apply to the other two.

Hierarchical Clustering

Hierarchical clustering produces a sequence of nested clusters organized as a tree structure called a dendrogram.

Two approaches:

  • Bottom-up (agglomerative): start with each observation as its own cluster; iteratively merge the two most similar clusters until one cluster remains.

  • Top-down (divisive): start with one cluster containing all observations; recursively split until each observation is a separate cluster.

This lecture covers bottom-up methods.

Building a Dendrogram

A dendrogram requires two components:

  1. Distance or similarity between observations — e.g., Euclidean distance

  2. Linkage function — a measure of distance between sets of observations

In a dendrogram:

  • Each leaf corresponds to an observation

  • Branches fuse at heights that reflect dissimilarity

  • Earlier fusions (lower on the vertical axis) indicate greater similarity

  • The vertical axis encodes the distance at which clusters fuse; the horizontal axis has no meaning (adjacent leaves may be very dissimilar)

Cutting the dendrogram at different heights yields different numbers of clusters. The optimal cut is often chosen where there is a gap in fusion heights.

Linkage Functions

Three common linkage functions define the distance between two clusters AAA and BBB:

  • Single linkage: minimum distance between any point in AAA and any point in BBB
    d(A,B)=min⁡i∈A,j∈Bdijd(A,B) = \min_{i \in A, j \in B} d_{ij}d(A,B)=mini∈A,j∈B​dij​

  • Complete linkage: maximum distance between any point in AAA and any point in BBB
    d(A,B)=max⁡i∈A,j∈Bdijd(A,B) = \max_{i \in A, j \in B} d_{ij}d(A,B)=maxi∈A,j∈B​dij​

  • Average linkage: average distance between all pairs of points in AAA and BBB
    d(A,B)=1∣A∣∣B∣∑i∈A∑j∈Bdijd(A,B) = \frac{1}{|A||B|} \sum_{i \in A} \sum_{j \in B} d_{ij}d(A,B)=∣A∣∣B∣1​∑i∈A​∑j∈B​dij​

Choosing a Linkage Function

There is no universally best linkage function; the appropriate choice depends on unknown data characteristics.

  • Single linkage:

    • Good for clusters with irregular shapes (e.g., nested, non-spherical)

    • Sensitive to outliers and noise — can produce chaining behavior (clusters grow one observation at a time)

    • Often ineffective in high dimensions because noise causes chaining

  • Complete linkage and Average linkage:

    • More robust to outliers and noise

    • Work best when clusters are roughly spherical and of comparable size

    • May fail to identify irregularly shaped clusters (e.g., nested structures) or clusters of very different sizes

Examples:

  • With outliers between two clusters, single linkage may merge them into one cluster while complete/average linkage separate them.

  • With nested clusters, single linkage can separate them; complete/average linkage often cannot.

  • With clusters of very different sizes, complete linkage tends to split large clusters to equalize sizes; single/average linkage perform better.

Because in high-dimensional biomedical data the true cluster shapes are unknown, choosing a linkage function is challenging. Often multiple linkages are tried and validated downstream.

Advantages and Disadvantages of Hierarchical Clustering

Pros

Cons

Produces a family of nested clusters (easy to interpret)

No formal optimization criterion

Computationally efficient

Final partition is chosen subjectively by the analyst

Works in high dimensions (with caveats)

Different linkage functions can yield different solutions

K-Means Clustering

K-means is a partition-based method: instead of a hierarchy, it aims to directly partition observations into a pre-specified number kkk of clusters.

Objective

K-means minimizes the within-cluster sum of squares (also called inertia):

min⁡∑j=1k∑i∈Cj∥xi−μj∥2\min \sum_{j=1}^{k} \sum_{i \in C_j} \| \mathbf{x}_i - \boldsymbol{\mu}_j \|^2min∑j=1k​∑i∈Cj​​∥xi​−μj​∥2

where CjC_jCj​ is the set of observations in cluster jjj, and μj\boldsymbol{\mu}_jμj​ is the centroid (mean) of cluster jjj.

Algorithm

The exact minimization is computationally intractable (NP-hard), but a simple iterative algorithm finds a good local optimum:

  1. Randomly assign each observation to one of kkk clusters.

  2. Repeat until cluster assignments stop changing:

    • Compute cluster centroids (mean of all observations in each cluster).

    • Reassign each observation to the cluster whose centroid is closest (typically using Euclidean distance).

The algorithm converges quickly (often within a few iterations) and is computationally efficient even for large datasets.

Properties and Behavior

  • No hierarchy — if kkk changes, cluster memberships can change completely.

  • K-means works best with compact, spherical clusters of comparable size; its behavior resembles that of complete linkage.

  • It can produce empty clusters (especially with outliers); a remedy is to remove empty clusters and rerun the algorithm.

  • Examples:

    • K-means separates well-separated spherical clusters effectively.

    • It struggles with nested clusters or elongated shapes, where single linkage may succeed.

    • In the presence of overlapping clusters, k-means can still separate them, whereas single linkage may artificially chain them.

Choosing the Number of Clusters

Selecting kkk (or where to cut a dendrogram) is a difficult problem without a response variable.

  • Hierarchical clustering: inspect the dendrogram for gaps in fusion heights; cut where there is a noticeable jump.

  • K-means: compute the within-cluster sum of squares for different kkk values and look for an elbow — the point where the objective flattens out.

However, these guidelines are informal. The best practice is to treat clustering as part of a larger data analysis pipeline:

Use a validation set or cross-validation approach with a downstream supervised learning task. Vary the number of clusters and evaluate performance on held‑out data (e.g., prediction accuracy). The number of clusters that optimizes the downstream task is the most appropriate for the problem.

Challenges and Caveats in Clustering

  • No one-size-fits-all: there is no universally correct definition of a cluster.

  • In high-dimensional biomedical data, clusters may have arbitrary shapes and sizes unknown to the analyst.

  • Evaluating cluster quality is hard without external validation; internal measures (e.g., silhouette score) are not definitive.

  • Preprocessing matters: centering and scaling variables can completely change clustering results.

  • All clustering results should be validated on independent data or through a train/test pipeline to avoid overinterpretation.


Dimension Reduction

Motivation

High-dimensional data (ppp large) creates challenges:

  • Visualization becomes impossible with standard scatter plots

  • Redundancy (correlation among features) means not all features are necessary

  • Some features may be noisy and uninformative

Dimension reduction methods find a low-dimensional representation of the data that retains the most important information. This aids visualization, reduces noise, and can improve the performance of supervised methods.

Principal Component Analysis (PCA)

PCA is the most widely used dimension reduction technique. It finds a set of new variables (principal components) that are linear combinations of the original features, ordered by the amount of variance they capture.

Key Idea

Given a data matrix X\mathbf{X}X (n×pn \times pn×p), PCA seeks the direction of maximum variance:

w1=arg⁡max⁡∥w∥=1Var(Xw)\mathbf{w}_1 = \arg \max_{\| \mathbf{w} \| = 1} \text{Var}(\mathbf{X} \mathbf{w})w1​=argmax∥w∥=1​Var(Xw)

The first principal component (PC1) is the linear combination z1=Xw1\mathbf{z}_1 = \mathbf{X} \mathbf{w}_1z1​=Xw1​ with the largest sample variance.

Subsequent principal components are orthogonal (perpendicular) to all previous ones and maximize variance subject to that constraint. In practice, PCA performs an eigenvalue decomposition of the covariance matrix (or singular value decomposition of the data matrix).

Interpretation and Examples

  • In a two‑feature example, PC1 is the direction of greatest elongation of the data; PC2 is the direction orthogonal to PC1, capturing the remaining variance.

  • PCA defines a new coordinate system that is a rotation (and possibly a projection) of the original axes. Observations can be plotted along the first few PCs for visualization.

  • Biplots overlay both observations and variable loadings (arrows) in the PC space, revealing which features drive the components.

Example: USArrests data (1973) — four crime statistics per state. The first two PCs capture most of the variation:

  • PC1 represents an overall measure of crime/urbanization.

  • PC2 contrasts assault/murder (negative loadings) with rape/urban population (positive loadings). States with high assault/murder rates appear at the bottom of the PC2 axis.

Applications in Biomedical Big Data

  • Population genetics: PCA corrects for population stratification in genome-wide association studies (GWAS).

  • Studying human migration patterns.

  • Identifying and correcting batch effects — artificial non‑biological variation introduced during data collection — often visible as clusters in PC plots.

How Many Principal Components?

Choosing the number of PCs (mmm) involves a trade‑off:

  • More PCs explain more variance but reduce the benefits of dimension reduction.

  • Scree plots (variance explained vs. PC number) may show an elbow.

  • Better practice: Use PCA within a pipeline (e.g., principal component regression — PCR). In PCR, PCs are used as predictors in a regression or classification model. The optimal mmm is chosen via cross‑validation to maximize prediction accuracy on test data.

Advantages and Limitations of PCA

Pros

Cons

Simple, well‑understood

Components are linear combinations — hard to interpret biologically

Computationally efficient

Assumes linear relationships

Provides best low‑rank approximation of the data

Sensitive to scaling; features should be standardized

Useful for visualization and noise reduction

Not ideal for identifying individual feature associations

Other Dimension Reduction Methods (Mentioned)

PCA is just one approach. Others include multidimensional scaling (MDS), independent component analysis (ICA), self‑organizing maps (SOM), and non‑negative matrix factorization (NMF). Each has its own strengths and is suitable for different data types.


Unsupervised Learning in the Data Analysis Pipeline

Unsupervised learning is rarely used in isolation. It is most powerful when integrated into a broader analysis workflow:

  • Exploratory Data Analysis: Preprocessing, visualization, batch effect correction, generating hypotheses.

  • Feature Extraction: Reducing dimensionality before applying supervised methods (e.g., PCA followed by regression).

  • Confirmatory Analysis: When combined with a response variable, unsupervised results can be validated via cross‑validation or held‑out data.

Key Takeaways

  1. Unsupervised learning discovers patterns without a response variable, but results require external validation.

  2. Clustering groups similar observations; hierarchical and k‑means are two major approaches, each with strengths and weaknesses.

  3. Dimension reduction (especially PCA) creates a compact representation of the data for visualization and downstream analysis.

  4. The choice of parameters (number of clusters/PCs) is best guided by performance on a validation task rather than by heuristics alone.

  5. All findings from unsupervised learning should be interpreted cautiously; without validation they may be spurious or non‑reproducible.

  6. Preprocessing (centering, scaling) significantly influences results and must be handled thoughtfully.

Practical Guidelines for Practitioners

  • Try multiple distance metrics and linkage functions for clustering; validate which yields the most generalizable results.

  • In PCA, the rotation is already optimal; the challenge is deciding which PCs to examine (e.g., PC1 vs. PC2, or PC1 vs. PC3).

  • Supervision in unsupervised learning is sometimes necessary — the data scientist must make informed choices. However, these choices should be guided by generalizability rather than over‑interpretation of the training data.

  • When combining supervised and unsupervised methods (e.g., PCA + regression), the goal matters:

    • Prediction → PCR works well.

    • Identifying associations with original features → PCR’s linear combinations are difficult to interpret; other methods (e.g., sparse PCA, Lasso) may be more suitable.

Ultimately, unsupervised learning is a tool for discovery — it reveals structure, generates hypotheses, and improves downstream analyses — but its results must be treated as tentative until confirmed by independent evidence.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent