Simulated Annealing Hyperparameter Search

Quick Overview

Implement simulated annealing to minimize an objective over a discrete, ordered hyperparameter space with a seeded NumPy generator. It tests neighbour moves with edge reflection, the Metropolis acceptance rule under geometric cooling, reproducible draw order, and tracking the best config apart from the current one.

Simulated Annealing Hyperparameter Search

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `simulated_annealing_search(objective, space, initial, n_iter, seed=0, t0=1.0, cooling=0.95)` to minimise `objective(config) -> float` over a discrete ordered `space` (a dict mapping each name to a list of values), starting from `initial`. Evaluate `initial` once, then run `n_iter` proposal steps. Requirements: - Use `rng = np.random.default_rng(seed)`. Each step draws, in order: `j = rng.integers(len(names))`, `rng.integers(2)` (1 means step `+1`, 0 means `-1`), `u = rng.random()`. Names follow `space` key order. - Move parameter `j`'s index by the step. If out of range, reflect (use `-step`). If still out of range, keep the index. - At step `k` (0-based), `T = t0 * cooling**k`, `delta = score - current_score`. Accept if `delta <= 0`, reject if `T <= 0`, else accept iff `u < exp(-delta / T)`. - Track the best over initial and all proposals (accepted or not). Only a strictly lower score replaces it. - Return a dict with keys `best_config`, `best_score` (float), `proposed_configs` (list of dicts), `proposed_scores` (float ndarray), `accepted` (bool ndarray). Example: ```python space = {"x": [1, 2]} res = simulated_annealing_search(lambda c: float(c["x"]), space, {"x": 1}, 6, seed=0, t0=1e12, cooling=1.0) [c["x"] for c in res["proposed_configs"]] # [2, 1, 2, 1, 2, 1] (boundary reflects inward) res["accepted"].tolist() # [True, True, True, True, True, True] res["best_config"], res["best_score"] # ({'x': 1}, 1.0) ``` With one parameter of two values, every move lands on the other value: a step off either edge reflects back inward. The huge temperature makes the uphill moves pass the acceptance test, and the best stays at the initial config because the later score of 1.0 only ties it. ```hint Represent positions as indices Store each parameter's position as an index into its value list. Moves and boundary checks then become integer arithmetic. ``` ```hint Current versus best The state the walk is at and the best config seen so far are two separate variables. Check which one a rejected proposal can still change. ``` ### Constraints & Assumptions - Every `initial[name]` appears in `space[name]`. Each value list is non-empty. - Objective values are finite. `n_iter` is at least 1. ### What a Strong Answer Covers - An index-space representation of the configuration and the reflect-then-stay rule at the edges. - Exactly three random draws per step in the stated order, including `u` on steps that improve. - The Metropolis acceptance rule with the geometric temperature schedule, including the `T <= 0` case. - Separate tracking of the current state and the best-so-far, with strict improvement and rejected proposals counted. - The output types (float and bool ndarrays) and the time and space complexity. ### Follow-up Questions - How would you pick `t0` and `cooling` when you do not know the typical size of `delta` in advance? - How would you extend the search to continuous or log-scaled parameters? - When the objective is a noisy validation loss, how does the noise affect the acceptance rule and the reported best? - How would you add restarts or reheating when the walk stops making progress?

Overview: Implement simulated annealing to minimize an objective over a discrete, ordered hyperparameter space with a seeded NumPy generator. It tests neighbour moves with edge reflection, the Metropolis acceptance rule under geometric cooling, reproducible draw order, and tracking the best config apart from the current one.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement simulated_annealing_search(objective, space, initial, n_iter, seed=0, t0=1.0, cooling=0.95) to minimise objective(config) -> float over a discrete ordered space (a dict mapping each name to a list of values), starting from initial. Evaluate initial once, then run n_iter proposal steps.

Requirements:

  • Use rng = np.random.default_rng(seed) . Each step draws, in order: j = rng.integers(len(names)) , rng.integers(2) (1 means step +1 , 0 means -1 ), u = rng.random() . Names follow space key order.
  • Move parameter j 's index by the step. If out of range, reflect (use -step ). If still out of range, keep the index.
  • At step k (0-based), T = t0 * cooling**k , delta = score - current_score . Accept if delta <= 0 , reject if T <= 0 , else accept iff u < exp(-delta / T) .
  • Track the best over initial and all proposals (accepted or not). Only a strictly lower score replaces it.
  • Return a dict with keys best_config , best_score (float), proposed_configs (list of dicts), proposed_scores (float ndarray), accepted (bool ndarray).

Example:

space = {"x": [1, 2]}
res = simulated_annealing_search(lambda c: float(c["x"]), space, {"x": 1},
                                 6, seed=0, t0=1e12, cooling=1.0)
[c["x"] for c in res["proposed_configs"]]  # [2, 1, 2, 1, 2, 1] (boundary reflects inward)
res["accepted"].tolist()                   # [True, True, True, True, True, True]
res["best_config"], res["best_score"]      # ({'x': 1}, 1.0)

With one parameter of two values, every move lands on the other value: a step off either edge reflects back inward. The huge temperature makes the uphill moves pass the acceptance test, and the best stays at the initial config because the later score of 1.0 only ties it.

Constraints & Assumptions

  • Every initial[name] appears in space[name] . Each value list is non-empty.
  • Objective values are finite. n_iter is at least 1.

What a Strong Answer Covers Guidance

  • An index-space representation of the configuration and the reflect-then-stay rule at the edges.
  • Exactly three random draws per step in the stated order, including u on steps that improve.
  • The Metropolis acceptance rule with the geometric temperature schedule, including the T <= 0 case.
  • Separate tracking of the current state and the best-so-far, with strict improvement and rejected proposals counted.
  • The output types (float and bool ndarrays) and the time and space complexity.

Follow-up Questions Guidance

  • How would you pick t0 and cooling when you do not know the typical size of delta in advance?
  • How would you extend the search to continuous or log-scaled parameters?
  • When the objective is a noisy validation loss, how does the noise affect the acceptance rule and the reported best?
  • How would you add restarts or reheating when the walk stops making progress?