Unsupervised Learning and Pattern Discovery
discovering meaningful structure, groups, and unusual observations in unlabeled data
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 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 . Each cluster is represented by a centroid . 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:
Because K-Means uses distances, scale numeric features first when their units differ. It also requires a value of , 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 , plot inertia against 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 . Prefer a solution that is stable under small data changes and useful in the problem domain.
K-Means Alternates Assignment and Update
Read diagram labels
- initialize
- assign
- update means
- →
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))Clusters found: 3
Points per cluster: [40 40 40]
Silhouette score: 0.73One K-Means Assignment and Update
Points are with initial centroids and . Perform one assignment and centroid update.
1.Distances assign to cluster 1 and to cluster 2.
2. and .
The new inertia is .
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 (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 .
Scale features before interpreting . 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
Read diagram labels
- dendrogram linkage
- DBSCAN density + noise
- GMM soft overlap
Reading a Dendrogram
Suppose merge heights are: with at , with at , and the two groups together at . What clusters result from a cut at height ?
1.Merges below the cut are retained: joins , and joins .
2.The height-7 merge lies above the cut and is not retained.
The result is two clusters, and .
Classify DBSCAN Points
With min_samples = 3 including the point itself, point has three points in its -neighborhood; has two but lies near ; is near no core. Classify them.
1. is a core point because its neighborhood count reaches 3.
2. is a border point because it is reachable from a core but is not itself core.
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 Gaussian distributions. Each component has a mixing weight , a mean vector , and a covariance matrix . The model assigns a probability density to any observation : The weights are non-negative and sum to one: and .
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 and 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.
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)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]: 1Responsibility and an EM Mean Update
For one point, two equally weighted components have likelihoods and . Find its responsibilities. Then component 1 has responsibilities for observations ; update its mean.
1.Unnormalized weights are and .
2.Normalize: and .
.
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 suggest well-separated compact clusters, values near 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
Read diagram labels
- a
- b
- s = (b − a) / max(a,b)
A Point's Silhouette Value
A point's mean distance within its cluster is and its mean distance to the closest neighboring cluster is . Find its silhouette value.
1.Use .
2..
The positive value suggests the point is closer to its assigned cluster than to its nearest alternative.
Stability Check
Across five bootstrap samples, two customers are grouped together four times. Estimate their co-clustering stability.
1.The empirical co-clustering frequency is .
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.
Choose a Method, Then State the Risk
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.
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.
(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
What distinguishes an unsupervised-learning dataset from a supervised-learning dataset?
What quantity does K-Means minimize when fitting its centroids?
Why is feature scaling usually important before applying K-Means to measurements with different units?
Which situation is a strong reason to try DBSCAN instead of K-Means?
Why can a Gaussian Mixture Model be more informative than K-Means for a point near the boundary between two overlapping groups?
After K-Means assigns every observation to its nearest centroid, what does its update step do?
What does a silhouette score close to suggest?
In DBSCAN, which description identifies a border point?
Further Readings
Explore these highly recommended external references to deepen your understanding
Scikit-Learn Clustering Guide
https://scikit-learn.org/stable/modules/clustering.html
Scikit-Learn Gaussian Mixture Models Guide
https://scikit-learn.org/stable/modules/mixture.html
DBSCAN: A Density-Based Algorithm for Discovering Clusters
https://cdn.aaai.org/KDD/1996/KDD96-037.pdf
UMAP: Uniform Manifold Approximation and Projection
https://arxiv.org/abs/1802.03426
