Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Scikit-Learn · Class

AgglomerativeClustering

AgglomerativeClustering hierarchically groups samples by repeatedly merging clusters. Choose either a target cluster count or a distance threshold, with linkage and optional connectivity controlling the merges.

How it works

The estimator builds a hierarchy by repeatedly merging the pair of clusters that minimizes the selected linkage criterion. You can stop at a requested number of clusters or use a distance threshold; optional connectivity constraints limit which samples may be neighbors during merging.

Syntax

class sklearn.cluster.AgglomerativeClustering(*, n_clusters=2, metric='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', distance_threshold=None, compute_distances=False)

Parameters

NameTypeDescription
n_clustersint or None, default=2Number of clusters to find; must be None when distance_threshold is set.
metricstr or callable, default='euclidean'Metric used to compute linkage; supports euclidean, l1, l2, manhattan, cosine, precomputed, or a callable.
memorystr or joblib.Memory instance, default=NoneUsed to cache the output of the computation.
connectivityarray-like, sparse matrix, or callable, default=NoneConnectivity matrix or callable defining neighboring samples.
compute_full_treebool or 'auto', default='auto'Whether to compute the full tree; distance_threshold requires True.
linkage{'ward', 'complete', 'average', 'single'}, default='ward'Linkage criterion: ward, complete, average, or single.
distance_thresholdfloat, default=NoneLinkage distance at or above which clusters are not merged.
compute_distancesbool, default=FalseWhether to compute distances between clusters.

Returns

Fitted estimator with labels_ containing cluster labels for each sample; additional fitted attributes include children_, n_connected_components_, n_leaves_, and, when computed, distances_.

Key points

  • The algorithm starts with individual samples and repeatedly merges clusters according to linkage distance.
  • n_clusters specifies the target number of output clusters and defaults to 2.
  • metric selects the distance calculation and supports named metrics or a callable.
  • linkage controls the inter-cluster distance rule and accepts ward, complete, average, or single.
  • connectivity can encode which samples are considered neighbors under a known data structure.
  • compute_distances enables cluster-distance computation even when threshold-based stopping is disabled.

Common mistakes

  • Do not set n_clusters together with distance_threshold; choose one stopping rule.
  • Using distance_threshold also requires computing the complete hierarchy.
  • Ward linkage cannot be paired with arbitrary distance metrics.
  • With a precomputed metric, pass pairwise distances rather than ordinary feature rows.

Example: Cluster sample data

from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
model = AgglomerativeClustering(n_clusters=3, linkage="ward")
labels = model.fit_predict(X)
print(labels)

Creates synthetic points, groups them into three clusters with Ward linkage, and prints the assigned cluster label for each sample.

When to use it

Hierarchical clustering

Explore nested group structure in unlabeled feature data.

Topology-aware clustering

Restrict merges to nearby or structurally connected samples.

Distance-matrix clustering

Use pairwise distances when original feature vectors are unavailable.

Interview questions

QWhat does AgglomerativeClustering do?

It is a hierarchical clustering estimator that recursively merges pairs of sample clusters. The selected linkage determines the distance criterion used to choose each merge.

Follow-up: How can the hierarchy be stopped? Set n_clusters to select a fixed number, or set distance_threshold to stop merging at a linkage distance.

QHow do linkage choices differ?

linkage chooses how distances between clusters are computed: Ward minimizes merged-cluster variance, average uses mean pairwise distances, complete uses the maximum, and single uses the minimum. The available values are ward, complete, average, and single.

Follow-up: Which metric restriction applies to Ward? Only euclidean and l2 are accepted.

QWhat is the purpose of connectivity?

connectivity describes neighboring samples according to the data structure. It can be supplied as a connectivity matrix or as a callable that transforms the data into one.

Follow-up: Why use connectivity? It constrains candidate merges to reflect local structure, such as neighbors produced by kneighbors_graph.

  • FeatureAgglomeration
  • Birch
  • DBSCAN
  • KMeans
  • MiniBatchKMeans

Source: AgglomerativeClustering — scikit-learn 1.9.1 documentation. Checked 2026-10-15.