Mean shift
Find the peaks of a density estimate by repeatedly moving to the local mean; clusters are basins.
Animated explanation
The idea
Imagine the data as a landscape where dense areas are hills. Mean shift places a walker on every point and lets each one climb uphill until it reaches a summit (a mode of the density). Points whose walkers reach the same summit belong to the same cluster.
The climbing step is beautifully simple: look at the data within a window around you, weighted by a kernel, and move to their mean. That move always points uphill on a kernel density estimate. There is no : the number of clusters falls out of the data and one parameter, the bandwidth (window size).
Bandwidth and cost
is the only knob: small gives many small modes, large few. scikit-learn's estimate_bandwidth uses a quantile of pairwise distances as a starting point. Each iteration costs naively, so mean shift suits small to medium datasets (or binned seeds). It is used for image segmentation (in colour + position space) and for object tracking (CamShift).
The algorithm, step by step
- 1Choose a kernel (Gaussian or flat) and bandwidth .
- 2Start a seed at every point (or at grid bins).
- 3Move each seed to the kernel-weighted mean of the data around it; repeat until it stops moving.
- 4Merge seeds that converged within of each other into one mode; label each point by its seed's mode.
The maths
Mean-shift vector
Link to the density gradient
Strengths and weaknesses
Strengths
- No number of clusters to choose
- Arbitrary cluster shapes (basins of attraction)
- One intuitive parameter
Weaknesses
- O(n²) per iteration
- The bandwidth is global; varying densities are hard
- Poor in high dimensions
Reach for it when…
Check your understanding
Lambdian Lab
Mean shift with a flat kernel
Implement mean shift with a flat kernel (all points within distance h, equal weight).
- shift(points, X, h): move every row of points to the mean of the X rows within h of it.
- mean_shift(X, h, iters, tol): start from X itself; iterate shift until no point moves more than tol; then merge converged points closer than h/2 into modes. Return (modes, labels).