Fit the hyperparameters of a GP with the squared-exponential kernel k(x,x′)=σf2exp(−∥x−x′∥2/(2ℓ2)) and Gaussian noise σy by empirical Bayes.
Work in log space, θ=(logℓ,logσf,logσy), so the parameters stay positive. With Kσ=K+σy2I (no jitter) and α=Kσ−1y:
- NLL: −logp(y∣X,θ)=21y⊤α+21log∣Kσ∣+2Nlog2π.
- Gradient: ∂θj∂logp=21tr((αα⊤−Kσ−1)∂θj∂Kσ); you need ∂Kσ/∂θj for each of the three log parameters (chain rule through the log).
Implement:
neg_log_marglik_and_grad(theta, X, y) returning (nll, grad), grad the gradient of the NLL (shape (3,)). X is (N, D) or 1-D.
fit_hyperparameters(X, y, inits, n_steps=200, lr=0.05): from each initial θ in inits, run n_steps steps of plain gradient descent θ←θ−lr⋅∇NLL. Return (best_theta, best_nll, final_nlls): the final θ and NLL of the run with the lowest final NLL (first run on ties) and the list of every run's final NLL.