Kernel regression estimates p(x,y) with a product KDE and reads off the conditional moments. With a Gaussian kernel of bandwidth h on the inputs and a Gaussian of variance σ2 on the outputs, the Nadaraya-Watson mean and the predictive variance are
wn(x)=∑n′Kh(x−xn′)Kh(x−xn),μ(x)=∑nwn(x)yn
V[y∣x,D]=σ2+∑nwn(x)yn2−μ(x)2
where Kh(u)∝exp(−∥u∥2/(2h2)).
Implement:
nw_predict(x_train, y_train, x_query, h, sigma) returning (mean, var), two arrays with one entry per query. Inputs are either 1-D arrays of scalars (x_train shape (N,), x_query shape (m,)) or 2-D arrays of shape (N, D) and (m, D).
- The result must be finite for every query, including queries so far from all training inputs that every kernel value underflows to zero. In that limit the weights concentrate on the nearest training input.
- The returned variance must never be smaller than σ2, and it must stay accurate when all targets share a large common offset (for example values around 108).
loo_cv_bandwidth(x_train, y_train, grid) for 1-D inputs: for each h in grid, predict every yn from the other N−1 points with the Nadaraya-Watson mean and compute the mean squared error. Return (best_h, mses): the h with the smallest error (first one on ties) and the list of errors in grid order.