Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 08 / Topic 3 of 7

Hyperparameter tuning

Settings the model cannot learn — tree depth, C, number of estimators — are hyperparameters. Tune them with cross-validation on training data; the test set stays sealed for the end.

# examples/02_hyperparameter_search_with_cross_validation.py
grid = GridSearchCV(
    RandomForestClassifier(random_state=0),
    param_grid={"n_estimators": [50, 200], "max_depth": [5, None]},
    cv=3, scoring="accuracy",
)
grid.fit(X, y)
# {'max_depth': 5, 'n_estimators': 50} 0.904
# {'max_depth': 5, 'n_estimators': 200} 0.913
# {'max_depth': None, 'n_estimators': 50} 0.94
# {'max_depth': None, 'n_estimators': 200} 0.944
# best: {'max_depth': None, 'n_estimators': 200}

GridSearchCV tries every combination; RandomizedSearchCV samples — better when the grid is big, since a few parameters usually matter and random search covers each one's range more finely for the same budget.

🧪 Quick quiz

  1. Where should you tune hyperparameters?
Show the answer

With cross-validation on the training data, keeping the test set for the final check — tuning on test makes the final score optimistic.

Done here? The practice set for Part 8 — 4 exercises with solutions — is on the part page.

Search the guide