Implement a grid search runner from scratch with cross-validated ranking and refit

Quick Overview

Build a hyperparameter grid search from scratch: expand a parameter grid in a fixed order, score every candidate on every cross-validation fold, then rank candidates and refit the best one. It tests ordering rules, tie handling, score statistics and matching scikit-learn's conventions.

Implement a grid search runner from scratch with cross-validated ranking and refit

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `build_grid(param_grid)`, which expands a dict (or a list of dicts) of value lists into candidate dicts. Then implement `grid_search(param_grid, evaluate, folds, refit=None)`, which scores every candidate on every `(train_idx, val_idx)` fold via `evaluate(params, train_idx, val_idx)` (higher is better) and returns a results dict. The functions must follow these rules: - Grid order: keys sorted alphabetically, last key varies fastest. A list of grids expands grid by grid, concatenated in order. An empty grid yields `[{}]`. - Call `evaluate` with candidates as the outer loop and folds as the inner loop. - Return the keys `params`, `split_scores` (shape `(n_candidates, n_folds)`), `mean_test_score`, `std_test_score` (population std, `ddof=0`), `rank_test_score`, `best_index`, `best_params`, `best_score` (a float) and `best_estimator`. - Rank = 1 + the number of candidates with a strictly higher mean, so ties share the minimum rank. `best_index` breaks ties toward the lowest index. - If `refit` is given, call it exactly once as `refit(best_params)` and store the result in `best_estimator`; otherwise `best_estimator` is `None`. The results must match scikit-learn's `ParameterGrid` order and `GridSearchCV.cv_results_` for the same folds. Example: ```python folds = [([1, 2], [0]), ([0, 2], [1]), ([0, 1], [2])] evaluate = lambda p, tr, va: p["a"] + va[0] * p["b"] / 10 res = grid_search({"b": [10, 20], "a": [1, 2]}, evaluate, folds) res["params"] # [{'a': 1, 'b': 10}, {'a': 1, 'b': 20}, {'a': 2, 'b': 10}, {'a': 2, 'b': 20}] res["split_scores"] # [[1, 2, 3], [1, 3, 5], [2, 3, 4], [2, 4, 6]] res["mean_test_score"] # [2, 3, 3, 4] res["rank_test_score"] # [4, 2, 2, 1] res["best_index"] # 3; best_score is 4.0 and best_estimator is None ``` ```hint Candidate order Look at which position `itertools.product` advances first, and how that maps onto a sorted list of keys. ``` ```hint Ties Check your ranks and `best_index` against the example, where two candidates tie on a mean of 3. ``` ### What a Strong Answer Covers - Grid expansion that reproduces `ParameterGrid` order, including a list of grids and the empty grid. - The required loop order and a candidates × folds score matrix. - Population standard deviation, min-rank ties and lowest-index selection of the best candidate. - A single `refit` call (or `None`), with parameter dicts copied so callbacks cannot change the stored candidates. - The cost of the search and the edge cases: empty value lists, bare strings as values, NaN scores. ### Follow-up Questions - How would you parallelise the candidate × fold evaluations? - How should the runner handle an `evaluate` call that raises an exception or returns NaN? - Your grid has five hyperparameters with ten values each. How would you keep the search affordable?

Overview: Build a hyperparameter grid search from scratch: expand a parameter grid in a fixed order, score every candidate on every cross-validation fold, then rank candidates and refit the best one. It tests ordering rules, tie handling, score statistics and matching scikit-learn's conventions.

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

Implement build_grid(param_grid), which expands a dict (or a list of dicts) of value lists into candidate dicts. Then implement grid_search(param_grid, evaluate, folds, refit=None), which scores every candidate on every (train_idx, val_idx) fold via evaluate(params, train_idx, val_idx) (higher is better) and returns a results dict.

The functions must follow these rules:

  • Grid order: keys sorted alphabetically, last key varies fastest. A list of grids expands grid by grid, concatenated in order. An empty grid yields [{}] .
  • Call evaluate with candidates as the outer loop and folds as the inner loop.
  • Return the keys params , split_scores (shape (n_candidates, n_folds) ), mean_test_score , std_test_score (population std, ddof=0 ), rank_test_score , best_index , best_params , best_score (a float) and best_estimator .
  • Rank = 1 + the number of candidates with a strictly higher mean, so ties share the minimum rank. best_index breaks ties toward the lowest index.
  • If refit is given, call it exactly once as refit(best_params) and store the result in best_estimator ; otherwise best_estimator is None .

The results must match scikit-learn's ParameterGrid order and GridSearchCV.cv_results_ for the same folds.

Example:

folds = [([1, 2], [0]), ([0, 2], [1]), ([0, 1], [2])]
evaluate = lambda p, tr, va: p["a"] + va[0] * p["b"] / 10
res = grid_search({"b": [10, 20], "a": [1, 2]}, evaluate, folds)

res["params"]          # [{'a': 1, 'b': 10}, {'a': 1, 'b': 20}, {'a': 2, 'b': 10}, {'a': 2, 'b': 20}]
res["split_scores"]    # [[1, 2, 3], [1, 3, 5], [2, 3, 4], [2, 4, 6]]
res["mean_test_score"] # [2, 3, 3, 4]
res["rank_test_score"] # [4, 2, 2, 1]
res["best_index"]      # 3; best_score is 4.0 and best_estimator is None

What a Strong Answer Covers Guidance

  • Grid expansion that reproduces ParameterGrid order, including a list of grids and the empty grid.
  • The required loop order and a candidates × folds score matrix.
  • Population standard deviation, min-rank ties and lowest-index selection of the best candidate.
  • A single refit call (or None ), with parameter dicts copied so callbacks cannot change the stored candidates.
  • The cost of the search and the edge cases: empty value lists, bare strings as values, NaN scores.

Follow-up Questions Guidance

  • How would you parallelise the candidate × fold evaluations?
  • How should the runner handle an evaluate call that raises an exception or returns NaN?
  • Your grid has five hyperparameters with ten values each. How would you keep the search affordable?