Sub topic 1
What clustering does and what counts as a cluster
Clustering groups data points so that points in the same group are more alike than points in different groups. No one tells the algorithm what the groups are. This chapter sets up the vocabulary and the ideas that the rest of the tutorial relies on. It covers what a clustering is, why "cluster" has no single definition, and why that matters before you choose between hierarchical clustering and DBSCAN.
Prerequisites
This chapter assumes you already have:
- Basic Python and NumPy, including array shapes such as
(n_samples, n_features). - The idea of unsupervised learning, meaning data without target labels.
- Euclidean distance between points.
- Familiarity with scikit-learn's
fitandfit_predictstyle API.
Later chapters build on the terms introduced here.
What a clustering is
A clustering takes a dataset X with n samples and assigns each sample to a group. In scikit-learn the result is an array labels of length n, where labels[i] is the group of sample i. Formally there are two common output types:
- A flat clustering (also called a partition) gives each point exactly one label. K-means and DBSCAN return flat clusterings.
- A hierarchical clustering returns a tree of nested groups. You get a flat clustering from it by cutting the tree at some level. Later chapters cover this.
Some methods also allow a point to belong to no cluster. DBSCAN uses the label -1 for such points and calls them noise. Keep this in mind, because it changes how you count clusters and how you evaluate results.
Clustering is used for several different jobs:
- Exploration: finding structure in data you do not yet understand, such as groups of customers or types of sensor readings.
- Compression and summarization: replacing many points with a few representatives.
- Preprocessing: creating a cluster label that becomes a feature for another model.
- Anomaly detection: treating points that fit no cluster as suspicious.
The job matters because it decides what a "good" result looks like. A clustering that is useful for summarization may be useless for anomaly detection.
Why there is no single definition of a cluster
There is no ground truth to compare against, so the algorithm's own definition of "cluster" becomes the definition you get. Three definitions matter for this tutorial.
| Notion | A cluster is... | Typical shape it finds | Example method |
|---|---|---|---|
| Compact group | A set of points close to a common center | Roughly round blobs | K-means, Ward linkage |
| Connected group | A set of points linked by chains of near neighbors | Elongated or curved shapes | Single linkage |
| Dense region | A region with many points per unit of space, separated from other dense regions by sparse space | Arbitrary shapes of similar density | DBSCAN |
The same data can be clustered correctly under one notion and incorrectly under another. Two interleaved half-moons are two clusters under the connected and density notions. Under the compact-group notion they are not, because the points of one moon are far from its own center.
The practical rule is to choose the method whose definition of a cluster matches what you mean by one in your problem.
What makes a clustering good
Most informal quality ideas reduce to two properties:
- Cohesion: points in the same cluster are close to each other.
- Separation: points in different clusters are far from each other.
Many evaluation scores, such as the silhouette score, combine these two. Both properties depend on a distance measure, so the quality of a clustering is tied to how you measure distance and whether your features are on comparable scales. The next two chapters cover those topics.
Cohesion and separation are not enough on their own, and these gaps cause common errors:
- Cohesion alone rewards splitting. If every point is its own cluster, cohesion is perfect and the result is useless.
- Separation alone rewards merging. If you put all points in one cluster, nothing is wrongly separated.
- Domain usefulness is a separate test. A clustering of customers can score well and still produce groups that no one can act on.
Clustering always returns an answer
The most important edge case is that most algorithms return clusters even when the data has none. Agglomerative clustering with n_clusters=3 produces three groups from uniform random noise, because you asked for three. The example below shows this and then contrasts it with data that has real structure.
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
rng = np.random.default_rng(0)
# Uniform noise: no real groups.
X_noise = rng.uniform(size=(200, 2))
# Three well-separated blobs.
X_blobs, _ = make_blobs(n_samples=200, centers=3, cluster_std=0.5, random_state=0)
for name, X in [("uniform noise", X_noise), ("blobs", X_blobs)]:
labels = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X)
sizes = np.bincount(labels)
score = silhouette_score(X, labels)
print(f"{name}: sizes={sizes.tolist()}, silhouette={score:.2f}")Both runs print three cluster sizes. The silhouette score is what separates them. It is much higher for the blobs than for the noise. A silhouette near 0 means points sit between clusters, so the labels carry little information. Always ask whether the data supports clusters before you interpret the ones you got.
The same data under different definitions
This example runs a compact-group method and a density method on the half-moon data. The true moon membership is used only to score the result afterward, which you can do on toy data but not on real unlabeled data. The adjusted Rand index (ARI) is 1.0 for a perfect match with the true grouping and near 0 for a random one.
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler
X, y_true = make_moons(n_samples=300, noise=0.05, random_state=0)
X = StandardScaler().fit_transform(X)
km_labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
db_labels = DBSCAN(eps=0.3, min_samples=5).fit_predict(X)
print("k-means ARI:", round(adjusted_rand_score(y_true, km_labels), 2))
print("DBSCAN ARI: ", round(adjusted_rand_score(y_true, db_labels), 2))K-means cuts the plane with a straight boundary between two centers, so it slices across both moons and scores well below 1. DBSCAN follows the dense curved bands and recovers the moons. Neither method is wrong in general. Each answers a different question about what a cluster is.
Choices that exist before you run any algorithm
Several decisions shape every result in this tutorial, and each is covered in later chapters:
- The distance measure. It defines "close". Euclidean distance is the default, but others suit other data.
- The feature scaling. A feature with a large numeric range dominates distance unless you rescale it.
- The number of clusters, or the parameters that control it indirectly. Hierarchical clustering lets you pick the count after seeing the tree. DBSCAN has no cluster-count parameter, but
epsandmin_samplesdetermine how many clusters appear. - The treatment of outliers. You can force every point into a cluster, or allow some points to stay unassigned.
Key points
- A clustering assigns each point to a group, or in DBSCAN's case possibly to no group, without any labels to guide it.
- "Cluster" has several working definitions: compact group, connected group, and dense region. Each method commits to one.
- Cohesion and separation are the basis of most quality measures, and neither works alone.
- Clustering algorithms return groups even for structureless data, so check that the groups are meaningful.
Exercise
You run Ward-linkage agglomerative clustering with n_clusters=4 on a dataset and get four clusters of similar size. A colleague says this proves the data has four natural groups. What is wrong with that claim, and what two checks would you run?
Show answer
The algorithm was told to produce four clusters, and it returns four even for data with no structure, so the count says nothing about the data. First, compute a quality score such as the silhouette score and compare it with the score on structureless data of the same shape (for example uniform random data), or across several values of n_clusters. Second, inspect the data visually, for instance with a two-dimensional plot, and check whether the groups make sense in the domain.
Exercise
Why does k-means fail to recover two interleaved half-moons while DBSCAN succeeds, in terms of how each defines a cluster?
Show answer
K-means defines a cluster as a compact group of points around a center, so it separates the data with a straight boundary between two centers and cuts across both moons. DBSCAN defines a cluster as a dense region connected through nearby points, so it follows each curved band and keeps each moon together.