Tune hyperparameters with cross-validation

scikit-learn 1.9.1

Search a documented parameter space and keep the final test set for evaluation.

On this page

Choose a search strategy and metric

Parameters are fitted from training data. Hyperparameters configure the estimator before fitting. GridSearchCV evaluates a supplied grid with cross-validation. RandomizedSearchCV samples from the search space using a fixed evaluation budget.

Tune on training data, then evaluate on the holdout

Choose folds and a metric for your problem. Use pipeline step names such as model__C in a parameter grid. Evaluate the refitted best pipeline once on the holdout. Use an untouched test set or nested cross-validation when estimating the performance of the tuning process.

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
pipeline = Pipeline([("scale", StandardScaler()), ("model", LogisticRegression(max_iter=500))])
search = GridSearchCV(pipeline, {"model__C": [0.1, 1, 10]}, cv=3, scoring="f1_macro")
search.fit(X_train, y_train)
print(len(search.cv_results_["params"]))
print(search.score(X_test, y_test) > 0.8)
Example output
3
True

Official references