A Parzen window or kernel density estimator (KDE) places one density kernel on every training point:
p(x∣D)=N1∑n=1NKh(x−xn)
In D dimensions use the product kernel Kh(u)=∏d=1Dh1K(hud) with one bandwidth h, built from these 1-D kernels:
"gaussian": K(u)=(2π)−1/2e−u2/2
"boxcar": K(u)=21I(∣u∣≤1)
"epanechnikov": K(u)=43(1−u2)I(∣u∣≤1)
"tricube": K(u)=8170(1−∣u∣3)3I(∣u∣≤1)
Implement:
kde_logpdf(X_train, X_eval, h, kernel): the log density at each row of X_eval, shape (m,). Inputs are (N, D) arrays or 1-D arrays (then D=1). Where the density is exactly zero return -np.inf, without emitting any warning. The Gaussian case must stay finite for points far from the data (work in the log domain).
silverman_bandwidth(X): Silverman's rule of thumb. For each dimension d, σ^d=1.4826median(∣xd−median(xd)∣) and hd=σ^d(4/(3N))1/5; return the geometric mean h=(∏dhd)1/D as a float.
loo_bandwidth(X, grid): for each h in grid, the Gaussian-kernel leave-one-out log-likelihood
ℓ(h)=N1∑n=1Nlog(N−11∑m=nKh(xn−xm))
Return (best_h, scores): the h with the largest ℓ(h) (first one on ties) and the list of ℓ(h) in grid order.