# How Do You Tune Hyperparameters?

> How to tune hyperparameters, grid vs random vs smarter search, and how to keep the score honest, explained simply for your AI interview.

**In short:** Hyperparameters are settings you choose before training, like the learning rate or tree depth. You tune them by trying candidate settings, scoring each with cross-validation on training data, and keeping the best, then checking the final model once on held-out data.

AI and LLM interview question Q436, Classic ML and deep-learning basics. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-tune-hyperparameters

## Say it in 30 seconds

Hyperparameters are the settings I choose before training, like learning rate and tree depth. I tune them by trying candidate settings, scoring each one with cross-validation on the training data, and keeping the best. Random search often does better than a full grid for the same budget. Then I check the final model once on data it never saw during tuning, so the score stays honest.

## Say it in 2 minutes

A model learns its parameters from data, but some settings I pick myself before training starts. Those are hyperparameters: the learning rate, how deep a decision tree may grow, how many trees a forest has. Get them wrong and the same model can look great or useless, so tuning is part of almost every real project.

There are three common ways to search. Grid search tries every combination from the lists I write down. It is thorough, but every extra setting multiplies the number of runs. Random search samples a fixed number of settings from ranges, and Bergstra and Bengio found that for the same budget it did better than a grid. Smarter methods like Bayesian optimisation use past scores to choose what to try next.

The score also has to be honest. I tune with cross-validation on the training part, so one lucky split doesn't decide the winner. Then I test the chosen settings once, on data that tuning never touched. If I tune against the test set, I've quietly trained on it, and the score is too kind.

In a real project I write the budget first: how many runs, how long each takes, and who pays for the compute. Then I pick the search that fits it, and I say what I'd check if the test score disappointed.

## What are hyperparameters, in plain words?

A model has two kinds of numbers. Parameters are what training learns from the data, like the weights in a neural network. Hyperparameters are the settings you pick before training starts, such as the learning rate, how deep a decision tree may grow, or how many trees a forest has.

scikit-learn, the Python library many teams use for classic machine learning, puts it this way: "Hyper-parameters are parameters that are not directly learnt within estimators."

Think of a triage nurse who sets the rules for how fast to flag a patient before the shift starts. The rules learn nothing from the patients. They still shape every decision. A bank's loan-default model works the same way: the learning rate and tree depth shape how it learns, while the bank's past loans decide what it learns.

- **Hyperparameter:** A setting you choose before training, like learning rate or tree depth. Training doesn't learn it.
- **Search space:** The ranges or lists of values you allow for each setting.
- **Cross-validation:** Training and scoring on several splits of the training data, then averaging, so one lucky split can't decide.
- **Held-out test set:** Data kept back from all tuning and used once at the end, for the final honest score.

## What are the main ways to search?

Three approaches cover most real work. Each one trades thoroughness against cost.

- **Grid search: Try every combination.** Thorough and simple, but the runs multiply with each new setting. Three settings with five values each already means 125 combinations.
- **Random search: Sample a fixed budget.** Picks settings at random from the ranges you allow. You choose how many runs you can afford, whatever the number of settings.
- **Smarter search: Learn from past runs.** Bayesian optimisation and successive halving use earlier scores to choose the next settings or drop weak ones early.

> "randomly chosen trials are more efficient for hyper-parameter optimization than trials on a grid." (Bergstra and Bengio, JMLR 2012)
>
> "Unfortunately, this tuning is often a "black art" requiring expert experience, rules of thumb, or sometimes brute-force search." (Snoek, Larochelle and Adams, NeurIPS 2012)

The Bergstra and Bengio paper starts by noting that grid and manual search are the most widely used strategies. It then compares them with random trials on the same budget. Why does random win? Imagine only one setting really matters. A grid spends most of its runs nudging the others. Random picks give the important setting more distinct values for the same number of runs.

*Diagram, Grid or random, same budget: Both methods get the same number of runs. The grid repeats the same few values for each setting, so many of those runs add little. Random picks spread their values, so the setting that matters gets more different tries.*
1. Many grid runs test small changes to a setting that barely matters.
2. Random picks spread out their values, so the key setting gets more distinct tries.

Smarter methods often spend fewer runs. scikit-learn's successive halving starts many settings on a small amount of data, and only the strong ones get more. It calls the process "like a tournament among candidate parameter combinations." Its halving searches "can be much faster at finding a good parameter combination."

Bayesian optimisation is different. It builds a rough model of which settings look promising, then tries the most promising one next. Snoek and colleagues framed tuning this way in 2012: "we consider this problem through the framework of Bayesian optimization".

> **Tip:** Asked what to use first? Say random search with a clear budget, then a finer search only in the range that looked good.

## How do you keep the score honest?

Tuning picks the best of many tries, so the winning score looks a little better than it really is. Two habits keep it honest: a split kept back from tuning, and cross-validation inside the training data.

*Diagram, The tuning loop: Pick a setting, train and score it with cross-validation, and repeat. Keep the best, then test it once on data that tuning never touched. Every loop uses only the training part.*
1. The search hands one setting to the training step.
2. The score goes back, and the search picks the next setting.
3. Each score is compared with the best one so far.
4. Only the winner is checked, once, on data it never saw.

