Sub topic 8
Tuning a scikit-learn model with cross-validation
This chapter assumes you can train and validate a scikit-learn model, know the difference between parameters and hyperparameters, and understand train/validation splits and k-fold cross-validation. You should also know how to write an Optuna objective function and call suggest_float, as covered in earlier chapters.
The workflow
A tuning run for a scikit-learn model has four steps:
- Hold out a test set that the search never sees.
- Write an objective that builds a model from the trial's suggestions and returns its cross-validated score on the training data.
- Run the study.
- Refit a fresh model with the best parameters on all the training data, then score it once on the test set.
Why cross-validation sits inside the objective
A single validation split gives a noisy score. With hundreds of trials, the sampler tends to find parameters that happen to suit that one split. Cross-validation averages over several splits, so the objective is less noisy and each trial is a fairer comparison. The cost is time: each trial trains the model k times.
The objective returns one number, so you average the fold scores with .mean(). Optuna compares only that number. It never sees the individual folds.
A complete example
This example tunes an SVM inside a pipeline on the breast cancer dataset.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
optuna.logging.set_verbosity(optuna.logging.WARNING)
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
def build_model(c, gamma):
return make_pipeline(StandardScaler(), SVC(C=c, gamma=gamma))
def objective(trial):
c = trial.suggest_float("c", 1e-2, 1e3, log=True)
gamma = trial.suggest_float("gamma", 1e-4, 1e0, log=True)
model = build_model(c, gamma)
return cross_val_score(model, X_train, y_train, cv=cv, scoring="f1").mean()
sampler = optuna.samplers.TPESampler(seed=0)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=40)
best_model = build_model(**study.best_params)
best_model.fit(X_train, y_train)
print("Best CV F1:", round(study.best_value, 4))
print("Test accuracy:", round(best_model.score(X_test, y_test), 4))Several details in this code matter:
- The scaler is inside the pipeline.
cross_val_scorefits the whole pipeline on each training fold, so the scaler learns its mean and variance from that fold only. If you scaledX_trainbefore cross-validation, statistics from the validation folds would leak into training. - The splitter is a fixed object. Every trial uses the same folds, so differences between trials come from the hyperparameters and not from different splits. Without a fixed
random_state, ashuffle=Truesplitter would produce different folds in each trial. build_modelis shared. The final model is built by the same function as the trial models, so the two cannot drift apart. Becausestudy.best_paramsis a dictionary keyed by the names you passed tosuggest_*,build_model(**study.best_params)only works when those names match the function's arguments.- Both parameters are log-scaled.
Candgammamatter on a multiplicative scale. Sampling on a log scale spends as many trials between 0.01 and 1 as between 10 and 1000.
Choosing the scoring metric and direction
cross_val_score uses the estimator's default metric unless you set scoring. That default is accuracy for classifiers and R² for regressors. Choose the metric that matches your goal, such as "f1" or "roc_auc" for imbalanced classes.
The direction of the study must agree with the metric. scikit-learn scorers follow a "bigger is better" convention, so error metrics are negated:
| Metric string | Meaning of the returned value | Study direction |
|---|---|---|
| `"accuracy"`, `"f1"`, `"roc_auc"` | Higher is better | `maximize` |
| `"r2"` | Higher is better | `maximize` |
| `"neg_mean_squared_error"` | Negated error, so higher is better | `maximize` |
| `"neg_log_loss"` | Negated loss, so higher is better | `maximize` |
You can also compute an error yourself and use direction="minimize". Do not mix the two. A study that minimises neg_mean_squared_error will search for the worst model.
Searching over model choices
You can also let the objective choose among estimator types. Each branch suggests only the parameters it needs, and each parameter has a name that is unique to its branch:
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()This needs RandomForestClassifier imported from sklearn.ensemble. Optuna requires that a parameter name keeps the same distribution within a study. Reusing a name such as "c" with different ranges in two branches raises an error. The prefixes svc_ and rf_ avoid that. The next chapter sections on conditional spaces cover this in more detail.
Common errors
- Tuning on the test set. If you pass the test data into the objective, the test score is no longer an honest estimate. Keep it out of the study entirely.
- Preprocessing outside the pipeline. Scalers, imputers and feature selectors fitted on all the training data before cross-validation leak information into the validation folds. The scores look better than they should.
- Wrong direction. Maximising a loss or minimising an accuracy produces a study that runs without errors and returns bad parameters. Check the first few trial values against what you expect.
- Unseeded randomness. Set
random_stateon the model and the splitter as well as the sampler seed. A seeded sampler with an unseeded forest still gives different scores on each run. - A search range that is too wide or too narrow. If
best_paramssits at the edge of a range, widen that range and run again. - Failing trials. An exception inside the objective stops
study.optimizeby default. Returningnanmarks the trial as failed. A model that can fail for some parameter combinations should be wrapped so that you either return a poor score or raiseoptuna.TrialPruned(). - Too many trials for a noisy objective. When the standard deviation of the fold scores is larger than the gaps between trials, extra trials mostly fit noise. Use more folds or repeated cross-validation, or stop earlier.
Exercise
You tune a Ridge regression with cross_val_score(model, X_train, y_train, cv=cv, scoring="neg_mean_squared_error").mean() as the return value. Which study direction do you pass to create_study, and why? Also, you fit a StandardScaler on X_train before the study begins. What problem does this cause, and how do you fix it?
Show answer
Use direction="maximize". The scorer returns the negated error, so a higher value means a smaller error. Fitting the scaler on all of X_train first lets statistics from each validation fold influence training, which leaks information and inflates the scores. Fix it by putting the scaler in a pipeline, for example make_pipeline(StandardScaler(), Ridge(alpha=alpha)), so that it is refitted on the training portion of every fold.