Pattern Recognition and Machine Learning, Lab 4
neoramic@fel.cvut.cz
16 October 2026
Test now
Bayesian task
We know everything.
Non-Bayesian tasks
Neyman-Pearson, minimax, Wald
Today
We have to estimate the density.
today
Once we have the estimate \(\cph(\cx \mid \ck)\), we plug it into the Bayesian strategy as before.
Each class is estimated separately, from its own samples: we drop \(\ck\) and write \(\cp(\cx)\) instead of \(\cp(\cx \mid \ck)\).
How can we estimate \(\cp(\cx)\) from samples?
Parametric
Known form (e.g. normal), unknown parameters.
MLE, MAP, Bayesian estimation
next lab
Non-parametric
Any shape of the density.
histogram, \(k\)-NN, Parzen windows (kernel density estimation)
today
Mixtures
Combine simple densities.
mixture of Gaussians, neural networks
The true density \(\cp(\cx)\) exists, but we do not know it.
We only get \(N = 12\) samples drawn from it: \(\cx_i \sim \cp(\cx)\).
Bins of width \(w_b\), \(N_b\) samples in bin \(b\). What is the height of the bin?
Compared with the true \(\cp(\cx)\): one bin in a dense region is empty.
The bin contains \(N_b\) of the \(N\) samples: \[ P(\cx \in \text{bin } b) \approx \frac{N_b}{N} \]
Density is probability per unit length: \[ \cph_b = \frac{N_b}{N \cdot w_b} \]
The estimate integrates to one: \[ \sum_b \cph_b \, w_b = \sum_b \frac{N_b}{N} = 1 \]
Here: \(\cph_b = \frac{5}{12 \cdot 1.5} = 0.28\) for the highest bin.
\(\cph_b\) is a height, not a probability: 6 of 12 samples in a bin of width 0.25 give \(\cph_b = 2\)
Pros
Cons
The histogram in \(D\) dimensions: \(K\) samples in a volume \(V\) around \(\cx\).
Fix \(K\), find the smallest \(V\) containing \(K\) samples: \(k\)-nearest neighbours.
Fix \(V\), count the samples \(K\) inside: Parzen windows.
The volume can be a ball or a hypercube: the cube is easy to count in.
Window function: the unit hypercube centred at the origin \[ \varphi(\mathbf{u}) = \begin{cases} 1 & \text{if } |u^j| \le \tfrac{1}{2} \text{ for all } j = 1, \dots, D \\ 0 & \text{otherwise} \end{cases} \]
\(\varphi\big(\frac{\cx - \cx_i}{\ch}\big) = 1\) iff \(\cx_i\) lies in the hypercube of side \(\ch\) around \(\cx\), so \(V = \ch^D\) and \[ K = \sum_{i=1}^{N} \varphi\Big(\frac{\cx - \cx_i}{\ch}\Big) \]
\[ \cph_\ch(\cx) = \frac{K}{N V} = \frac{1}{N} \sum_{i=1}^{N} \underbrace{\frac{1}{\ch^D}\, \varphi\Big(\frac{\cx - \cx_i}{\ch}\Big)}_{K_\ch(\cx, \cx_i)} \]
\(N = 6\) samples \(\cx_i\).
Around every sample a box of width \(\ch\) and height \(\frac{1}{N\ch}\) (area \(\frac{1}{N}\)).
\(\cph_\ch(\cx)\) is their sum: still step-like, but no fixed bins.
A Gaussian kernel around every sample, again with area \(\frac{1}{N}\).
Their sum is a smooth estimate.
\[ K_\text{box}(\cx, \cx_i) = \begin{cases} \frac{1}{\ch} & \text{if } |\cx - \cx_i| \le \frac{\ch}{2} \\ 0 & \text{otherwise} \end{cases} \]
\[ \int K_\text{box}(\cx, \cx_i)\, d\cx = \ch \cdot \frac{1}{\ch} = 1 \]
\[ K_\text{tri}(\cx, \cx_i) = \begin{cases} \frac{1}{\ch} \Big(1 - \frac{|\cx - \cx_i|}{\ch}\Big) & \text{if } |\cx - \cx_i| \le \ch \\ 0 & \text{otherwise} \end{cases} \]
\[ \int K_\text{tri}(\cx, \cx_i)\, d\cx = \frac{1}{2} \cdot 2\ch \cdot \frac{1}{\ch} = 1 \]
\[ K_\text{Gauss}(\cx, \cx_i) = \frac{1}{\sqrt{2\pi}\, \ch}\, e^{-\frac{(\cx - \cx_i)^2}{2\ch^2}} \]
\[ \int K_\text{Gauss}(\cx, \cx_i)\, d\cx = 1 \]
Which properties must \(K_\text{type}(\cx, \cx_i)\) have, so that the estimate \(\cph_\ch(\cx)\) is a density?
For all \(\cx\) and \(\cx_i\): \[ K_\text{type}(\cx, \cx_i) \ge 0, \qquad \int K_\text{type}(\cx, \cx_i)\, d\cx = 1 \]
\[ \int \cph_\ch(\cx)\, d\cx = \int \frac{1}{N} \sum_{i=1}^{N} K_\text{type}(\cx, \cx_i)\, d\cx = \frac{1}{N} \sum_{i=1}^{N} \int K_\text{type}(\cx, \cx_i)\, d\cx = \frac{1}{N} \cdot N = 1 \]
Usually also symmetric: \[ K_\text{type}(\cx, \cx_i) = K_\text{type}(\cx_i, \cx) \]
Assignment: \(K_\text{Gauss}(\cx, \cx_i)\) = norm.pdf(x, loc=x_i, scale=h)
Samples: \(\;-1,\ 0,\ 0,\ 1.5,\ 2 \quad (N = 5)\)
1. Box kernel, \(\ch = 1\): what is \(\cph_\ch(1)\)?
2. The same for \(\ch = 2\).
3. Which \(\ch\) gives a larger estimate far from all samples, e.g. at \(\cx = 5\)?
\(\ch = 1\): window \([0.5, 1.5]\), \(K = 1\) \[ \cph_1(1) = \frac{1}{5 \cdot 1} = 0.2 \]
\(\ch = 2\): window \([0, 2]\), \(K = 4\) \[ \cph_2(1) = \frac{4}{5 \cdot 2} = 0.4 \]
Gaussian kernel, \(\ch = 1\): \[ \cph_1(1) = \frac{1}{5} \sum_{i=1}^{5} \mathcal{N}(1 - \cx_i;\, 0, 1) \approx 0.226 \]
The unit test of parzen in the assignment.
Ball kernel, small \(\ch\) (radius). Put it on every sample and average.
Small \(\ch\): a separate disc around every sample, gaps in between.
Ball kernel, large \(\ch\).
Large \(\ch\): the discs overlap, but the estimate is still step-like.
Gaussian kernel, small \(\ch = \sigma\).
Small \(\ch\): a separate peak around every sample.
Gaussian kernel, large \(\ch = \sigma\).
Large \(\ch\): the kernels merge into a smooth density with two clusters.
kern2d = (x, y) => Math.exp(-(x * x + y * y) / (2 * h2d * h2d)) / (2 * Math.PI * h2d * h2d)
circle2d = d3.range(0, 2 * Math.PI + 0.01, 0.05).map(t => ({x: h2d * Math.cos(t), y: h2d * Math.sin(t)}))
html`<div class="kde-try-title">Gaussian kernel, from above</div>${Plot.plot({
width: 360, height: 360, margin: 0,
x: {domain: [-3, 3], axis: null}, y: {domain: [-3, 3], axis: null},
color: {scheme: "oranges", domain: [0, 1.5]},
marks: [
Plot.raster({fill: kern2d, x1: -3, x2: 3, y1: -3, y2: 3, pixelSize: 3}),
Plot.line(circle2d, {x: "x", y: "y", stroke: "#202729", strokeWidth: 2, strokeDasharray: "6 5"}),
Plot.arrow([{x1: 0, y1: 0, x2: h2d, y2: 0}], {x1: "x1", y1: "y1", x2: "x2", y2: "y2", stroke: "#7A8B00", strokeWidth: 3}),
Plot.text([{x: Math.min(h2d, 2.2) + 0.1, y: 0}], {x: "x", y: "y", text: () => "h = σ", textAnchor: "start", fill: "#7A8B00", fontSize: 22, stroke: "white", strokeWidth: 4, paintOrder: "stroke"}),
Plot.frame({stroke: "#C9D1CD"})
]
})}`profile2d = d3.range(-3, 3.001, 0.02).map(u => ({u, k: kern2d(u, 0)}))
html`<div class="kde-try-title">profile</div>${Plot.plot({
width: 360, height: 200, marginLeft: 10, marginRight: 10, marginTop: 10, marginBottom: 30,
style: {fontSize: "16px"},
x: {domain: [-3, 3], ticks: [-2, 0, 2], label: null}, y: {domain: [0, 1.1], axis: null},
marks: [
Plot.areaY(profile2d, {x: "u", y: "k", fill: "#E08A00", fillOpacity: 0.2}),
Plot.line(profile2d, {x: "u", y: "k", stroke: "#E08A00", strokeWidth: 3}),
Plot.arrow([{x1: 0, x2: h2d, y: kern2d(0, 0) + 0.12}], {x1: "x1", x2: "x2", y1: "y", y2: "y", stroke: "#7A8B00", strokeWidth: 3}),
Plot.text([{x: Math.min(h2d, 2.2) + 0.1, y: kern2d(0, 0) + 0.12}], {x: "x", y: "y", text: () => "h = σ", textAnchor: "start", fill: "#7A8B00", fontSize: 20}),
Plot.ruleY([0])
]
})}`pts2d = [[3.03,4.42],[4.10,2.74],[2.73,2.73],[3.51,3.15],[3.67,1.54],[4.41,3.11],[3.61,3.08],[2.66,3.62],[3.74,3.02],[2.86,3.82],[2.22,1.84],[3.36,2.60],[1.27,2.47],[2.58,2.13],[4.76,6.65],[8.35,6.25],[5.88,7.18],[8.08,6.15],[7.82,8.16],[6.69,5.38],[7.52,6.97],[8.65,4.67],[6.01,5.34],[4.40,6.79],[7.79,5.49],[9.08,7.83]]
dens2d = (x, y) => d3.mean(pts2d, p => Math.exp(-((x - p[0]) ** 2 + (y - p[1]) ** 2) / (2 * h2d * h2d))) / (2 * Math.PI * h2d * h2d)
densPlot2d = withPoints => Plot.plot({
width: 640, height: 640, margin: 0,
x: {domain: [0, 10], axis: null}, y: {domain: [0, 10], axis: null},
color: {scheme: "blues"},
marks: [
Plot.raster({fill: dens2d, x1: 0, x2: 10, y1: 0, y2: 10, pixelSize: 5}),
withPoints ? Plot.dot(pts2d, {x: d => d[0], y: d => d[1], r: 6, fill: "#0F8B8D", stroke: "white"}) : null,
Plot.frame({stroke: "#C9D1CD"})
]
})
html`<div class="kde-try-row">
<div><div class="kde-try-title">samples x<sub>i</sub> and kernels</div>${densPlot2d(true)}</div>
<div><div class="kde-try-title">estimate p̂<sub>h</sub>(x)</div>${densPlot2d(false)}</div>
</div>`samplesTry = [1.31,1.72,1.73,1.79,1.84,2.28,2.36,2.46,2.52,2.61,2.65,2.66,2.89,3.00,3.04,3.08,3.37,4.16,4.42,4.74,4.80,4.86,5.03,5.06,5.28,5.38,5.48,5.54,5.55,5.80,5.95,6.02,6.05,6.10,6.16,6.27,6.42,6.42,7.73,7.90]
gaussPdf = (u, s) => Math.exp(-0.5 * (u / s) ** 2) / (s * Math.sqrt(2 * Math.PI))
kernelTry = ({
Gaussian: u => gaussPdf(u, hTry),
box: u => (Math.abs(u / hTry) <= 0.5 ? 1 / hTry : 0),
triangle: u => Math.max(0, 1 - Math.abs(u / hTry)) / hTry
})[kernTry]
curveTry = d3.range(0, 9.0001, 0.01).map(x => ({
x,
est: d3.mean(samplesTry, xi => kernelTry(x - xi)),
truth: 0.4 * gaussPdf(x - 2.5, 0.6) + 0.6 * gaussPdf(x - 6, 1)
}))
Plot.plot({
width: 1350, height: 760, marginLeft: 70, marginTop: 40, marginBottom: 60,
style: {fontSize: "20px"},
x: {label: "x", domain: [0, 9]},
y: {label: "p̂(x)", domain: [0, 0.8], grid: true, ticks: 8},
marks: [
showTrue ? Plot.line(curveTry, {x: "x", y: "truth", stroke: "#2F7A52", strokeWidth: 3, strokeDasharray: "8 6"}) : null,
Plot.line(curveTry, {x: "x", y: "est", stroke: "#3C7DD9", strokeWidth: 4, clip: true}),
Plot.ruleX(samplesTry, {x: d => d, y1: 0, y2: 0.04, stroke: "#0F8B8D", strokeWidth: 3}),
Plot.ruleY([0])
]
})Can we choose \(\ch\) by maximising the likelihood of the training samples?
No: for \(\ch \to 0\) every sample gets its own spike and \(\cph_\ch(\cx_i) \to \infty\). We need unseen data.
\[ \cX = \bigcup_{j=1}^{J} S_j, \quad S_i \cap S_j = \emptyset, \qquad \cX^j_{\mathrm{tst}} = S_j, \quad \cX^j_{\mathrm{trn}} = \cX \setminus S_j \]
For every split \(j\) and bandwidth \(\ch\): \[ L^j(\ch) = \sum_{\cx \in \cX^j_{\mathrm{tst}}} \log \cph_\ch\big(\cx \,;\, \cX^j_{\mathrm{trn}}\big) \]
\[ L(\ch) = \frac{1}{J} \sum_{j=1}^{J} L^j(\ch) \] \[ \ch^* = \arg\max_{\ch} L(\ch) \]
Why the logarithm?
Part 1: estimate
parzen(x, trn_x, h)
Gaussian kernel, x can be a vector.
Part 2: choose \(\ch\)
compute_Lh(...)
10-fold cross-validation, fminbound gives \(\ch^*\) for each class.
Part 3: classify
classify_bayes_parzen(...)
Bayes with 0/1 loss, priors \(\cp(\cA) = \frac{N_\cA}{N_\cA + N_\cC}\).
parzen is evaluated for all \(\cx\) and all training samples at once: build a \(M \times N\) matrix of kernel values, then average over \(N\).