Mean Shift

Machine Learning
Introduced by
Fukunaga, K. & Hostetler, L. D.; extended by Comaniciu, D. & Meer, P.
Year
1975
Type
Non-parametric mode-seeking / density-based clustering

What does it do?

Mean Shift is a non-parametric, iterative mode-seeking algorithm that identifies clusters as the peaks of an underlying probability density.

Fukunaga and Hostetler (1975) introduced the underlying gradient-estimation idea for pattern recognition, and Comaniciu and Meer (2002) extended it into a general procedure for feature-space analysis and image segmentation. Unlike k-means, Mean Shift does not require the number of clusters to be specified in advance; the cluster structure comes from the data density, although the bandwidth still has to be chosen.

The intuition behind the method

Imagine placing a seed at each data location and letting it move uphill toward the nearest concentration of data. Each seed settles at a local peak, or mode, of the estimated density, and seeds that settle at the same peak belong to the same cluster. Mean Shift formalises this by smoothing the data with a kernel to form a density surface and then repeatedly moving each point toward the kernel-weighted average of its neighbours. The bandwidth controls how far that smoothing reaches: a large bandwidth merges nearby peaks, while a small bandwidth reveals finer structure and can split one group into several.

History

Fukunaga and Hostetler (1975) introduced the mean shift procedure as a way to estimate the gradient of a density function and to follow gradient lines in pattern recognition. The method remained a relatively specialised tool for years after that. Comaniciu and Meer (2002) generalised it: they proved convergence of the recursive procedure for discrete data, related it to the Nadaraya-Watson estimator and to robust M-estimators of location, and applied it to discontinuity-preserving smoothing and image segmentation.

When to use it

Choose Mean Shift when the number of clusters is unknown or unnatural to fix in advance, when cluster shapes may be irregular or non-convex, and when the density of the data is a meaningful description of structure. It suits low-dimensional feature spaces such as image pixels with colour and position, object tracking in video, and exploratory analysis of spatial or feature data. Avoid it when the data are very high-dimensional, since density estimates degrade there, or when the dataset is so large that the naive quadratic cost per iteration is prohibitive without acceleration. Its results also depend heavily on bandwidth, so a plan for bandwidth selection, such as a sensitivity analysis or a validity index, should be part of the analysis. Rules of thumb such as Silverman's rule were derived for density estimation and must be adapted for multivariate data and for mode-finding. Cross-validation is another option. Either may serve as a starting point, but none is universally reliable, so check how the number of modes changes across a range of bandwidths.

Limitations and considerations

  • Each seed costs O(n) per iteration, so updating all n seeds costs O(n²) per iteration. This becomes slow for large datasets unless neighbourhood search is accelerated with structures such as ball trees or approximate nearest-neighbour methods, or the number of seeds is reduced.
  • Results are sensitive to the bandwidth h: a poor choice can merge distinct clusters or fragment one cluster into several modes.
  • No automatic bandwidth selection is universally applicable, so cross-validation or domain knowledge is usually needed.
  • Density estimates degrade in high-dimensional spaces, which limits the method unless dimensionality is reduced first.
  • Isolated points can form their own single-point modes, so outlier handling usually requires post-processing rather than being automatic.
  • The method yields no explicit generative model, so assigning a new point to a cluster requires re-running the procedure or using a proximity heuristic.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • No need to specify the number of clusters in advance; the number of modes follows from the data density at the chosen bandwidth.
  • Finds arbitrarily shaped clusters, because clusters are defined as basins of attraction of density modes rather than as spherical regions as in k-means.
  • In the image-analysis algorithms of Comaniciu and Meer (2002), the only user-set parameter is the resolution of the analysis (the bandwidth). The general method additionally requires a kernel choice and a mode-merging tolerance.
  • Each cluster centre is a density mode, so a few distant points do not move a well-populated mode much; isolated points, however, can form their own modes (see limitations).
  • Convergence to a stationary point of the density is established for the discrete-data procedure in Comaniciu and Meer (2002).

Applications

  • Image segmentation: grouping pixels by colour and spatial position into coherent regions, as in Comaniciu and Meer (2002).
  • Discontinuity-preserving smoothing of images, where pixels are moved toward their density modes.
  • Object tracking in video, following an object's mode through frames in feature space (the Camshift variant).
  • Exploratory clustering of spatial or feature data where the number of natural groupings is unknown.
  • Outlier screening: points far from any dense mode receive low density estimates and can be flagged for inspection.

How it works

How it works

1

A kernel density estimate is placed over the data. Each observation contributes a kernel of bandwidth h centred on it, with Epanechnikov and Gaussian kernels the usual choices. Write the kernel as K(x) = c·k(||x||²), where k is the kernel profile and c a normalising constant. The sum of these kernels forms a smooth density surface over the feature space. The bandwidth h is the most important hyperparameter, because it sets the resolution at which density modes are detected.

