Implement a Bayesian optimization loop with a Gaussian process and expected improvement

Quick Overview

Implement a Gaussian process posterior, the expected improvement acquisition function and a Bayesian optimization loop that minimizes an objective over a finite candidate set. It tests numerically stable linear algebra, careful handling of zero variance and a seeded, deterministic search loop.

Implement a Bayesian optimization loop with a Gaussian process and expected improvement

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement `gp_posterior`, `expected_improvement` (for minimization) and `bayes_opt`, which minimizes `objective` over a finite `candidates` array. It evaluates `n_init` random points, then runs `n_iter` select/evaluate/refit steps. The signatures are: ```python def gp_posterior(X_train, y_train, X_test, length_scale=1.0, signal_var=1.0, noise=1e-6): ... def expected_improvement(mu, sigma, best, xi=0.0): ... def bayes_opt(objective, candidates, n_init, n_iter, seed, length_scale=1.0, signal_var=1.0, noise=1e-6, xi=0.0): ... ``` Requirements: - `gp_posterior` returns `(mean, std)` arrays of length `len(X_test)`. 1-D inputs are treated as single-feature columns. - `expected_improvement` returns `0` wherever `sigma <= 0`. - The initial design is `np.random.default_rng(seed).choice(n, size=n_init, replace=False)`, evaluated in that order. - Each iteration fits on all evaluated points, scores the unevaluated candidates (in ascending index order) with `best = min(y)`, and picks the first `argmax` of EI. A candidate is never evaluated twice. - Return `{"indices": list[int], "y": np.ndarray, "best_index": int, "best_y": float}`. Raise `ValueError` if `n_init < 1`, `n_iter < 0` or `n_init + n_iter > len(candidates)`. Reference formulas: ```text k(a, b) = signal_var * exp(-0.5 * ||a - b||^2 / length_scale^2) m = mean(y_train) # constant prior mean K = k(X, X) + noise * I mean = m + k(X, X*)^T K^-1 (y - m) var = max(signal_var - diag(k(X, X*)^T K^-1 k(X, X*)), 0); std = sqrt(var) imp = best - mu - xi; z = imp / sigma EI = imp * Phi(z) + sigma * phi(z) # standard normal cdf / pdf ``` ```hint Avoid the explicit inverse Both the posterior mean and the variance need products with `K^-1`. Think about which factorization of a symmetric positive definite matrix gives you both terms without ever forming the inverse. ``` ```hint Zero variance EI divides by `sigma`. Decide which entries take part in that division before you compute it, so the zero-variance entries never produce a `NaN` or a warning. ``` ```hint Determinism Every ordering and tie in the loop is fixed by the spec. Check that the order of the remaining candidates and the way you take the argmax match it, so two runs with the same seed pick the same points. ``` ### Clarifying Questions to Ask - For a 1-D `candidates` array, does `objective` receive a scalar or a length-1 row? - Should `y` be standardized before fitting, given that `signal_var` is fixed, or must the formulas be used exactly as written? - Is SciPy available for the Cholesky factorization and the normal CDF and PDF? ### What a Strong Answer Covers - The posterior mean and standard deviation from the given formulas, computed with a stable solve and with the variance clipped at zero. - Expected improvement for minimization, including the zero-`sigma` case and the role of `xi`. - The loop: the seeded initial design in the stated order, refitting on all data, scoring only unevaluated candidates, deterministic tie-breaking and input validation. - The return dict with the right types and the first-occurring minimum. - The cost per iteration in terms of observations and candidates, and the numerical failure modes. ### Follow-up Questions - How would you set `length_scale` and `signal_var` instead of fixing them? - How does this change for a continuous search space? - How would you propose a batch of `q` points for parallel evaluation?

Overview: Implement a Gaussian process posterior, the expected improvement acquisition function and a Bayesian optimization loop that minimizes an objective over a finite candidate set. It tests numerically stable linear algebra, careful handling of zero variance and a seeded, deterministic search loop.

General logo
General
Nov 25, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement gp_posterior, expected_improvement (for minimization) and bayes_opt, which minimizes objective over a finite candidates array. It evaluates n_init random points, then runs n_iter select/evaluate/refit steps.

The signatures are:

def gp_posterior(X_train, y_train, X_test, length_scale=1.0, signal_var=1.0, noise=1e-6): ...
def expected_improvement(mu, sigma, best, xi=0.0): ...
def bayes_opt(objective, candidates, n_init, n_iter, seed, length_scale=1.0,
              signal_var=1.0, noise=1e-6, xi=0.0): ...

Requirements:

  • gp_posterior returns (mean, std) arrays of length len(X_test) . 1-D inputs are treated as single-feature columns.
  • expected_improvement returns 0 wherever sigma <= 0 .
  • The initial design is np.random.default_rng(seed).choice(n, size=n_init, replace=False) , evaluated in that order.
  • Each iteration fits on all evaluated points, scores the unevaluated candidates (in ascending index order) with best = min(y) , and picks the first argmax of EI. A candidate is never evaluated twice.
  • Return {"indices": list[int], "y": np.ndarray, "best_index": int, "best_y": float} . Raise ValueError if n_init < 1 , n_iter < 0 or n_init + n_iter > len(candidates) .

Reference formulas:

k(a, b) = signal_var * exp(-0.5 * ||a - b||^2 / length_scale^2)
m = mean(y_train)                       # constant prior mean
K = k(X, X) + noise * I
mean = m + k(X, X*)^T K^-1 (y - m)
var  = max(signal_var - diag(k(X, X*)^T K^-1 k(X, X*)), 0);  std = sqrt(var)

imp = best - mu - xi;  z = imp / sigma
EI  = imp * Phi(z) + sigma * phi(z)     # standard normal cdf / pdf

Clarifying Questions to Ask Guidance

  • For a 1-D candidates array, does objective receive a scalar or a length-1 row?
  • Should y be standardized before fitting, given that signal_var is fixed, or must the formulas be used exactly as written?
  • Is SciPy available for the Cholesky factorization and the normal CDF and PDF?

What a Strong Answer Covers Guidance

  • The posterior mean and standard deviation from the given formulas, computed with a stable solve and with the variance clipped at zero.
  • Expected improvement for minimization, including the zero- sigma case and the role of xi .
  • The loop: the seeded initial design in the stated order, refitting on all data, scoring only unevaluated candidates, deterministic tie-breaking and input validation.
  • The return dict with the right types and the first-occurring minimum.
  • The cost per iteration in terms of observations and candidates, and the numerical failure modes.

Follow-up Questions Guidance

  • How would you set length_scale and signal_var instead of fixing them?
  • How does this change for a continuous search space?
  • How would you propose a batch of q points for parallel evaluation?