Traditional models · lesson 13 of 16
Parts in this lesson
AGridSearchCV(SVC(), {'C': [...], 'gamma': [...]})2.9: try every combination
BRandomizedSearchCV(SVC(), {'C': loguniform(0.01, 1000)})random combinations, on a log scale
Cvalidation_curve(...), learning_curve(...)scores against a setting, and against data size
Dcross_val_score(search, X, y)nested cross-validation: the search, scored honestly

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, k in k-NN, C and γ for an SVM, the learning rate for boosting.
tuning.ipynb

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:

ModelTune firstThen, maybe
k-NN (2.4)n_neighborsweights
Ridge, lasso, logistic (3.8, 3.9)alpha or C, on a log scalel1_ratio
Decision tree (4.4)max_depth or min_samples_leafccp_alpha
Random forest (4.5)usually nothing: plenty of treesmax_features, min_samples_leaf
Gradient boosting (4.6)learning_rate with early stoppingmax_leaf_nodes, min_samples_leaf, l2_regularization
SVM (4.7)C and gamma together, on log scalesthe 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:

tuning.ipynb

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:

tuning.ipynb

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:

Search grid9 tries each, on a log scale
0.010.111010010001e-41e-31e-21e-11Cγgridbest 0.619randombest 0.858Darker pink: a highervalidation score.Only γ matters much here:the good band runs across.

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:

tuning.ipynb

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:

tuning.ipynb

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:

tuning.ipynb

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 k-NN by cross-validation:

tuning.ipynb

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:

tuning.ipynb

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

  1. Start with the defaults, and a baseline (lesson 4.14). Many models are close to their best already: a random forest almost always is.
  2. 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.
  3. If the best value is at the edge of a range, widen the range and search again.
  4. Use early stopping for anything trained in steps.
  5. Read the learning curve: does the model need more data, or a different model or features?
  6. 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

Which of these is a hyperparameter?
A learning curve shows training and validation scores that have both flattened out, close together, at 70%. What will help?
A grid search over 500 settings reports a best cross-validated accuracy of 93%. What should you report as the model’s accuracy?

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.

All sources for Simple Machine Learning