Guide To AI Logo
Unit 14

Unsupervised Learning and Pattern Discovery

discovering meaningful structure, groups, and unusual observations in unlabeled data

Unsupervised Clustering: Discovering Groups Without Labels
Feature 1Feature 2Possible outlierPoints are grouped by similarity, not supplied labels.
Read diagram labels
  • Feature 1
  • Feature 2
  • Possible outlier
  • Points are grouped by similarity, not supplied labels.

Core Concepts Covered

  • Unlabeled data, similarity, distance, and exploratory pattern discovery
  • K-Means, hierarchical clustering, DBSCAN, and soft cluster membership
  • Cluster evaluation, visualization, stability, and domain interpretation
Local Setup Recommendation

To execute and experiment with the code cells below on your local machine, ensure you have set up your isolated virtual environments and scientific libraries by following the detailed protocols in Unit 03: Environment Setup or run them in Google Colab.

1. Learning from Unlabeled Data

In supervised learning, each training example has a target such as a house price or a spam label. Unsupervised learning instead starts with feature vectors x1,x2,...,xnx_1, x_2, ..., x_n and no target column. Its purpose is exploratory: reveal groups, compact representations, dense regions, or unusual observations that may be useful to people or later models.

A discovered pattern is not automatically a real-world category. The result depends on how examples are represented, which features are included, and how distance or similarity is measured. For example, customer groups based on annual spending may change dramatically if age and income are measured on much larger numeric scales and are not standardized.

Common goals include clustering similar observations, reducing dimensions for visualization, estimating latent distributions, and identifying possible outliers. Unit 8 introduced the mathematics of PCA; here, PCA becomes one practical tool for inspecting an unlabeled dataset before or alongside clustering.

2. K-Means: Finding Compact Clusters

K-Means divides observations into a chosen number of clusters KK. Each cluster is represented by a centroid μk\mu_k. The algorithm repeatedly assigns every point to its nearest centroid, then replaces each centroid with the mean of its assigned points until the assignments no longer change substantially.

Its objective is to make points within each cluster close to their centroid by minimizing the within-cluster sum of squares, often called inertia: J=i=1nmink{1,...,K}xiμk2J = \sum_{i=1}^{n} \min_{k \in \{1, ..., K\}} \lVert x_i - \mu_k \rVert^2

Because K-Means uses distances, scale numeric features first when their units differ. It also requires a value of KK, is sensitive to initialization, and works best when groups are reasonably compact and similar in spread. Run multiple initializations, inspect the result, and use domain knowledge rather than treating a cluster ID as a ground-truth label.

To compare candidate values of KK, plot inertia against KK and look for an elbow where additional clusters bring diminishing improvement. A silhouette score can provide another view of separation, but neither method discovers a uniquely correct KK. Prefer a solution that is stable under small data changes and useful in the problem domain.

K-Means Alternates Assignment and Update

initializeassignupdate means
Read diagram labels
  • initialize
  • assign
  • update means
Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

# An unlabeled dataset with three compact groups
X, _ = make_blobs(
    n_samples=120,
    centers=[[-2, -2], [0, 2], [3, -1]],
    cluster_std=0.6,
    random_state=7,
)

# Scale features before using a distance-based algorithm
X_scaled = StandardScaler().fit_transform(X)

kmeans = KMeans(n_clusters=3, n_init=10, random_state=7)
cluster_labels = kmeans.fit_predict(X_scaled)

print("Clusters found:", len(np.unique(cluster_labels)))
print("Points per cluster:", np.bincount(cluster_labels))
print("Silhouette score:", round(silhouette_score(X_scaled, cluster_labels), 2))
Out [1]:
Clusters found: 3
Points per cluster: [40 40 40]
Silhouette score: 0.73
Worked Example 1

One K-Means Assignment and Update

Problem

Points are 1,2,8,101,2,8,10 with initial centroids μ1=2\mu_1=2 and μ2=8\mu_2=8. Perform one assignment and centroid update.

Step-by-step solution

1.Distances assign 1,21,2 to cluster 1 and 8,108,10 to cluster 2.

2.μ1new=(1+2)/2=1.5\mu_1^{new}=(1+2)/2=1.5 and μ2new=(8+10)/2=9\mu_2^{new}=(8+10)/2=9.

Final answer and interpretation

The new inertia is (11.5)2+(21.5)2+(89)2+(109)2=2.5(1-1.5)^2+(2-1.5)^2+(8-9)^2+(10-9)^2=2.5.

Each assignment and mean-update step cannot increase the K-Means objective, though the final solution may be only locally optimal.

3. Other Ways to Discover Groups

Hierarchical clustering builds nested groups. Agglomerative methods begin with each point separate and merge groups. Single linkage uses the nearest pair and can recover long shapes but may chain through noise; complete linkage uses the farthest pair and favors compact groups; average linkage compromises between them; Ward linkage merges groups that cause the smallest rise in within-cluster variance. A dendrogram records merge distance, and a horizontal cut chooses a clustering.

