Tuning a model
Last updated
Every model in this stage has settings you choose before training: a tree's depth, a forest's features per split, an SVM's C and γ, boosting's learning rate. Good settings can be the difference between a model that overfits and one that works. This lesson shows which settings matter for each model, how to search for them without wasting time, how to read the curves that say whether more data or a different model would help, and how to report the result honestly.
By the end of this lesson you can
- Tell parameters from hyperparameters, and name the ones that matter for each model
- Search with GridSearchCV and RandomizedSearchCV on log-scaled ranges
- Read validation curves and learning curves, and use early stopping
- Explain why a search’s best score is optimistic, and use nested cross-validation
Parameters and hyperparameters
Two kinds of number go into a model:
- Parameters are learned from the data by
fit: a linear model's weights, a tree's thresholds, an SVM's support vectors and their weights. - Hyperparameters are chosen by you, before
fit: the depth of a tree, in -NN, C and for an SVM, the learning rate for boosting.
C = 10 and = 0.05 were set by hand. From the data, the SVM chose 296 of the 600 digits as support vectors, and learned 9 weights for each, one for each of the other nine classes it's compared against. Tuning means choosing the hyperparameters, and the only honest way is to compare settings on data the model didn't train on: a validation set, or cross-validation (lesson 2.9).
Which settings matter
Every scikit-learn model has many settings, but only a few matter much. A start for each:
| Model | Tune first | Then, maybe |
|---|---|---|
| -NN (2.4) | n_neighbors | weights |
| Ridge, lasso, logistic (3.8, 3.9) | alpha or C, on a log scale | l1_ratio |
| Decision tree (4.4) | max_depth or min_samples_leaf | ccp_alpha |
| Random forest (4.5) | usually nothing: plenty of trees | max_features, min_samples_leaf |
| Gradient boosting (4.6) | learning_rate with early stopping | max_leaf_nodes, min_samples_leaf, l2_regularization |
| SVM (4.7) | C and gamma together, on log scales | the kernel |
| PCA in a pipeline (4.10) | n_components |
Inside a pipeline, a setting is named by its step: svc__C, histgradientboostingregressor__learning_rate. The two underscores separate the step's name from the setting's.
Grid search against random search
Lesson 2.9's GridSearchCV tries every combination in a grid. Six values of C times five of , three folds each, on 600 digits:
30 settings, 90 fits, and the best, C = 10 and = 0.1, scores 98.8%. The heat map shows how the two settings work together. The good region, in yellow, has a diagonal edge: a smaller needs a bigger C. And = 1 is poor whatever C is. About half the grid is dark, so half the fits were spent on settings that were never going to work, while was only ever tried at five values.
Random search draws each try's settings at random from ranges you give. With the same budget of 30 tries, it tests 30 different values of each setting, instead of 6 and 5:
98.8% for the grid, 99.2% for random search, with = 0.13, a value the grid never tried. Bergstra and Bengio showed in 2012 that when only a few settings matter, which is usual, random search finds good values with far fewer tries. Compare them on a made-up score:
The grid tries only 3 different values of γ, each 3 times; random search tries 9. Best found: grid 0.619, random 0.858, against a peak of 0.973.
Notice the ranges: loguniform(0.01, 1000) draws C so that 0.01 to 0.1 is as likely as 100 to 1000. For settings like C, , alpha and the learning rate, what matters is the ratio between values, so search on a log scale. A plain range from 0.01 to 1000 would spend 90% of its tries above 100.
Validation curves and learning curves
Two plots say why a model is falling short.
A validation curve shows training and validation scores as one setting changes. A tree's depth, on the moons:
At depth 1, both scores are low (80.5% validation): underfitting, too simple. At depth 2 to 4, validation peaks near 88.8%. Past that, training keeps rising towards 100% while validation falls: overfitting. It's lesson 2.6's U-shaped curve, measured.
A learning curve shows the same two scores as the training set grows:
An SVM on the digits: from 50 training digits, 88.8% on its own training data but 63.2% on new ones. From 1,400: 99% and 95.3%. The gap is closing, and validation is still rising: more data would help. If instead both curves had flattened out low and close together, more data would be wasted, and the model would need to be more flexible, or the features better (lesson 4.2). A learning curve can save you from collecting data that won't help, or from tuning a model that just needs more data.
Early stopping
For models trained a step at a time, like boosting (and the neural networks of later stages), the number of steps is a hyperparameter you don't have to search. Hold back a validation set, watch its score after each tree, and stop when it hasn't improved for a while:
Allowed up to 1,000 trees, the model stopped after 41: no gain on its 15% validation set for 10 trees in a row, with the best validation accuracy 96.3%. It saved 959 trees of training, and the overfitting they'd have brought (lesson 4.6).
Wrong way: reporting the search’s best score
100 rows of random numbers, and labels that are coin flips: there is nothing to learn. Search 78 settings of -NN by cross-validation:
The best setting scored 58%, better than a coin. But it can't really be: the labels are random. With 78 settings, some will do better than 50% on these particular folds by luck, and the search picks the luckiest. Its best_score_ measures the luck as well as the model, so it's optimistic, and the more settings you try, the more so.
The fix is nested cross-validation: treat the whole search as the model, and cross-validate that. Each outer fold runs a complete search on its training part and scores the winner on its held-out part, which the search never saw:
51%: a coin, which is the truth. In practice the simpler version is the one from lesson 2.9: search with cross-validation on the training set, then score the chosen model once on a test set kept aside from the start. Either way, never report the number the search chose by.
A tuning recipe
- Start with the defaults, and a baseline (lesson 4.14). Many models are close to their best already: a random forest almost always is.
- Tune the one or two settings that matter (step 2), on log scales where it fits, with random search: 20 to 60 tries goes a long way.
- If the best value is at the edge of a range, widen the range and search again.
- Use early stopping for anything trained in steps.
- Read the learning curve: does the model need more data, or a different model or features?
- Score the final choice once, on the test set.
And keep a sense of proportion. Lesson 4.P's house-price project finds that tuning gradient boosting gains nothing measurable over its defaults, while lesson 4.2's location features cut a linear model's error by 0.028. Better data and features usually beat better settings.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- scikit-learn: Tuning the hyper-parameters of an estimator: GridSearchCV, RandomizedSearchCV, and successive halving
- scikit-learn: Validation curves and learning curves: validation_curve and learning_curve
- scikit-learn: Nested versus non-nested cross-validation: why the search’s best score is optimistic
- Varma and Simon, Bias in error estimation when using cross-validation for model selection, BMC Bioinformatics 7, 2006: nested cross-validation, shown on data with no signal