Mean shift clustering

Also known as: mean shift

On this page 7

Mean shift clustering is a nonparametric, density-based clustering algorithm that repeatedly moves each data point toward the weighted mean of its neighbors until it reaches a local maximum of the estimated data density, called a mode. In machine learning, points that converge to the same mode form one cluster, so the method does not require the number of clusters in advance.

The procedure was proposed by Fukunaga and Hostetler in 1975, generalized by Cheng in 1995 and popularized for image analysis by Comaniciu and Meer in 2002. Within artificial intelligence, mean shift is valued for arbitrary cluster shapes and a single intuitive parameter, the bandwidth, but its computational cost limits it to small and medium datasets.

How mean shift climbs the density surface

Mean shift is a gradient ascent procedure on a kernel density estimate. Instead of computing the density explicitly, it uses the fact that the vector from a point to the kernel-weighted mean of its neighborhood, the mean shift vector, points in the direction of steepest density increase.

  1. Place a window, defined by a kernel and a bandwidth, around each starting point.
  2. Compute the weighted mean of all data points inside the window.
  3. Move the window center to that mean.
  4. Repeat until the shift is smaller than a convergence tolerance.
  5. Merge converged centers that lie closer than a threshold and assign each point to its mode.

Because the step size shrinks automatically near a peak, the algorithm needs no learning rate. With a Gaussian or flat kernel, convergence to a stationary point is guaranteed for the sequence of window centers, although the stopping point can occasionally be a saddle rather than a true maximum.

The link to kernel density estimation explains the behavior precisely. With a kernel profile k, the mean shift vector equals the density gradient estimated with the shadow kernel of k, divided by the density itself. The step is therefore large in sparse regions and small near a peak, which makes the procedure an adaptive form of gradient ascent.

Bandwidth, kernels and other key parameters

The bandwidth is the decisive parameter of mean shift clustering. It sets the radius of influence of each point and therefore the smoothness of the density surface: a small value produces many small clusters, while a large value merges distinct groups into a few broad ones.

ParameterTypical settingEffect of a larger value
BandwidthEstimated from data, for example by nearest-neighbor quantilesFewer, larger clusters
KernelFlat or GaussianGaussian gives smoother weighting
Convergence toleranceAbout 0.001 times the bandwidthFaster but less precise modes
SeedsAll points or a binned subsetMore seeds raise cost and precision
Minimum bin frequency1 to a few pointsIgnores sparse seed regions
Main parameters and their effect

Automatic bandwidth estimators, such as the quantile of pairwise nearest-neighbor distances, give a reasonable starting point but rarely the best one. Practitioners usually run a short sweep and inspect the number and stability of clusters. Feature scaling is essential, because one bandwidth applies to all dimensions.

Variants address uneven density. Adaptive mean shift assigns each point its own bandwidth based on local density, and blurring mean shift moves the data points themselves, which converges faster but can collapse clusters if run too long.

Mean shift compared with other clustering methods

Mean shift belongs to the mode-seeking family of clustering algorithms. It shares the density view of DBSCAN and the centroid view of k-means, but differs from both in what it needs from the user.

MethodNumber of clustersCluster shapeMain parameter
Mean shiftFound automaticallyArbitrary, around density modesBandwidth
k-means clusteringSet in advanceRoughly sphericalk
DBSCANFound automaticallyArbitrary, connected dense regionsEpsilon and minimum points
Gaussian mixture modelSet in advanceEllipsoidalNumber of components
HDBSCANFound automaticallyArbitrary, varying densityMinimum cluster size
Mean shift and neighboring clustering algorithms

Unlike DBSCAN, standard mean shift assigns every point to a cluster and has no explicit noise label, although isolated points may end up in tiny clusters that can be filtered afterward. Unlike k-means, it is deterministic when all points are used as seeds, so repeated runs give identical results.

Where mean shift is used

Mean shift performs best on low-dimensional data with clear density peaks. Its classic applications come from computer vision, where pixels are described by a few color and position coordinates.

ApplicationFeature spaceWhy mean shift fits
Image segmentationColor plus pixel positionUnknown number of regions, edge preservation
Object trackingColor histogram of a targetFast local mode search per frame
Geospatial hotspot detectionLatitude and longitudeClusters follow real density peaks
Color quantizationThree color channelsFinds dominant colors automatically
Mode finding in sensor dataFew numeric readingsRobust to irregular shapes
Typical applications and why mean shift fits

The CamShift tracker, used in early face and hand tracking, extends mean shift with an adaptive window size. Libraries such as scikit-learn and OpenCV provide standard implementations, the former with seeding by binning to reduce cost.

Mean shift also serves as a post-processing step for other models. Detection pipelines can merge overlapping predictions by finding modes among box centers, and analysts sometimes apply it to low-dimensional embeddings produced by UMAP or t-SNE to label visible groups.

Limitations and common mistakes

The main drawback is computational cost. A naive implementation needs on the order of n squared operations per iteration, which becomes impractical beyond tens of thousands of points without spatial indexing or seed reduction.

  • High-dimensional data: density estimates become unreliable because of the curse of dimensionality, so reduce dimensions first.
  • Unscaled features: a feature with large units dominates the distance and distorts every window.
  • One bandwidth for uneven density: dense and sparse clusters cannot both be captured well.
  • Treating modes as ground truth: modes depend on the bandwidth, so validate clusters against domain knowledge.

In practice, dimensionality reduction plus a bandwidth sweep resolves most problems. When density varies strongly or noise must be labeled explicitly, HDBSCAN is usually the better choice.

In plain words

Imagine people scattered across a dark field, each holding a flashlight. Every person looks around, sees where others stand most closely, and takes a step toward that crowd. They repeat this again and again. In the end, people gather at a few crowded spots.

Each crowded spot is a group. Nobody had to say how many groups there should be. The only choice is how far each person can see. Short sight makes many small groups. Long sight makes a few big ones.

A real-world example

A city transport agency wants to know where ride-hailing pickups concentrate in the evening. Analysts take 40,000 pickup locations from one month, convert latitude and longitude to meters and run mean shift with a bandwidth of about 250 meters, using binned seeds to keep run time under a minute.

The algorithm finds 27 pickup hotspots without any preset cluster count, including a cluster around a new concert venue that planners had not listed. Testing bandwidths of 150 and 400 meters shows that the 15 largest hotspots remain stable. The agency then places temporary pickup zones at the top 10 locations, which reduces double parking complaints on those streets.