1. Clustering: Basic concepts of clustering
The goal of clustering is to:
- The similarity within the cluster (Intra-cluster Similarity) is as high as possible.
- The similarity between clusters (Inter-cluster Similarity) is as low as possible.
Different from classification:
| Contrast | Classification | Clustering |
|---|---|---|
| learning type | supervised learning | unsupervised learning |
| Do you need real labels? | usually required | No need |
| target | Forecast predefined categories | Discover the data grouping structure |
| output | Prediction category | cluster label |
| Typical algorithm | SVM、Logistic Regression | K-Means、DBSCAN |
It should be noted that the labels obtained by clustering are usually just cluster identifiers, such as 0, 1, and 2, and have no natural size relationship or business meaning.
Common clustering methods
| method | core idea | representative algorithm |
|---|---|---|
| Centroid-based | Divide samples according to cluster centers | K-Means |
| Density-based | Discover clusters based on local sample density | DBSCAN、HDBSCAN |
| Hierarchical | Merge or divide clusters based on hierarchical relationships between samples | Agglomerative Clustering |
Different methods make different assumptions about cluster shape, density, and number, so there is no optimal clustering algorithm that works for all data.
2. Distance Metrics: distance and similarity
Most clustering algorithms rely on some distance or similarity measure of sample relationships.
Euclidean Distance: Euclidean distance
This is the most common distance measure.
Suitable for continuous features with real numerical meaning.
Manhattan Distance: Manhattan distance
Calculate the sum of absolute differences in each dimension.
Cosine Distance: cosine distance
Measure the difference based on vector direction:
Suitable for certain high-dimensional features, such as text vectors.
scikit-learn implementation
from sklearn.metrics import pairwise_distances
distances = pairwise_distances(
X,
metric="euclidean",
)
It should be noted that the complete pairwise distance matrix has a space overhead of , and large-scale data should not be calculated at will.
Feature Scaling
If Euclidean distance is used, the numerical scale of the features will directly affect the clustering results.
For example:
Age: 20~60
Salary: 3000~30000
Without normalization, Salary may dominate distance calculations.
Therefore it is often used:
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
But standardization is not an absolute requirement. If the units and weights of different features themselves make business sense, decisions on how to scale should be based on the analysis goals.
3. K-Means: K mean clustering
K-Means is one of the most common clustering algorithms.
It divides the data into pre-specified K clusters, each cluster represented by a center point (Centroid).
Basic process
- Initialize K cluster centers.
- Assign each sample to the nearest center.
- The mean of each cluster is recalculated based on the distribution results.
- Allocation and updating are repeated until convergence conditions are met.
Optimization target: Inertia
K-Means minimizes the within-cluster sum of squares:
Among them:
- : The Kth cluster.
- : The center of the corresponding cluster.
- : In-cluster samples.
This target is also called Within-Cluster Sum of Squares (WCSS).
scikit-learn implementation
from sklearn.cluster import KMeans
model = KMeans(
n_clusters=3,
init="k-means++",
n_init=10,
random_state=42,
)
labels = model.fit_predict(X_scaled)
Main attributes:
model.labels_ # Cluster labels for each sample
model.cluster_centers_ # cluster center
model.inertia_ # sum of squares within cluster
model.n_iter_ # Number of iterations
Key hyperparameters
| parameters | function |
|---|---|
n_clusters | Specify the number of clusters K |
init | Cluster center initialization method |
n_init | Number of repeated runs with different initializations |
max_iter | Maximum number of iterations in a single run |
random_state | Controlling randomness |
k-means++ can improve the selection of initial centers and reduce the impact of some bad initializations.
How to choose K?
Elbow Method (elbow rule)
Try different K and see how Inertia changes.
import matplotlib.pyplot as plt
ks = range(2, 11)
inertias = []
for k in ks:
model = KMeans(
n_clusters=k,
n_init=10,
random_state=42,
)
model.fit(X_scaled)
inertias.append(model.inertia_)
plt.plot(ks, inertias, marker="o")
plt.xlabel("Number of Clusters")
plt.ylabel("Inertia")
plt.show()
As K increases, Inertia generally decreases, but the number of clusters also increases.
If the curve has an obvious inflection point, it can be used as a candidate K.
Another method is to compare Silhouette Score with different K, which will be introduced later.
Features of K-Means
Advantages:
- Simple and computationally efficient.
- The results are easy to understand.
- New samples can be assigned the nearest cluster center using
predict(). - Suitable for more compact, approximately spherical clusters.
Limitations:
- K needs to be specified in advance.
- Sensitive to initialization and outliers.
- Sensitive to feature scale.
- Not suitable for some complex cluster shapes such as curves and rings.
MiniBatchKMeans
For larger data sets, you can use MiniBatch K-Means:
from sklearn.cluster import MiniBatchKMeans
model = MiniBatchKMeans(
n_clusters=5,
batch_size=1024,
random_state=42,
)
It updates cluster centers using small batches of data, which generally reduces computational cost, but the results may differ from standard K-Means.
4. DBSCAN: Density-based clustering
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) finds clusters based on the local density of the sample.
Unlike K-Means, DBSCAN:
- There is no requirement to specify the number of clusters in advance.
- Non-spherical clusters can be identified.
- Points in low-density areas can be labeled as noise.
core concepts
DBSCAN mainly includes three concepts:
Core Point (core point)
Points with at least min_samples samples within radius eps, count inclusive of itself.
Border Point (boundary point)
It does not meet the core point conditions, but it is located in the neighborhood of a core point.
Noise Point (noise point)
A sample that is neither a core point nor can be classified into any core point neighborhood.
Clustering process
- Determine the neighborhood of each point based on
eps. - Determine which points are core points.
- Connect core points with reachable density into clusters.
- Assign adjacent boundary points to clusters.
- The remaining points are labeled as noise.
scikit-learn implementation
from sklearn.cluster import DBSCAN
model = DBSCAN(
eps=0.5,
min_samples=5,
metric="euclidean",
)
labels = model.fit_predict(X_scaled)
Common properties:
model.labels_
model.core_sample_indices_
model.components_
Among them, labels_ == -1 represents the noise point.
Key hyperparameters
| parameters | function |
|---|---|
eps | neighborhood radius |
min_samples | The minimum number of samples required for the core point neighborhood |
metric | distance measure |
algorithm | Neighbor search algorithm |
The impact of eps
epsis smaller: more points may be identified as noise and clusters may be fragmented.epsis larger: more points may be connected or even merged into a large cluster.
The impact of min_samples
- Smaller: Easier to form core points.
- Larger: requires higher local density.
Both parameters must be adjusted in conjunction with data scale and density distribution.
K-Distance Plot
You can observe the distance from each point to the K nearest neighbor and assist in selecting eps:
import numpy as np
from sklearn.neighbors import NearestNeighbors
neighbors = NearestNeighbors(n_neighbors=5)
neighbors.fit(X_scaled)
distances, _ = neighbors.kneighbors(X_scaled)
k_distances = np.sort(distances[:, -1])
plt.plot(k_distances)
plt.ylabel("5-NN Distance")
plt.show()
If the curve has obvious bends, the corresponding distance can be used as a candidate value for eps.
But not all data has a clear inflection point.
Advantages and Disadvantages of DBSCAN
Advantages:
- No need to specify the number of clusters.
- Able to recognize some irregular shapes.
- Noise points can be found.
Limitations:
- More sensitive to
eps. - If the densities of different clusters vary greatly, it may be difficult to identify them simultaneously with a unified
eps. - Distances may lose their discriminative power in high-dimensional data.
- Under certain parameters and data distributions, memory overhead may be higher.
5. HDBSCAN: Hierarchical density clustering
HDBSCAN (Hierarchical DBSCAN) can be understood as an extension of DBSCAN.
It does not rely on a single fixed eps to determine the final cluster, but builds a hierarchy through different density scales and selects the results based on the stability of the cluster.
Main differences from DBSCAN
| Contrast | DBSCAN | HDBSCAN |
|---|---|---|
| density threshold | Dependency fixed eps | Consider multiple density scales |
| Number of clusters | autodiscover | autodiscover |
| noise point | support | support |
| different density clusters | relatively difficult | usually more flexible |
| Main parameters | eps、min_samples | min_cluster_size、min_samples |
HDBSCAN is generally more adaptable to structures of different densities, but does not guarantee correct identification of clusters with arbitrary density differences.
scikit-learn implementation
HDBSCAN is available starting with scikit-learn 1.3.
from sklearn.cluster import HDBSCAN
model = HDBSCAN(
min_cluster_size=10,
min_samples=5,
)
labels = model.fit_predict(X_scaled)
Key hyperparameters
min_cluster_size
Specifies the minimum size of the cluster.
- Smaller: Allow smaller clusters.
- Larger: More likely to identify larger stable clusters.
min_samples
Affects the degree of conservatism in density estimation and noise identification.
- Smaller: usually allows more samples to enter the cluster.
- Larger: Typically requires higher density and may generate more noise.
cluster_selection_method
Common choices:
eom: Select based on cluster stability.leaf: Prefers selection of finer-grained clusters in the hierarchy.
Common results
model.labels_
model.probabilities_
probabilities_ represents the strength of membership of the sample to the assigned cluster, which should not be simply understood as the predicted probability of a class in supervised learning.
Features of HDBSCAN
Suitable for:
- The data may contain noise.
- The clusters are irregular in shape.
- Different clusters have different densities.
- The number of clusters cannot be reasonably specified in advance.
Need to pay attention to:
- Parameters can still significantly affect the results.
- The algorithm complexity is usually higher than K-Means.
- The implementation of scikit-learn differs from the third-party
hdbscanpackage in API and some parameter conventions.
6. Hierarchical Clustering: Hierarchical clustering
Hierarchical clustering builds a hierarchical structure based on the similarities between samples.
Mainly divided into:
- Agglomerative (agglomerative): Continuously merge clusters from bottom to top.
- Divisive (split): Split clusters continuously from top to bottom.
The more common one in actual development is Agglomerative Clustering.
Agglomerative Clustering
Basic process:
- Initially each sample is an independent cluster.
- Calculate the distance between clusters.
- Merge the two closest clusters.
- Repeat until the specified number of clusters or distance threshold is reached.
Linkage: distance between clusters
Different Linkage determines how to measure the distance between two clusters.
| Linkage | rules |
|---|---|
| Single | The distance between the closest samples in two clusters |
| Complete | The distance between the farthest samples in the two clusters |
| Average | The average distance between two clusters of samples |
| Ward | Choose the merge that minimizes the increase in within-cluster variance |
Different Linkage may result in completely different clustering structures.
scikit-learn implementation
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(
n_clusters=3,
linkage="ward",
)
labels = model.fit_predict(X_scaled)
Use other distances:
model = AgglomerativeClustering(
n_clusters=3,
linkage="average",
metric="cosine",
)
Note: Ward Linkage only supports Euclidean distance.
Dendrogram: tree diagram
An important advantage of hierarchical clustering is that it can display the merged relationship between samples or clusters through Dendrogram.
SciPy provides a more convenient drawing method:
from scipy.cluster.hierarchy import linkage, dendrogram
import matplotlib.pyplot as plt
Z = linkage(
X_scaled,
method="ward",
)
plt.figure(figsize=(10, 5))
dendrogram(Z)
plt.xlabel("Samples")
plt.ylabel("Linkage Distance")
plt.show()
For a large number of samples, the full Dendrogram may be too dense and a truncated display may be performed.
Clustering by distance threshold
model = AgglomerativeClustering(
n_clusters=None,
distance_threshold=2.0,
linkage="ward",
)
At this time, there is no need to specify the number of clusters in advance, but the division result is determined based on the hierarchical merging distance.
Features of Hierarchical Clustering
Advantages:
- Hierarchical relationships in data can be explored.
- K does not necessarily need to be fixed beforehand.
- Different Linkage and distance measures are supported.
- Dendrogram has better interpretability.
Limitations:
- The computational and memory overhead for large-scale data can be high.
- Sensitive to distance metric and Linkage selection.
- Merges that have already been completed are usually not undone in subsequent steps.
7. Clustering Metrics: Clustering evaluation
Clusters often do not have ground-truth labels, so model evaluation is more difficult than supervised learning.
Common methods include:
- Internal Evaluation: Based on intra-cluster closeness and inter-cluster separation.
- External Evaluation: When there is a reference tag, compare it with the real group.
- Stability Evaluation: Stability of analysis results to perturbations and parameter changes.
Silhouette Score: Contour coefficient
Measures how close a sample is to its cluster and how separated it is from other clusters.
For a single sample:
Among them:
- : The average distance to other samples in the same cluster.
- : Average distance to the nearest other clusters.
Value range:
Explanation:
- Close to 1: tightness within clusters and good separation between clusters.
- Close to 0: The sample is close to the cluster boundary.
- Less than 0: the sample is probably closer to other clusters.
from sklearn.metrics import silhouette_score
score = silhouette_score(X_scaled, labels)
Note: There must be at least two valid clusters and the number of clusters is less than the number of samples in order to calculate this indicator.
Silhouette is more friendly to some compact, convex clusters and may not necessarily correctly reflect the irregularly shaped clusters found by algorithms such as DBSCAN.
Davies–Bouldin Index
Measures the degree of dispersion within clusters relative to the distance between clusters.
from sklearn.metrics import davies_bouldin_score
score = davies_bouldin_score(X_scaled, labels)
The lower is usually better.
But the indicator also has a preference for certain cluster shapes.
Calinski–Harabasz Index
The clustering quality is measured by the ratio of the degree of dispersion between clusters and the degree of dispersion within clusters.
from sklearn.metrics import calinski_harabasz_score
score = calinski_harabasz_score(X_scaled, labels)
The higher is usually better.
Comparison of three internal indicators
| indicator | optimal direction | Main inspection |
|---|---|---|
| Silhouette | The higher the better | closeness and separation |
| Davies–Bouldin | The lower the better | Dispersion within clusters and similarity between clusters |
| Calinski–Harabasz | The higher the better | Dispersion ratio between clusters and within clusters |
These metrics alone cannot prove that clustering makes real business sense, nor should they be used mechanically for all shapes of clusters.
How to deal with noise points?
DBSCAN and HDBSCAN may label some samples as -1.
If -1 is directly regarded as an ordinary cluster, the internal clustering index may be misleading.
A common approach is to filter out noise points first and then evaluate the remaining clusters:
import numpy as np
from sklearn.metrics import silhouette_score
mask = labels != -1
X_valid = X_scaled[mask]
labels_valid = labels[mask]
n_clusters = len(np.unique(labels_valid))
if 2 <= n_clusters < len(labels_valid):
score = silhouette_score(
X_valid,
labels_valid,
)
But this only evaluates samples assigned to clusters.
Therefore the noise ratio should also be reported at the same time:
noise_ratio = np.mean(labels == -1)
Otherwise, an algorithm may obtain a high Silhouette Score even if it retains only a few samples.
8. External Evaluation: Evaluation when there are real labels
Some clustering tasks have reference labels, such as known sample categories, but you want to test whether the clustering algorithm can automatically discover these categories.
Common indicators:
| indicator | function |
|---|---|
| Adjusted Rand Index(ARI) | Measure the consistency of the clusters with the true groupings and perform random corrections |
| Normalized Mutual Information(NMI) | Measure the information consistency between two label partitions |
| Adjusted Mutual Information(AMI) | Random correction of mutual information |
| Homogeneity | Whether a cluster mainly contains the same ground truth category |
| Completeness | Whether the same real category is concentrated in the same cluster |
For example:
from sklearn.metrics import (
adjusted_rand_score,
normalized_mutual_info_score,
)
ari = adjusted_rand_score(y_true, labels)
nmi = normalized_mutual_info_score(y_true, labels)
These metrics do not require that the cluster label numbers match the true class numbers.
For example, the real categories are 0, 1, 2, and the cluster labels are 2, 0, 1. As long as the sample division is consistent, a high score can still be obtained.
Note: If the goal is purely to explore unknown groupings, there is usually no y_true, and these external indicators cannot be used.
9. How to choose a clustering algorithm?
| algorithm | Whether to specify K | Support noise | Features |
|---|---|---|---|
| K-Means | Yes | No | Efficient and suitable for compact clusters |
| DBSCAN | No | Yes | Suitable for irregular shapes and similar densities |
| HDBSCAN | No | Yes | Supports hierarchical density analysis and different density scales |
| Agglomerative | K or distance threshold can be specified | Noise is not marked separately by default | Hierarchical structure, Linkage adjustable |
Recommended scenarios
K-Means
- Customer segmentation.
- Numerical feature clustering.
- Data with larger scale and regular cluster shapes.
DBSCAN
- Spatial point clustering.
- There are obvious high-density areas in the data distribution.
- Want to identify noise points.
HDBSCAN
- The density of data clusters varies significantly.
- There are irregular shapes and noise.
- Unified DBSCAN
epsis difficult to determine.
Hierarchical Clustering
- Want to understand the hierarchical relationship between clusters.
- Interpretable Dendrogram required.
- Small and medium-scale experimental data and sample grouping.
10. Complete Example: Comparing Different Clustering Algorithms
Compare four algorithms using make_moons to generate nonspherical data.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import (
KMeans,
DBSCAN,
HDBSCAN,
AgglomerativeClustering,
)
# 1. Generate data
X, _ = make_moons(
n_samples=500,
noise=0.06,
random_state=42,
)
# 2. Standardization
X_scaled = StandardScaler().fit_transform(X)
# 3. Define clustering model
models = {
"K-Means": KMeans(
n_clusters=2,
n_init=10,
random_state=42,
),
"DBSCAN": DBSCAN(
eps=0.25,
min_samples=5,
),
"HDBSCAN": HDBSCAN(
min_cluster_size=10,
min_samples=5,
),
"Hierarchical": AgglomerativeClustering(
n_clusters=2,
linkage="single",
),
}
# 4. train and visualize
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
for ax, (name, model) in zip(axes.flat, models.items()):
labels = model.fit_predict(X_scaled)
ax.scatter(
X_scaled[:, 0],
X_scaled[:, 1],
c=labels,
cmap="tab10",
s=12,
)
ax.set_title(name)
plt.tight_layout()
plt.show()
The clusters of this data set are crescent-shaped, which is suitable for displaying:
- K-Means Restrictions on non-convex clusters.
- DBSCAN / HDBSCAN Ability to identify irregular clusters.
- Single Linkage method of identifying connected structures.
These parameters are only demonstration and cannot be directly applied to any real data set.
11. Frequently Asked Questions and Practical Notes
Does clustering necessarily require standardization?
Not necessarily, but distance-based algorithms often rely heavily on feature scale.
K-Means, DBSCAN, HDBSCAN and Agglomerative Clustering all require attention to distance measurement and feature representation.
Do cluster labels have real class meaning?
uncertain.
Clustering discovers the data structure under the current features and distance measures.
For example, users are divided into three clusters, which does not mean that there are three objective customer types.
Further analysis of the characteristic distribution of each cluster is required to give business interpretation.
Can the clustering results predict new samples?
Depends on the algorithm.
- K-Means provides
predict(), which assigns new samples to existing cluster centers. - DBSCAN, HDBSCAN and AgglomerativeClustering of scikit-learn are mainly oriented to clustering existing data and do not provide the same general
predict()interface.
If you need to stably classify new samples that are coming in, you should consider this in advance when selecting.
Why is high-dimensional data clustering difficult?
As the dimensionality increases, the distances between different samples may become indistinguishable.
Common processing ideas:
- Remove irrelevant features.
- Feature standardization.
- Choose an appropriate distance metric.
- Use methods such as PCA to reduce dimensionality.
- Check the stability of the clustering results under different parameters and random perturbations.
Does a high clustering evaluation score necessarily mean that the clustering is reasonable?
uncertain.
Cluster evaluation requires a combination of:
- Mathematical indicators.
- noise ratio.
- Cluster size.
- Stability under different parameters.
- Business interpretability.
Summary
| Knowledge points | importance |
|---|---|
| Clustering / Unsupervised Learning | core |
| Distance Metrics / Feature Scaling | core |
| K-Means / Centroid / Inertia | core |
| K-Means / Elbow Method | important |
| DBSCAN / Core / Border / Noise | core |
| DBSCAN / eps / min_samples | core |
| HDBSCAN / Density Hierarchy | important |
| HDBSCAN / min_cluster_size | important |
| Agglomerative / Linkage | core |
| Dendrogram | important |
| Silhouette Score | core |
| Davies–Bouldin / Calinski–Harabasz | important |
| ARI / NMI | on demand |
| Cluster Stability / Noise Ratio | important |
The five most important concepts:
- Distance / Similarity: Clustering results are highly dependent on feature scale, distance measure and feature representation.
- Centroid-based Clustering: K-Means minimizes the sum of squares within the cluster by iteratively updating the cluster centers.
- Density-based Clustering: DBSCAN, HDBSCAN Discover irregular clusters based on density structure and can identify noise.
- Hierarchical Clustering: Builds a hierarchy by gradually merging samples, and Linkage determines the merging rules for clusters.
- Clustering Evaluation: It is necessary to comprehensively judge the clustering results by combining internal indicators, noise ratio, stability and business significance.