DBSCAN uses a radius ε\varepsilon (eps) and neighbor threshold min_samples. A core point has enough points in its neighborhood, a border point is reachable from a core but lacks enough neighbors itself, and a noise point is not density-reachable. It can recover irregular shapes and needs no preset KK.

Scale features before interpreting ε\varepsilon. DBSCAN struggles when clusters have sharply different densities: one radius can fragment a sparse cluster or merge dense nearby clusters. HDBSCAN varies the density scale and can be more robust, but it still requires domain validation.

Hierarchical, Density-Based, and Probabilistic Views

dendrogram linkageDBSCAN density + noiseGMM soft overlap
Read diagram labels
  • dendrogram linkage
  • DBSCAN density + noise
  • GMM soft overlap
Worked Example 1

Reading a Dendrogram

Problem

Suppose merge heights are: AA with BB at 11, CC with DD at 22, and the two groups together at 77. What clusters result from a cut at height 44?

Step-by-step solution

1.Merges below the cut are retained: AA joins BB, and CC joins DD.

2.The height-7 merge lies above the cut and is not retained.

Final answer and interpretation

The result is two clusters, {A,B}\{A,B\} and {C,D}\{C,D\}.

Worked Example 2

Classify DBSCAN Points

Problem

With min_samples = 3 including the point itself, point pp has three points in its ε\varepsilon-neighborhood; qq has two but lies near pp; rr is near no core. Classify them.

Step-by-step solution

1.pp is a core point because its neighborhood count reaches 3.

2.qq is a border point because it is reachable from a core but is not itself core.

Final answer and interpretation

rr is noise under these settings.

4. Gaussian Mixture Models: Probabilistic Clustering

A Gaussian Mixture Model (GMM) assumes the data was generated by a weighted combination of KK Gaussian distributions. Each component has a mixing weight πk\pi_k, a mean vector μk\mu_k, and a covariance matrix Σk\Sigma_k. The model assigns a probability density to any observation xx: p(x)=k=1KπkN(xμk,Σk)p(x) = \sum_{k=1}^{K} \pi_k \mathcal{N}(x \mid \mu_k, \Sigma_k) The weights are non-negative and sum to one: πk0\pi_k \geq 0 and k=1Kπk=1\sum_{k=1}^{K} \pi_k = 1.

Unlike K-Means, which gives every point one hard cluster ID, a GMM calculates a responsibility for each component: the posterior probability that a component generated the point. For an observation near an overlap between two groups, the model might assign probabilities of 0.550.55 and 0.450.45 instead of pretending the boundary is certain. This also lets a GMM estimate density and identify points that are unlikely under every component.

The covariance setting determines the shapes that components can learn. full gives each component its own complete covariance matrix and can represent tilted ellipses. tied shares one full covariance matrix across components. diag allows different variance per feature but no feature correlation, while spherical uses one variance in every direction. More flexible covariance types need more data and can overfit, so start with the simplest option that matches the geometry of the problem.

GMMs are usually fit with Expectation-Maximization (EM). In the E-step, calculate responsibilities using the current parameters. In the M-step, update the weights, means, and covariances using those responsibilities as soft weights. Repeating these steps increases the data likelihood until the parameters stabilize. Unit 16 develops the full EM derivation and its latent-variable interpretation.

Jupyter Code Notebook Cell
Python 3 (ipykernel)
In [1]:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler

# Two overlapping groups make an uncertain boundary useful to inspect.
X, _ = make_blobs(
    n_samples=160,
    centers=[[-1.25, 0], [1.25, 0]],
    cluster_std=[1.1, 1.1],
    random_state=7,
)
X_scaled = StandardScaler().fit_transform(X)

gmm = GaussianMixture(
    n_components=2,
    covariance_type="full",
    n_init=10,
    random_state=7,
)
gmm.fit(X_scaled)

# Sort components by their first coordinate for readable, stable output.
component_order = np.argsort(gmm.means_[:, 0])
boundary_point = np.array([[0.0, 0.0]])
probabilities = gmm.predict_proba(boundary_point)[0][component_order]

kmeans = KMeans(n_clusters=2, n_init=10, random_state=7).fit(X_scaled)
hard_label = kmeans.predict(boundary_point)[0]

print("GMM means (sorted):")
print(np.round(gmm.means_[component_order], 2))
print("GMM membership probabilities for [0.0, 0.0]:", np.round(probabilities, 2))
print("K-Means hard label for [0.0, 0.0]:", hard_label)
Out [1]:
GMM means (sorted):
[[-0.85 -0.15]
 [ 0.69  0.12]]
