Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python

Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python

Grid search evaluates every parameter combination in a predefined grid. This updated tutorial uses current scikit-learn APIs, stratified cross-validation, a probability-based scoring metric, and an untouched holdout.

Prepare the classification data

The example uses scikit-learn’s built-in breast-cancer dataset and preserves the class ratio in the train/test split.

X_train, X_test, y_train, y_test = train_test_split(
    dataset.data,
    dataset.target,
    test_size=0.25,
    stratify=dataset.target,
    random_state=RANDOM_SEED,
)
search = GridSearchCV(
    RandomForestClassifier(
        class_weight="balanced", random_state=RANDOM_SEED, n_jobs=-1
    ),
    param_grid=parameter_grid,
    scoring="average_precision",
    cv=StratifiedKFold(n_splits=4, shuffle=True, random_state=RANDOM_SEED),
    n_jobs=1,
)
search.fit(X_train, y_train)

Average precision is preferable to accuracy when probability ranking and minority-class detection matter. The selected model is also compared with a DummyClassifier prevalence baseline.

Evaluate the result

The final average precision, ROC AUC, classification report, and confusion matrix are calculated once on the untouched holdout.

Grid-search validation and holdout confusion matrix

A small exhaustive grid is appropriate for teaching. Larger production searches should reflect a justified compute budget, use nested or repeated validation where needed, and include threshold selection based on real error costs.

Florian Follonier

Florian Follonier · Cloud Solution Architect at Microsoft

Florian Follonier (PhD) is a Cloud Solution Architect at Microsoft based in Zurich and the author of relataly.com, writing hands-on tutorials on machine learning, Python, RAG, and AI agents.

2 Commentsarchived from the original site

  • osmotic
    Helⅼo there! WoulԀ you mind if I share your blog with my facebook group? There's a lot of peoρle that I think would гeally appreciate your content. Please let me know. Ⅿany thanks
  • หี
    Μy brother suggesteɗ I might like this web sіte. He was entireⅼy right. This post actually made my day. Үou cann't imagine just how much time I had spent fоr this information! Thanks!