Random Search With Hold-Out Validation and Refit

Quick Overview

Implement a random hyperparameter search class in NumPy that samples configurations from uniform, log-uniform, integer and categorical specs, scores each on a contiguous hold-out split, and refits the best one on all data. It tests reproducible random sampling, split arithmetic, deterministic tie-breaking and estimator handling.

Random Search With Hold-Out Validation and Refit

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a `RandomSearch` class using NumPy. It samples `n_iter` configurations from `param_distributions` and scores each one on a hold-out split with `score_fn(y_true, y_pred)` (higher is better). It then refits the best configuration on all data. The constructor takes these arguments: ```python class RandomSearch: def __init__(self, estimator_factory, param_distributions, n_iter, score_fn, val_fraction=0.25, seed=0): ... ``` The class must behave as follows: - `sample_params()` creates a fresh `np.random.default_rng(seed)` on every call and returns a list of `n_iter` dicts. Within each config, draw the params in sorted-name order. An unknown distribution kind raises `ValueError`. - `fit(X, y)` uses the last `floor(n * val_fraction)` rows as validation, with no shuffling. An empty train or validation split raises `ValueError`. - Each trial fits `estimator_factory(**params)` on the train rows and appends a dict with the keys `trial_id`, `params`, `score` and `runtime` to `trials_`. Ids are sequential from 0. Scores and runtimes are floats, and the runtime is in seconds and covers fitting plus scoring. - `best_index_` is the first index with the maximum score, and `best_params_` and `best_score_` come from that trial. - `fit` refits a new estimator on the full `X, y` as `best_estimator_` and returns `self`. `predict` delegates to `best_estimator_`. Each value in `param_distributions` is one of these specs: ```python ("uniform", lo, hi) # float(rng.uniform(lo, hi)) ("loguniform", lo, hi) # float(exp(rng.uniform(log(lo), log(hi)))) ("int", lo, hi) # int(rng.integers(lo, hi + 1)) (inclusive) ("choice", values) # values[int(rng.integers(len(values)))] ``` ```hint Where the randomness lives The configs must come out identical every time `sample_params` runs. Consider where the generator is created and in what order its draws are consumed. ``` ```hint Split arithmetic Work through a tiny case, such as 3 rows with `val_fraction=0.25`, before writing the split, and check both sides for emptiness. ``` ### Constraints & Assumptions - Estimators expose `fit(X, y)` and `predict(X)`. - `X` and `y` have the same number of rows `n`, and row order matters because the validation set is the tail. ### What a Strong Answer Covers - How sampling stays identical across calls (where the generator lives, the draw order) and how each distribution kind is drawn, including the integer bounds. - How the validation size is computed and which splits are rejected. - What each trial record holds and what the runtime measures. - How ties between equal scores are resolved and how the final estimator is built. - Edge cases such as unknown kinds, NaN scores and zero iterations. ### Follow-up Questions - How would you replace the single hold-out split with k-fold cross-validation? - How would you parallelize trials while keeping results reproducible? - How could you cut the cost of evaluating poor configurations early?

Overview: Implement a random hyperparameter search class in NumPy that samples configurations from uniform, log-uniform, integer and categorical specs, scores each on a contiguous hold-out split, and refits the best one on all data. It tests reproducible random sampling, split arithmetic, deterministic tie-breaking and estimator handling.

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

Implement a RandomSearch class using NumPy. It samples n_iter configurations from param_distributions and scores each one on a hold-out split with score_fn(y_true, y_pred) (higher is better). It then refits the best configuration on all data.

The constructor takes these arguments:

class RandomSearch:
    def __init__(self, estimator_factory, param_distributions, n_iter, score_fn,
                 val_fraction=0.25, seed=0):
        ...

The class must behave as follows:

  • sample_params() creates a fresh np.random.default_rng(seed) on every call and returns a list of n_iter dicts. Within each config, draw the params in sorted-name order. An unknown distribution kind raises ValueError .
  • fit(X, y) uses the last floor(n * val_fraction) rows as validation, with no shuffling. An empty train or validation split raises ValueError .
  • Each trial fits estimator_factory(**params) on the train rows and appends a dict with the keys trial_id , params , score and runtime to trials_ . Ids are sequential from 0. Scores and runtimes are floats, and the runtime is in seconds and covers fitting plus scoring.
  • best_index_ is the first index with the maximum score, and best_params_ and best_score_ come from that trial.
  • fit refits a new estimator on the full X, y as best_estimator_ and returns self . predict delegates to best_estimator_ .

Each value in param_distributions is one of these specs:

("uniform", lo, hi)      # float(rng.uniform(lo, hi))
("loguniform", lo, hi)   # float(exp(rng.uniform(log(lo), log(hi))))
("int", lo, hi)          # int(rng.integers(lo, hi + 1))  (inclusive)
("choice", values)       # values[int(rng.integers(len(values)))]

Constraints & Assumptions

  • Estimators expose fit(X, y) and predict(X) .
  • X and y have the same number of rows n , and row order matters because the validation set is the tail.

What a Strong Answer Covers Guidance

  • How sampling stays identical across calls (where the generator lives, the draw order) and how each distribution kind is drawn, including the integer bounds.
  • How the validation size is computed and which splits are rejected.
  • What each trial record holds and what the runtime measures.
  • How ties between equal scores are resolved and how the final estimator is built.
  • Edge cases such as unknown kinds, NaN scores and zero iterations.

Follow-up Questions Guidance

  • How would you replace the single hold-out split with k-fold cross-validation?
  • How would you parallelize trials while keeping results reproducible?
  • How could you cut the cost of evaluating poor configurations early?