GMM membership probabilities for [0.0, 0.0]: [0.29 0.71]
K-Means hard label for [0.0, 0.0]: 1
Worked Example 1

Responsibility and an EM Mean Update

Problem

For one point, two equally weighted components have likelihoods 0.120.12 and 0.040.04. Find its responsibilities. Then component 1 has responsibilities (0.75,0.25)(0.75,0.25) for observations (2,6)(2,6); update its mean.

Step-by-step solution

1.Unnormalized weights are 0.5(0.12)=0.060.5(0.12)=0.06 and 0.5(0.04)=0.020.5(0.04)=0.02.

2.Normalize: r1=0.06/0.08=0.75r_1=0.06/0.08=0.75 and r2=0.25r_2=0.25.

Final answer and interpretation

μ1new=[0.75(2)+0.25(6)]/(0.75+0.25)=3\mu_1^{new}=[0.75(2)+0.25(6)]/(0.75+0.25)=3.

The E-step computes soft assignments; the M-step recomputes parameters using them as fractional counts.

5. Evaluating and Interpreting Discovered Patterns

Without known labels, classification accuracy is unavailable. The silhouette score compares how close a point is to its own cluster with how close it is to the nearest other cluster. Scores near +1+1 suggest well-separated compact clusters, values near 00 suggest overlap, and negative values can indicate that points may be assigned to the wrong cluster.

Use internal scores as diagnostics, not as proof. Compare several reasonable hyperparameter choices, check whether clusters remain stable under small data changes, visualize the data when possible, and ask whether the groups make sense in the domain. A visually appealing cluster can still reflect a data-collection artifact or an irrelevant feature.

Pattern discovery can also surface rare cases. A point that DBSCAN marks as noise, or that lies far from every centroid, may be an error, a fraud case, a novel subgroup, or simply a valid but uncommon observation. Investigate it before deciding what it means.

Silhouette Compares Within-Cluster and Neighbor Distances

abs = (b − a) / max(a,b)
Read diagram labels
  • a
  • b
  • s = (b − a) / max(a,b)
Worked Example 1

A Point's Silhouette Value

Problem

A point's mean distance within its cluster is a=2a=2 and its mean distance to the closest neighboring cluster is b=5b=5. Find its silhouette value.

Step-by-step solution

1.Use s=(ba)/max(a,b)s=(b-a)/\max(a,b).

2.s=(52)/5=0.6s=(5-2)/5=0.6.

Final answer and interpretation

The positive value suggests the point is closer to its assigned cluster than to its nearest alternative.

Worked Example 2

Stability Check

Problem

Across five bootstrap samples, two customers are grouped together four times. Estimate their co-clustering stability.

Step-by-step solution

1.The empirical co-clustering frequency is 4/5=0.84/5=0.8.

Final answer and interpretation

This is evidence of a fairly stable relationship, not proof of a true category.

6. Other Possibilities for Unlabeled Data

Clustering is only one possibility. Anomaly discovery ranks unusual transactions or sensor readings; segmentation groups customers, images, or documents for inspection. Spectral clustering builds a similarity graph and can separate non-convex structures, but its affinity choice and computational cost matter.

PCA supplies a linear, variance-preserving projection whose derivation remains in Unit 8. t-SNE is valuable for local exploratory visualization but distorts global distances and should not be treated as a clustering algorithm. UMAP constructs a neighborhood graph and often preserves more global organization, though its embedding also changes with hyperparameters and random seeds. HDBSCAN can cluster variable-density structures in an embedding, but validate results in the original feature space.

Worked Example 1

Choose a Method, Then State the Risk

Problem

Choose a starting method for (a) two crescent-shaped groups with known clean scale, (b) a 500-feature table needing a compact linear representation, and (c) rare suspicious transactions.

Step-by-step solution

1.(a) Try spectral clustering or DBSCAN; K-Means' spherical geometry is a poor match.

2.(b) Start with PCA and measure explained variance; Unit 8 supplies the derivation.

Final answer and interpretation

(c) Use anomaly scoring and investigation, because rare does not automatically mean fraudulent.

Geometry, scale, and the downstream question should drive method choice.

Interactive Practice Quiz

Test your understanding with instant feedback

QUESTION 01

What distinguishes an unsupervised-learning dataset from a supervised-learning dataset?

QUESTION 02

What quantity does K-Means minimize when fitting its centroids?

QUESTION 03

Why is feature scaling usually important before applying K-Means to measurements with different units?

QUESTION 04

Which situation is a strong reason to try DBSCAN instead of K-Means?

QUESTION 05

Why can a Gaussian Mixture Model be more informative than K-Means for a point near the boundary between two overlapping groups?

QUESTION 06

After K-Means assigns every observation to its nearest centroid, what does its update step do?

QUESTION 07

What does a silhouette score close to +1+1 suggest?

QUESTION 08

In DBSCAN, which description identifies a border point?