Kernel Density Estimation and Bandwidth Selection

easy
Unit 7 · Interpretability I0/5 to milestone

A kernel density estimate smooths a sample into a density by placing a Gaussian bump of width h (the bandwidth) on every point:

f^(x)=1nh∑iϕ ⁣(x−xih)\hat f(x) = \frac{1}{n h}\sum_i \phi\!\left(\frac{x - x_i}{h}\right)

Implement for 1-D data:

  • kde(sample, x, h): the density at each point of x
  • silverman(sample): Silverman's rule of thumb, 0.9 * min(std, IQR / 1.34) * n ** (-1/5) (population std; IQR from np.percentile)
  • loo_log_likelihood(sample, h): the leave-one-out log-likelihood, ∑ilog⁡f^−i(xi)\sum_i \log \hat f_{-i}(x_i), where each point's density is estimated from the other n − 1 points
  • best_bandwidth(sample, grid): the h in grid with the highest leave-one-out log-likelihood (ties: the smallest)
#density-estimation#nonparametric#statistics2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Kernel Density Estimation and Bandwidth Selection · TechGradify