Fill In the Whole Grid

Hyperparameter OptimizationEasy+10 XP+10

Fill In the Whole Grid

Grid Search tunes hyperparameters by brute force: list a few candidate values for each hyperparameter, train and score a model for every combination, and keep the best one.

Task: write grid_search(grid, score) and return a tuple (best_params, best_score, evaluations).

  • grid is a dict that maps each hyperparameter's name to its list of candidate values, for example {"k": [1, 3, 5], "weighting": ["uniform", "distance"]}. It can hold any number of hyperparameters.
  • score is a function. Call it with one combination, as a dict {name: value} covering every hyperparameter, and it returns that model's validation accuracy. Higher is better.
  • Visit the combinations the way nested loops would: the first hyperparameter in grid is the outermost loop and changes slowest, and the last one is the innermost and changes fastest. Each list is tried in the order given.
  • If two combinations tie, keep the one visited first.

Return best_params as a dict with its keys in grid's order, best_score rounded to 4 decimal places, and evaluations, the number of times you called score.

That last number is the real cost of Grid Search. Every one of those calls stands for a full model trained and validated.

Run the Grid

Evaluate one cell at a time. Every combination gets a turn.

?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?

Examples

grid = {"k": [1, 3, 5, 7, 9], "weighting": ["uniform", "distance"]}
score = lambda p: 0.9 - 0.012 * abs(p["k"] - 5) + (0.015 if p["weighting"] == "distance" else 0.0)
returns ({'k': 5, 'weighting': 'distance'}, 0.915, 10)
grid = {"max_depth": [2, 4, 6, 8], "min_samples_split": [2, 5, 10]}
score = lambda p: 80 - abs(p["max_depth"] - 5) - abs(p["min_samples_split"] - 5)
returns ({'max_depth': 4, 'min_samples_split': 5}, 79, 12)

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run