Sub topic 8
Tuning a scikit-learn model with cross-validation
This chapter assumes you know how to train a scikit-learn model, what a hyperparameter is, and how cross-validation splits data. You also need to know how to write an Optuna objective function and call suggest_* methods. Here you combine these into the usual tuning workflow.
Why cross-validation belongs inside the objective
A single train/validation split gives a noisy score. Optuna's sampler treats each score as the truth, so noise can lead it toward settings that were simply lucky on one split. Cross-validation averages over several splits, which gives a steadier number for the sampler to learn from. The cost is that each trial takes roughly k times longer.
The objective has three jobs:
- Ask the trial for hyperparameter values.
- Build a model from them.
- Return one number, the mean cross-validation score.
A worked example
The objective below chooses between two classifiers. It only suggests the hyperparameters that the chosen classifier uses. This is the define-by-run style from the previous chapter.
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
def objective(trial):
name = trial.suggest_categorical("classifier", ["svc", "rf"])
if name == "svc":
c = trial.suggest_float("svc_c", 1e-3, 1e3, log=True)
model = SVC(C=c, gamma="scale")
else:
depth = trial.suggest_int("rf_max_depth", 2, 16)
model = RandomForestClassifier(max_depth=depth, n_estimators=100, random_state=0)
return cross_val_score(model, X, y, cv=3).mean()
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=30)
print(study.best_trial.params)Points to notice:
direction="maximize"matches the metric.cross_val_scorereturns accuracy by default, where higher is better. If you switch to a loss such asneg_log_loss, the sign is already flipped by scikit-learn, so keep maximizing. If you compute a raw error yourself, minimize.svc_cuseslog=True.Cspans several orders of magnitude, so a log scale samples each magnitude about equally.- Parameter names are prefixed (
svc_c,rf_max_depth). Each name keeps one distribution within a study, so a clear prefix avoids clashes. - The seeded
TPESamplermakes the suggestions repeatable. The model's ownrandom_stateis set too. Both are needed for repeatable scores.
How the pieces fit together
Common errors
- Tuning on the test set. Keep a final test set outside the study. Cross-validate only on the training data, then evaluate the best model once on the test set. Scores from the study itself are optimistic, because you picked the maximum over many noisy trials.
- Forgetting preprocessing in the folds. If you scale or impute outside the cross-validation, information leaks from validation folds into training. Put those steps in a
Pipelineand pass the pipeline tocross_val_score. - Wrong direction. A study that maximizes an error will steadily find the worst model.
- Reusing a parameter name with a different range. Optuna raises an error when the same name has incompatible distributions in one study.
Exercise
Your objective scales features with StandardScaler on the full training set, then calls crossvalscore on an SVC. What is wrong, and how do you fix it?
Show answer
Scaling before cross-validation lets each validation fold influence the scaler's mean and variance, which leaks information and inflates scores. Wrap StandardScaler and SVC in a Pipeline and pass the pipeline to crossvalscore, so scaling is fitted on the training folds only.