Scikit-learn using GridSearchCV on DecisionTreeClassifier
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
GridSearchCV is scikit-learn's standard tool for trying multiple hyperparameter combinations under cross-validation and selecting the best model by score. With DecisionTreeClassifier, it is especially useful because tree quality can change a lot with settings such as max_depth, min_samples_split, min_samples_leaf, and criterion.
The Basic Pattern
A DecisionTreeClassifier works out of the box, but its defaults are rarely the best choice for a real dataset. GridSearchCV wraps the estimator, tries every combination in a parameter grid, and evaluates each combination across multiple folds.
A small runnable example with the Iris dataset:
This code does four important things:
- splits train and test data before tuning
- defines a finite parameter grid
- runs cross-validation on the training set only
- evaluates the chosen model on held-out test data afterward
Why The Train/Test Split Still Matters
A common mistake is to run grid search on the whole dataset and report best_score_ as the final model quality. That score is a cross-validation score on the training process, not a true final estimate on unseen held-out data.
The safer workflow is:
- create a train/test split
- run
GridSearchCVon the training split - evaluate
best_estimator_on the test split
That keeps model selection and final evaluation separate.
Choosing A Useful Parameter Grid
For decision trees, start with parameters that control complexity and split quality:
- '
criterion' - '
max_depth' - '
min_samples_split' - '
min_samples_leaf' - '
ccp_alpha'
For example, pruning via ccp_alpha can help reduce overfitting:
Do not make the grid huge without reason. Grid search is exhaustive. The number of fits is roughly:
number of parameter combinations * number of CV folds
A grid with 100 combinations and cv=5 means 500 model fits.
Reading The Results
After fitting, the most important attributes are:
- '
best_params_' - '
best_score_' - '
best_estimator_' - '
cv_results_'
Example:
If you want to inspect all runs, convert cv_results_ into a DataFrame:
That is often more informative than looking only at the winner.
Scoring And Class Imbalance
The default classifier score is accuracy, but that is not always the right metric. If the classes are imbalanced, try a metric that reflects the real objective better, such as f1_macro, roc_auc_ovr, or a custom scorer.
A grid search is only as good as the metric it optimizes.
When To Use A Pipeline
A plain decision tree does not require feature scaling, so a pipeline is often unnecessary. But if preprocessing is involved, wrap everything in a Pipeline so cross-validation applies the transformations correctly inside each fold.
That avoids data leakage. Even when the final estimator is a tree, preprocessing steps still belong inside the pipeline if they learn from the data.
Common Pitfalls
- Running
GridSearchCVon the full dataset and treating the internal CV score as the final test result. - Making the parameter grid far larger than necessary and wasting compute.
- Forgetting
random_state, which makes comparisons harder to reproduce. - Tuning for accuracy when the real problem needs another metric.
- Inspecting only
best_params_and ignoringcv_results_, which often reveals close alternatives and instability.
Summary
- '
GridSearchCVtries parameter combinations under cross-validation and selects the best one by score.' - With
DecisionTreeClassifier, focus first on depth, split thresholds, leaf size, criterion, and pruning. - Split the data before tuning so you can evaluate the chosen model on a true test set.
- Use a scoring metric that matches the real problem, not just the default.
- Review
cv_results_instead of relying only on the single best parameter set.
Related reading
- Scikit and Pandas Fitting Large Data
- Scikit calculate precision and recall using cross_val_score function
- Scikit classification report - change the format of displayed results
- Scikit K-means clustering performance measure
- Scikit learn - fit_transform on the test set
- Scikit Learn - K-Means - Elbow - criterion
- scikit learn custom classifier compatible with GridSearchCV
- Scikit Learn GridSearchCV without cross validation unsupervised learning
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.