Models have hyperparameters you set before training (tree depth, regularisation strength, k). Tuning them — searching for the combination that cross-validates best — often turns a decent model into a strong one.
GridSearchCV
from sklearn.model_selection import GridSearchCVparam_grid = {"n_estimators": [100, 300], "max_depth": [5, 10, None]}search = GridSearchCV(RandomForestClassifier(), param_grid, cv=5, scoring="f1")search.fit(X_train, y_train)search.best_params_ # the winning combinationsearch.best_estimator_ # the model refit on all training data with those params
RandomizedSearchCV
Key takeaways
- 01Hyperparameters are set before training (depth, alpha, k) — tuning them boosts performance.
- 02GridSearchCV exhaustively tries every combination via cross-validation.
- 03RandomizedSearchCV samples combinations — faster for large search spaces.
- 04best_params_/best_estimator_ give the winning settings and refit model; tune on a pipeline.
