B4B33RPZ · Pattern Recognition and Machine Learning
Parzen windows
Lab 4: estimating a probability density from samples: histogram, k-NN and Parzen windows (kernel density estimation)
Klára JanouškováFEE CTU, Prague
Part I
Recap
What have we assumed so far?
p(x∣k)
priors p(k)
loss W
Bayesian decision
known
known
known
Neyman–Pearson, minimax, Wald
known
unknown
unknown
Today
unknown
we only have samples x1,…,xn
Probability density estimation: from samples x1,…,xn drawn from p(x), build an estimate p^(x). For a classifier we do it once per class: the samples of class k give p^(x∣k).
How can we estimate a density?
Parametric (next lab)
Assume a shape, e.g. a Gaussian; estimate its few parameters (μ, σ).
MLE, MAP, Bayesian estimation
Non-parametric (today)
No fixed shape: the samples themselves define p^.
histogram, k-NN, Parzen windows = kernel density estimation
Mixtures
A sum of a few simple densities: in between the two.
mixture of Gaussians, deep neural networks
Parametric: few numbers to learn, but if the true density has a different shape (two bumps, one Gaussian fitted), the error stays however many samples we get. Non-parametric: follows any shape given enough data, but needs more samples and keeps all of them to evaluate p^(x).
Part II
Histogram
We have samples. What is p(x)?
We have:{x1,x2,…,xn}, each xi∼p(x), independent
We want:p(x)
Where is p(x) high? Where is it zero? How would you decide?
Count: many samples close together → p(x) high; no samples → p(x)≈0.
Simplest way to count: cut the axis into bins and count the samples in each bin.
Counts as bars = a histogram. But a count is not a density: how tall should a bar be?
How tall should a histogram bar be?
The same bins as before, now as bars. A bin B holds NB of the N samples and has width wB. Which height p^?
↓ what the data say: the fraction of samples that landed in the bin
fraction in B=NNB
The bin has width wB.
↓ what our bar says: probability of the bin = area of the bar = height × width
area of the bar=p^(x)wB
↓ we choose the height so that the two agree
p^(x)wB=NNB
↓ divide both sides by wB
p^(x)=NwBNB
In words: take each bin's relative frequency NNB and divide it by the bin width wB. Bin [−2,−1): 4013÷1=0.325
Histogram: pros and cons?
Discuss in pairs for a minute, then we collect.
✓ Pros
✓ simple, easy to visualise
✓ we don't need to keep the xi: the bin counts are enough
✓ fast to evaluate: find the bin, read the height
✗ Cons
✗ step-like, not smooth
✗ we must choose wB: too small → empty bins, too large → no detail
✗ depends on where the bins start
✗ sparse for dimension >2: m bins per axis → mD cells
Try it: bin width and bin origin
Part III
More dimensions: K, N and V
More dimensions?
1D: p^=NB/(NwB). In 2D the bin is a square region R around x. Rename: count NB→K, size wB→V (area s2; a volume in D dims).
↓ what our estimate says: p^ is constant over R, so probability = height × volume
probability of R=p^(x)V
↓ what the data say: K of the N samples fell into R
fraction in R=NK
↓ we choosep^ so that the two agree, then divide by V
p^(x)V=NK⇒p^(x)=NVK
Two ways to use it (N fixed): fix V, count K: histogram, Parzen windows fix K, find V: k-nearest neighbours
From now on R is a ball around x (a circle in 2D): one number, the radius r; V=πr2. k-NN grows r until K samples are inside.
Fix K, find V: k-nearest neighbours
R is now a circle around the query. N=21 samples, K=3. Question: is p^ higher at q1 or at q2?
q1: grow a circle until it holds 3 points. The 3rd nearest point sets the radius: r=2.42
q2: the 3 nearest are much closer: r=1.12
↓ in 2D the "volume" of the circle is its area
p^(q)=NVK,V=πr2
q1: p^=21⋅π⋅2.4223=21⋅18.33=0.0078
q2: p^=21⋅π⋅1.1223=21⋅3.93=0.0364
Same K, smaller circle V → higher density p^ at q2.
Same 21 samples. Now every query gets a circle of the same radiusr=2. Count the points inside.
q1: K=1
q2: K=5
↓ now V is the same for both queries, only K changes
p^(q)=NVK,V=π⋅22=12.6
q1: p^=21⋅12.61=0.0038
q2: p^=21⋅12.65=0.0189
Both ways agree: q2 lies in the denser region. A window around x that counts points is the idea behind Parzen.
Quick check: fixed K or fixed V?
We have N≥K samples. With which estimate can some x get p^(x)=0?
p^=K/(NV). A fixed window in an empty area holds K=0, so p^=0. A k-NN circle grows until it holds K samples, so p^>0 everywhere (with fewer than K samples k-NN is not defined at all).
In the k-NN estimate, a query far from all points gets…
K is fixed, so V grows with the distance: p^∼1/V is small but never 0.
k-NN density in 1D: what does K do?
K=1: a spike wherever two samples are close: overfits.
K=5: follows both bumps, still noisy.
K=20: smooth, but flat and with heavy tails.
Notice the tails: far from the data the k-NN estimate stays much too high. Why, and what it means: next slide.
What happens far from the data?
A query right of all samples, x=6. Its K=5 nearest samples are the rightmost ones.
↓ in 1D the "ball" is an interval of half-width r; it must reach back to the data, so r grows with the distance from the data
V=2r,r=x−2.21≈∣x∣ for large ∣x∣
here r=6−2.21=3.79, V=7.58 (2.21: the 5th sample from the right)
↓ into K/(NV): far out, the estimate falls only like 1/∣x∣
p^(x)≈2N∣x∣K
At x=6: p^=0.016, true p=0.00005: about 308× too high. A Gaussian tail falls like e−x2/2.
↓ total area of the right tail, from a to b
∫ab2NxKdx=2NKlnabb→∞∞
TL;DR: k-NN can never say "nothing here": it always stretches until it finds K samples, so the tails never die out and the total area is infinite. Parzen: each bump has area n1, total exactly 1.
Part IV
Parzen windows
A window around x
The fixed circle from before, in 1D: a window of width h centred at x. Five samples, h=1.4.
At x=0.6: how many samples fall into the window?
K=2
↓ K/(NV) with V=h
p^(x)=nhK
p^(0.6)=5⋅1.42=0.29
Seen from one sample xi: it adds nh1 to every x within h/2 of it: a box of width h, height nh1, so area n1.
Every sample adds its box: n⋅n1 = total area 1, and p^≥0: a proper probability density.
↓ the estimate at x = the boxes that cover x; [⋅] is 1 if true, else 0
p^(x)=n1i=1∑nh1[∣x−xi∣<h/2]
Smooth bumps instead of boxes
With boxes a sample counts fully or not at all, so p^ jumps. Let its weight fade with the distance instead.
boxes (before)
bumps (now)
one sample xi adds
nh1[∣x−xi∣<2h]
nh1φ(hx−xi)
h is the
width of the box
std. deviation
area of one
1/n
1/n
all n samples
staircase, area 1
smooth, area 1
Every sample gets its bump; φ(u)=2π1e−u2/2 is the standard normal density, and h1φ(hu)=Kh(u), a normal with std. h.
p^h(x)=n1i=1∑nKh(x−xi)
Parzen windows: the general recipe
Given samples x1,…,xn, a kernelK and a bandwidthh>0:
p^h(x)=n1i=1∑nh1K(hx−xi)
K sets the shape of one bump, h its width; the h1 keeps its area unchanged when we stretch it. In D dimensions: hD1.
Box: K(u)=[∣u∣<21]. Gaussian: K(u)=φ(u), as in the assignment. More shapes in the Optional section.
What must K look like?
K(u)≥0: no negative density
∫K(u)du=1: total area 1
symmetric, K(u)=K(−u)
The first two are needed for a density; the third is a sensible choice.
A good estimate puts high density where new samples actually land. Two estimates, three held-out samples:
x1′
x2′
x3′
product
sum of logs
p^A
0.30
0.25
0.20
0.015
−4.2
p^B
0.50
0.01
0.40
0.002
−6.2
B is higher at two samples, but nearly misses x2′: the product punishes that. A wins.
↓ samples are independent, so the probability of seeing all of them is a product: the likelihood
x∈Xtst∏p^(x)
↓ take the log: products of many small numbers underflow (100 samples at 0.05: 10−130); the log turns the product into a sum and keeps the same order, so the same h wins
log∏p^(x)=x∈Xtst∑logp^(x)
Higher log-likelihood on held-out samples = better estimate. A sample where p^≈0 gives logp^→−∞: a strong penalty for spikes and gaps.
Upload to BRUTE (zip, no folders): parzen.py, parzen.ipynb, parzen_estimates.png, optimal_h_classA.png, optimal_h_classC.png, parzen_classif.png. Bonus: 2D measurements (Optional section).
Optional
Extra material
Other kernels
Any symmetric bump with area 1 works: p^h(x)=n1∑iKh(x−xi) with Kh(u)=h1K(hu).
The box gives the window count from before (steps); the Gaussian is smooth everywhere.
"Epanechnikov is optimal": with the best h for each kernel, it gives the smallest error (the AMISE from the rules-of-thumb slide) of all non-negative kernels. The others are close: for the same error the Gaussian needs only about 5% more samples, the box about 7%.
So in practice h matters far more than the shape of the kernel.
One h is a compromise: too wide where samples are crowded, too narrow where they are sparse. Idea: every sample xi gets its own width hi.
h: one global width, as before (Silverman or cross-validation).
Pilotp~: ordinary Parzen with that h. p~(xi) says how crowded it is around xi.
g: a typical pilot value (geometric mean of all p~(xi)). Ratio p~(xi)/g: >1 crowded, <1 sparse.
hi=h(gp~(xi))−1/2
4× more crowded than typical → half the width; 4× sparser → twice the width (Abramson's square-root law)
p^(x)=n1∑iKhi(x−xi): the same recipe; every bump still has area n1, so p^ is still a density.
Adaptive bandwidth on a skewed sample
60 samples from a skewed density: a sharp peak near 1 and a long thin tail to the right.
Fixed h (from CV): a compromise. The peak comes out too low, and lonely tail samples still make small bumps (around 4.3).
Adaptive hi: narrow bumps at the peak, so it is closer to the truth; wide bumps in the tail, so it is smooth. Grey bars: the widths hi of the far samples.
Used in:t-SNE (each point's Gaussian width σi is set by the perplexity, i.e. by its neighbours) · particle physics, Cranmer 2001, in ROOT as RooKeysPdf · Abramson 1982
The curse of dimensionality, numerically
Standard Gaussian in D dimensions. Window: a cube of side 1 around the peak. How many samples land in it?
D
probability inside
n for K≈20 inside
1
0.38
52
2
0.15
136
3
0.056
356
5
0.0082
2 400
10
0.000068
295 000
20
4.6·10⁻⁹
4.4·10⁹
↓ the coordinates are independent; each one is inside [−21,21] with probability 0.383
P(inside)=0.383D,n≈0.383D20
A 28×28 image has D=784. Parzen (and histograms) work in 1–3 dimensions; beyond that we need models that assume structure.
x = (left half) − (right half) intensity y = (top half) − (bottom half) intensity
↓ a round 2D Gaussian bump of width h on every sample, covariance h2I
Kh(u)=2πh21e−∥u∥2/(2h2)
↓ the same average as in 1D
p^h(x)=n1i=1∑nKh(x−xi)
Watch the scales: one h for both axes only makes sense if x and y have similar ranges. Rescale them first (e.g. divide each by its standard deviation), or use a separate h per axis.
In D dimensions V∼hD: to keep K samples in the window we need far more data. Parzen works well only in low dimensions.
Bonus task: show the estimated p^(x∣k) for both letters, e.g. as contour plots.
Parzen regression: to predict y at a new x, average the training outputs yi, weighting each by how close its xi is to x.
y^(x)=i∑wiyi,wi=∑jKh(x−xj)Kh(x−xi)
The weights are ≥0 and sum to 1: close samples count more.
Attention in a transformer does the same: each token's output is a weighted average of the other tokens' values, with larger weights for tokens that are more "similar" to it.
The difference: "similar" is not a fixed kernel with a bandwidth h, but learned during training.
2014: the original GAN paper could not compute the likelihood of its samples. So it fitted a Parzen estimate to generated images, chose h by validation, and reported the log-likelihood of the test images.
2016:Theis, van den Oord, Bethge showed that in image dimensions this number is far from the true log-likelihood even with very many samples, and can rank models in the wrong order.
Why: images have hundreds of dimensions. The curse of dimensionality from the Optional section: no sample lands near a test image, so p^ measures distance to the nearest sample, not probability.
The metric was dropped. Lesson: a density estimate is only as good as the dimension it lives in.
Further reading
Bishop: Pattern Recognition and Machine Learning, §2.5: histogram, Parzen, k-NN, with the same K/(NV) derivation as today
Silverman: Density Estimation for Statistics and Data Analysis (1986): the classic on bandwidth choice