Formula
\hat{f}(\mathbf{x}) = \frac{1}{n h^d} \sum_{i=1}^{n} K\!\left(\frac{\mathbf{x} - \mathbf{x}_i}{h}\right)
2

For a query point x, the mean shift vector m(x) is the difference between the kernel-weighted centroid of the points inside the kernel window and x itself. The weight function is g(u) = -k'(u), the negative derivative of the profile k. With this choice, m(x) is proportional to the gradient of the density estimate divided by the local density, so it points uphill toward a higher-density region. The Epanechnikov kernel gives g constant inside the window, so the weighted mean is a plain (uniform-weight) mean of the points in the window. The Gaussian kernel gives Gaussian weights.

Formula
\mathbf{m}(\mathbf{x}) = \frac{\sum_{i=1}^{n} \mathbf{x}_i \, g\!\left(\left\|\frac{\mathbf{x}-\mathbf{x}_i}{h}\right\|^2\right)}{\sum_{i=1}^{n} g\!\left(\left\|\frac{\mathbf{x}-\mathbf{x}_i}{h}\right\|^2\right)} - \mathbf{x}
3

The query point is moved by adding m(x) to its current position, and the mean shift vector is recomputed at the new location. The update repeats until the shift falls below a convergence threshold. Comaniciu and Meer (2002) prove, for discrete data, that this recursive procedure converges to the nearest stationary point of the underlying density estimate. In the usual case the trajectory climbs uphill and ends at a mode. Stationary points in general also include saddle points and minima, so the converged locations should be read as candidate modes, and clusters are formed from them.

Formula
\mathbf{x}^{(t+1)} \leftarrow \mathbf{x}^{(t)} + \mathbf{m}\!\left(\mathbf{x}^{(t)}\right)
4

After convergence, each starting point is associated with a mode. Points whose trajectories end at the same mode, within a small merging tolerance, are grouped into one cluster. The number of clusters is the number of distinct modes found, so no target k is set in advance. The merging tolerance therefore directly affects the final count.

Common pitfalls

  • Using one global bandwidth when clusters differ strongly in density. Adaptive-bandwidth variants exist for this case and should be considered.
  • Choosing the mode-merging tolerance carelessly: a loose tolerance collapses distinct clusters, while a tight one leaves many near-duplicate modes.
  • Applying Mean Shift directly to high-dimensional data without reducing dimensionality first, which degrades the density estimate.
  • Treating the number of discovered clusters as definitive without checking how it changes across a range of bandwidths.
  • Assuming the result is reproducible by default. If every data point is used as a seed, the procedure is deterministic; randomness enters only when seeds are subsampled, so the seed should be fixed in that case.

Frequently asked questions

How do I choose the bandwidth?

Bandwidth selection is the central practical challenge. Common strategies include Silverman's rule of thumb (derived for density estimation and needing adaptation for multivariate data), least-squares cross-validation on the kernel density estimate, and a grid search guided by a cluster validity index such as the silhouette score. It is good practice to run Mean Shift over a range of bandwidths and inspect how the number of modes and their positions change, rather than relying on a single automatic value.

Does Mean Shift always converge?

Comaniciu and Meer (2002) prove that the recursive mean shift procedure converges to the nearest stationary point of the underlying density for discrete data. In the usual case this is a mode, although stationary points in general also include saddle points and minima. Epanechnikov and Gaussian kernels are the usual choices in practice. The speed of convergence depends on the bandwidth and the geometry of the data.

How does Mean Shift compare to DBSCAN?

Both are density-based and require no pre-specified number of clusters. DBSCAN defines clusters through reachability from core points and labels low-density points as noise explicitly. Mean Shift defines clusters as basins of attraction of density modes, so every point is assigned to some mode, and isolated points can form their own single-point modes. The two methods therefore treat low-density points differently, and this difference matters when outliers are present.

Is Mean Shift suitable for very large datasets?

In its naive form, each seed costs O(n) per iteration, so running all n seeds costs O(n²) per iteration, which can be prohibitive for tens of thousands of points. Using m seeds reduces this to O(m·n). Other practical options include restricting neighbourhood search with ball-tree or k-d tree structures, or using the Blurring Mean Shift variant. For very large datasets, sub-sampling followed by assignment of the remaining points is common.

Related methods

Sources

  1. Fukunaga, K. & Hostetler, L. D. (1975). The estimation of the gradient of a density function, with applications in pattern recognition. IEEE Transactions on Information Theory, 21(1), 32–40.

    Open DOI reference
  2. Comaniciu, D. & Meer, P. (2002). Mean shift: A robust approach toward feature space analysis. IEEE Transactions on Pattern Analysis and Machine Intelligence, 24(5), 603–619.

    Open DOI reference
  3. Hastie, T., Tibshirani, R. & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed., Ch. 14). Springer.

    ISBN: 978-0-387-84858-7