Coarse-to-Fine Grid Search with Boundary Handling

Quick Overview

Implement a coarse-to-fine grid search in Python that evaluates a full grid each round, then zooms into a narrower window around the best point while keeping that window inside the original bounds. It tests careful loop logic, tie handling, input validation and how grid search cost grows with the number of hyperparameters.

Coarse-to-Fine Grid Search with Boundary Handling

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `coarse_to_fine_search(objective, bounds, n_points=5, n_rounds=3, shrink=0.5, maximize=False)`. `bounds` maps each parameter name to `(lo, hi)`. Each round evaluates a full grid, then the next round zooms into a narrower window around the best point found so far. Requirements: - Each round's grid is the Cartesian product (`itertools.product` in `bounds` key order) of `np.linspace(lo, hi, n_points)` per parameter. Call `objective(params_dict)` once per point. - Best is the min score (max if `maximize`) across all rounds. Only strict improvements replace it, so ties keep the earliest trial. - Next window: width = current width × `shrink`, centered on the best params. If it crosses an original bound, shift it inside while keeping its width. - Return a dict with `best_params`, `best_score`, `n_evaluations`, `ranges` (one `{name: (lo, hi)}` per round) and `trials` (each `{"round", "params", "score"}`). Parameter values, range endpoints and scores are returned as floats. - Raise `ValueError` for any of: empty `bounds`, an `n_points` that is not an integer or is less than 2, an `n_rounds` that is not an integer or is less than 1, a `shrink` outside the open interval (0, 1), or any `lo >= hi`. Example: ```python res = coarse_to_fine_search(lambda p: (p["x"] - 0.3) ** 2, {"x": (0.0, 1.0)}, n_points=5, n_rounds=3, shrink=0.5) res["ranges"] # [{'x': (0.0, 1.0)}, {'x': (0.0, 0.5)}, {'x': (0.125, 0.375)}] res["best_params"] # {'x': 0.3125} res["n_evaluations"] # 15 ``` ```hint Which best to zoom around Keep a single best over every trial of every round, and think about what a strict comparison does when a grid point from an earlier round shows up again in a later grid. ``` ```hint Sliding the window Since `shrink` is below 1, the new width is always smaller than the original range. What does that tell you about how many original bounds one window can cross at once? ``` ### What a Strong Answer Covers - Builds each round's grid with `np.linspace` per parameter and `itertools.product` in `bounds` key order, calling the objective exactly once per grid point. - Keeps one best across all rounds, with a strict comparison whose direction follows `maximize`, so ties keep the earliest trial. - Derives the next window from the current width and the global best, and slides it back inside the original bounds without changing its width. - Checks every listed invalid input and raises `ValueError` before any objective call. - States the cost in objective calls and how it grows with the number of parameters. ### Follow-up Questions - How would you handle log-scaled parameters like a learning rate? - Why can coarse-to-fine miss the global optimum, and how would you mitigate it? - The grid cost is `n_points ** d` per round. How would this scale to 10 parameters?

Overview: Implement a coarse-to-fine grid search in Python that evaluates a full grid each round, then zooms into a narrower window around the best point while keeping that window inside the original bounds. It tests careful loop logic, tie handling, input validation and how grid search cost grows with the number of hyperparameters.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement coarse_to_fine_search(objective, bounds, n_points=5, n_rounds=3, shrink=0.5, maximize=False). bounds maps each parameter name to (lo, hi). Each round evaluates a full grid, then the next round zooms into a narrower window around the best point found so far.

Requirements:

  • Each round's grid is the Cartesian product ( itertools.product in bounds key order) of np.linspace(lo, hi, n_points) per parameter. Call objective(params_dict) once per point.
  • Best is the min score (max if maximize ) across all rounds. Only strict improvements replace it, so ties keep the earliest trial.
  • Next window: width = current width × shrink , centered on the best params. If it crosses an original bound, shift it inside while keeping its width.
  • Return a dict with best_params , best_score , n_evaluations , ranges (one {name: (lo, hi)} per round) and trials (each {"round", "params", "score"} ). Parameter values, range endpoints and scores are returned as floats.
  • Raise ValueError for any of: empty bounds , an n_points that is not an integer or is less than 2, an n_rounds that is not an integer or is less than 1, a shrink outside the open interval (0, 1), or any lo >= hi .

Example:

res = coarse_to_fine_search(lambda p: (p["x"] - 0.3) ** 2, {"x": (0.0, 1.0)},
                            n_points=5, n_rounds=3, shrink=0.5)
res["ranges"]         # [{'x': (0.0, 1.0)}, {'x': (0.0, 0.5)}, {'x': (0.125, 0.375)}]
res["best_params"]    # {'x': 0.3125}
res["n_evaluations"]  # 15

What a Strong Answer Covers Guidance

  • Builds each round's grid with np.linspace per parameter and itertools.product in bounds key order, calling the objective exactly once per grid point.
  • Keeps one best across all rounds, with a strict comparison whose direction follows maximize , so ties keep the earliest trial.
  • Derives the next window from the current width and the global best, and slides it back inside the original bounds without changing its width.
  • Checks every listed invalid input and raises ValueError before any objective call.
  • States the cost in objective calls and how it grows with the number of parameters.

Follow-up Questions Guidance

  • How would you handle log-scaled parameters like a learning rate?
  • Why can coarse-to-fine miss the global optimum, and how would you mitigate it?
  • The grid cost is n_points ** d per round. How would this scale to 10 parameters?