TExcelTAD
Home › SciPy › SciPy Kernel Density Estimation

SciPy Kernel Density Estimation

A histogram shows the shape of your data, but it looks different depending on how you choose the bins, and it's jagged. Kernel density estimation (KDE) gives a smooth estimate of the underlying probability density instead. The idea is simple: place a small bump (a kernel, usually a Gaussian) on top of every data point and add the bumps up.

scipy.stats.gaussian_kde does exactly that, and it doesn't assume the data follows any named distribution — which makes it ideal for data with several peaks.

A first density estimate

python · try it yourself
import numpy as np
from scipy import stats

data = np.array([2.1, 2.5, 2.8, 3.0, 3.1, 3.3, 8.0, 8.4, 8.5, 9.1])
kde = stats.gaussian_kde(data, bw_method=0.3)   # narrow bumps; see "Choosing the bandwidth"

for x in [1, 3, 5.5, 8.5, 11]:
    print(f"density at {x:3}: {kde(x)[0]:.4f}")
print(f"bandwidth factor: {kde.factor:.4f}")
density at   1: 0.0456
density at   3: 0.2402
density at 5.5: 0.0061
density at 8.5: 0.1631
density at  11: 0.0063
bandwidth factor: 0.3000

The estimated density is high near the two clusters (around 3 and around 8.5) and low in the gap between them. Calling the KDE object evaluates the density; it always returns an array.

Bimodal data: KDE versus a normal fit

Fitting a single normal distribution to two-peaked data hides the structure completely. KDE reveals it:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

rng = np.random.default_rng(10)
# Commute times: a group that walks (~15 min) and a group that drives (~40 min)
times = np.concatenate([rng.normal(15, 3, 150), rng.normal(40, 6, 100)])

grid = np.linspace(0, 65, 400)
kde = stats.gaussian_kde(times)
mu, sigma = stats.norm.fit(times)

plt.hist(times, bins=30, density=True, alpha=0.4, label="histogram")
plt.plot(grid, kde(grid), lw=2, label="KDE")
plt.plot(grid, stats.norm(mu, sigma).pdf(grid), "--", label="single normal fit")
plt.xlabel("commute time (min)")
plt.legend()
plt.show()

peaks = grid[1:-1][(kde(grid)[1:-1] > kde(grid)[:-2]) & (kde(grid)[1:-1] > kde(grid)[2:])]
print("KDE peaks at:", np.round(peaks, 1), "minutes")
print(f"normal fit: mean {mu:.1f}, std {sigma:.1f} (one peak only)")
KDE peaks at: [14.5 39.3] minutes
normal fit: mean 24.0, std 12.5 (one peak only)

Choosing the bandwidth

The bandwidth controls how wide each bump is. Too narrow and the estimate is spiky; too wide and real features get smoothed away. SciPy picks one automatically with Scott's rule (the default) or Silverman's rule, and you can pass a number to scale it yourself:

python · try it yourself
import numpy as np
from scipy import stats

rng = np.random.default_rng(10)
times = np.concatenate([rng.normal(15, 3, 150), rng.normal(40, 6, 100)])
grid = np.linspace(0, 65, 651)

for bw in ["scott", "silverman", 0.05, 0.8]:
    kde = stats.gaussian_kde(times, bw_method=bw)
    dens = kde(grid)
    n_peaks = np.sum((dens[1:-1] > dens[:-2]) & (dens[1:-1] > dens[2:]))
    label = bw if isinstance(bw, str) else f"factor {bw}"
    print(f"{label:11} factor={kde.factor:.3f}  peaks found: {n_peaks}")
scott       factor=0.331  peaks found: 2
silverman   factor=0.351  peaks found: 2
factor 0.05 factor=0.050  peaks found: 13
factor 0.8  factor=0.800  peaks found: 1

A tiny bandwidth invents many spurious peaks; a huge one merges the two real groups into one.

Probabilities and sampling from a KDE

A KDE is a real probability density, so you can integrate it to get probabilities and draw new samples from it:

python · try it yourself
import numpy as np
from scipy import stats

rng = np.random.default_rng(10)
times = np.concatenate([rng.normal(15, 3, 150), rng.normal(40, 6, 100)])
kde = stats.gaussian_kde(times)

print(f"P(commute < 20 min)  = {kde.integrate_box_1d(-np.inf, 20):.3f}")
print(f"share in data < 20   = {(times < 20).mean():.3f}")
print(f"P(25 to 30 min)      = {kde.integrate_box_1d(25, 30):.3f}")

new = kde.resample(5, seed=np.random.default_rng(3))
print("5 simulated commutes:", np.round(new[0], 1))
P(commute < 20 min)  = 0.524
share in data < 20   = 0.588
P(25 to 30 min)      = 0.044
5 simulated commutes: [22.6  3.8 16.  28.8 16.1]

Two dimensions

gaussian_kde also works in several dimensions. Pass the data with one row per variable (shape (d, n)):

python · try it yourself
import numpy as np
from scipy import stats

rng = np.random.default_rng(6)
x = rng.normal(0, 1, 300)
y = 0.8 * x + rng.normal(0, 0.5, 300)

kde2 = stats.gaussian_kde(np.vstack([x, y]))
points = np.array([[0, 0, 2], [0, 2, 2]])     # columns: (0,0), (0,2), (2,2)
print("density at (0,0), (0,2), (2,2):", np.round(kde2(points), 4))
density at (0,0), (0,2), (2,2): [0.2582 0.0005 0.0383]

The point (2, 2) lies along the direction of correlation, so it's much more likely than (0, 2), even though it's farther from the centre.

Tip: KDE gets unreliable near hard boundaries (for example, times can't be negative). A common fix is to estimate the density of log(data) and transform back.

Test yourself

What does kernel density estimation do?

  1. Fits a normal distribution
  2. Places a small bump on each data point and sums them to estimate a smooth density
  3. Counts values in fixed bins
  4. Finds clusters with k-means

What happens with a very small bandwidth?

  1. The estimate becomes a straight line
  2. The estimate becomes spiky with many false peaks
  3. All peaks merge into one
  4. KDE raises an error

For 2-D data, what shape must the array passed to gaussian_kde have?

  1. (n, 2)
  2. (2, n) — one row per variable
  3. (n,)
  4. (n, n)