1. **Split off a test set first:** Put some data aside before any tuning. scikit-learn calls the tuning data a "development set" and the data for the final score an "evaluation set".
2. **Score settings with cross-validation:** Split the training part into folds, train on all but one, score on the one left out, and rotate. The average decides between settings.
3. **Test once, at the end:** Run the chosen settings on the held-out data one time. If the result disappoints, don't go back and retune on it, or it stops being a test.

scikit-learn's guide says that evaluating the result must use "held-out samples that were not seen during the grid search process". Tune on the test data and the test data quietly becomes part of training, so the final score comes out too kind.

### How would you plan a tuning run for a fraud model?

A bank wants a card fraud model, and three settings need tuning: learning rate, tree depth and number of trees. Each setting gets 5-fold cross-validation, which means five train-and-score rounds. One training run takes about 4 minutes on the bank's data, so the budget is the real limit, not the code.

Here is the budget in plain Python, with made-up ranges:

```python
# A made-up fraud model's tuning plan. Each fit takes 4 minutes, so the budget is the real limit.
from itertools import product

LEARNING_RATES = [0.01, 0.03, 0.1, 0.3]
MAX_DEPTHS = [3, 5, 7, 9]
TREE_COUNTS = [100, 300, 600]
FOLDS = 5
MINUTES_PER_FIT = 4

settings = list(product(LEARNING_RATES, MAX_DEPTHS, TREE_COUNTS))
grid_fits = len(settings) * FOLDS
print(f"Grid search: {len(settings)} settings, {grid_fits} fits, {grid_fits * MINUTES_PER_FIT / 60:.0f} hours")

BUDGET = 20
random_fits = BUDGET * FOLDS
print(f"Random search: {BUDGET} settings, {random_fits} fits, {random_fits * MINUTES_PER_FIT / 60:.1f} hours")
```

Output:

```text
Grid search: 48 settings, 240 fits, 16 hours
Random search: 20 settings, 100 fits, 6.7 hours
```

The full grid tries 48 settings. That is 240 training runs, about 16 hours of compute. A random budget of 20 settings is 100 runs, about 6.7 hours, and still tries many different values for each setting. The team agrees the budget with the people who pay for the compute before the first run. When the search ends, the chosen model is tested once on data kept back from tuning.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: settings you choose before training, not learned from the data.
- [ ] Grid, random and smarter search, and why random often wins on the same budget.
- [ ] Cross-validation on training data, with a test set kept back for one final check.
- [ ] The budget: how many runs, and what each one costs.
- [ ] Honest scoring: no tuning against the test set.
- [ ] When to stop: a fixed budget, not endless tries.

**Common traps**

- Trap: "I just tried everything until the score was best." Better: That costs the most. Give the search a budget and say what each run costs.
- Trap: "I picked the settings with the test score." Better: That tunes on the data you test with. Tune on training folds, then test once.
- Trap: "Random search is always better." Better: In Bergstra and Bengio's experiments it did better for the same budget. Compare the methods on your own problem.

## Can you spot the leak?

**Spot the leak:** A team's tuning script runs in a loop. Which line uses the test set to choose a setting?

A. search = GridSearchCV(model, grid, cv=5).fit(X_train, y_train)
B. best = search.best_params_
C. for lr in [0.01, 0.1]: test_score(X_test, y_test, lr)  # picks lr by test score
D. final = model.set_params(**best).fit(X_train, y_train)

**Answer:** C. The loop picks the learning rate by its test score, so the test set helped tune the model and its score is too kind. Tune with cross-validation on training data, and score the test set once at the end.

**Quick check:** You tried 200 settings, and the best one scored 94% on the test set, which you also used to choose it. What is the safest claim?

A. The 94% is reliable, because 200 settings were tried
B. The 94% is too optimistic, because the test set helped choose the settings
C. The 94% is fine, because the test set was never used for training
D. The model will score 94% for every new customer

**Answer:** B. Choosing settings by test score means the test set shaped the result, so 94% is too kind. Check the model on fresh data that tuning never saw.

## Can you answer these from memory?

**Flash cards**

- **What is a hyperparameter?** A setting you choose before training, like learning rate or tree depth. Training doesn't learn it.
- **Grid vs random search?** Grid tries every combination. Random tries a fixed budget of settings, picked from the ranges.
- **Why is random often better?** For the same budget it tends to try more values of the settings that matter most.
- **What does cross-validation do?** Scores a setting on several splits of the training data, so one lucky split can't decide.
- **Why keep a test set?** It gives an honest score. Tuning on it makes that score too kind.
- **What is successive halving?** A tournament: weak settings drop out early, and the survivors get more resources.

## Likely follow-up questions

- Q423 What is cross-validation? https://designervenkat.online/interview/ai/what-is-cross-validation
- Q424 What is data leakage? https://designervenkat.online/interview/ai/what-is-data-leakage
- Q425 How do you handle class imbalance? https://designervenkat.online/interview/ai/how-do-you-handle-class-imbalance
- Q429 What is early stopping? https://designervenkat.online/interview/ai/what-is-early-stopping
- Q439 Bagging vs boosting? https://designervenkat.online/interview/ai/bagging-vs-boosting

## Learn it in depth

- [Tuning a model's settings](https://designervenkat.online/learn/machine-learning/hyperparameter-tuning)
- [K-Fold Cross Validation: every slice counts](https://designervenkat.online/learn/machine-learning/k-fold-cross-validation)
