Skip to content
Lambdian

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 kk: the number of clusters falls out of the data and one parameter, the bandwidth hh (window size).

Bandwidth and cost

hh is the only knob: small hh gives many small modes, large hh few. scikit-learn's estimate_bandwidth uses a quantile of pairwise distances as a starting point. Each iteration costs O(n2)O(n^2) 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

  1. 1
    Choose a kernel (Gaussian or flat) and bandwidth hh.
  2. 2
    Start a seed at every point (or at grid bins).
  3. 3
    Move each seed to the kernel-weighted mean of the data around it; repeat until it stops moving.
  4. 4
    Merge seeds that converged within h/2h/2 of each other into one mode; label each point by its seed's mode.

The maths

Mean-shift vector

m(x)−x=∑iKh(x−xi) xi∑iKh(x−xi)−x\mathbf{m}(\mathbf{x}) - \mathbf{x} = \frac{\sum_i K_h(\mathbf{x}-\mathbf{x}_i)\,\mathbf{x}_i}{\sum_i K_h(\mathbf{x}-\mathbf{x}_i)} - \mathbf{x}

Link to the density gradient

m(x)−x∝∇f^(x)f^(x)\mathbf{m}(\mathbf{x}) - \mathbf{x} \propto \frac{\nabla\hat f(\mathbf{x})}{\hat f(\mathbf{x})}

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…

Low-dimensional data where you want the modes of the density: image segmentation, tracking, finding hotspots.

Check your understanding

Question 1

Q1What determines the number of clusters in mean shift?

Question 2

Q2Each mean-shift step moves a point…

Question 3

Q3Doubling the bandwidth typically…

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).
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.