Hyperparameter Tuning in Machine Learning: GridSearchCV, RandomizedSearchCV and Cross-Validation

A student has built a Random Forest to identify three Iris flower species from four measurements. The classifier already performs well, but an important question remains: could a shallower tree, a different minimum leaf size or a different feature-selection setting make its predictions more reliable? A classmate suggests trying every conceivable setting; another recommends choosing whatever produces the highest score on the final test set. Both proposals risk wasting effort or overstating success. The scientific approach is to establish a baseline, reserve independent test data, compare sensible settings under cross-validation, then report what the held-out observations actually show.

In this hands-on guide to hyperparameter tuning in machine learning, you will use GridSearchCV to evaluate a complete finite grid, RandomizedSearchCV to sample a controlled subset and StratifiedKFold to make fair model comparisons. We will calculate every search budget, run genuine Scikit-Learn experiments, inspect selected settings and build a complete student portfolio project. We will also explain why tuning does not guarantee better models, and why the training, validation and final test sets serve different purposes.

Reproducible experiment verified on 25 November 2026. Iris contains 150 flowers, four measurements and three equally sized species classes. An 80/20 stratified split (seed 89) produced 120 training and 30 untouched test observations. GridSearchCV examined 24 settings in 120 cross-validation fits; RandomizedSearchCV examined 12 settings in 60 fits. Both achieved a best five-fold macro F1 of 0.9582. Under the predetermined tie rule, GridSearchCV was chosen, and its model achieved 29/30 (96.67%) accuracy and 0.9666 macro F1 on the held-out test. Python 3.13.5, Scikit-Learn 1.8.0, NumPy 2.3.5 and Pandas 2.2.3 were used. This small illustrative study is not a guarantee of future or production accuracy.

What is a hyperparameter in machine learning?

Imagine a woodworking machine whose cutting depth, rotation speed and blade selection can be adjusted. The machine has not fundamentally become a different tool, but its operating settings change what it produces. A machine-learning hyperparameter is similar: it controls how a learning algorithm fits or what kind of structure it can learn. The model’s ordinary fitted coefficients, patterns and tree splits are instead estimated from data during the fitting procedure.

Examples include maximum decision-tree depth (max_depth), minimum training examples in a tree leaf (min_samples_leaf), the number of trees in a Random Forest (n_estimators), regularization strength in Logistic Regression (C) and neighbour count in k-nearest neighbours (n_neighbors). Automated searches can select these settings, so ‘hyperparameter’ does not mean ‘must be picked manually’. A good setting is contextual: sample size, features, evaluation metric, computation budget and deployment requirements all influence which choice is sensible.

Model parameters versus hyperparameters: a crucial distinction

Learned parameters are estimated by an algorithm from observations during fitting. In linear models they include slopes and intercepts; in trees they include selected feature splits and their thresholds. Hyperparameters define constraints, controls or procedures around learning, such as the maximum number of splits or the strength of regularization. The choice of hyperparameters can change which learned parameter values a model eventually obtains.

For example, the algorithm can decide that petal length of roughly a certain size separates two groups after seeing training flowers. The student, however, can set a maximum permitted tree depth before the algorithm learns its splits. Hyperparameter search evaluates several such structural settings, comparing their validation performance. Terminology can depend on the modelling framework, but the distinction between search settings and fitted values is fundamental to avoiding confusion.

QuestionLearned model parameterHyperparameter
Where does it come from?Estimated during fittingChosen or searched outside ordinary coefficient estimation
Tree exampleSplit feature and thresholdmax_depth; min_samples_leaf
Linear-model exampleCoefficients and interceptRegularization strength C
EffectDefines a fitted prediction ruleControls the set or procedure of possible fitted rules
How to determine?Training optimizationValidation and search design

Why tune a model that already works?

Many algorithms provide defaults that are thoughtfully chosen for broad use, but a default is not guaranteed to match a particular dataset. Deeper trees can represent subtle relationships but may also follow sampling noise. Larger minimum leaf sizes limit overly specific decisions, potentially improving generalization while reducing flexibility. The number of trees affects ensemble variability and computing cost. Hyperparameter tuning systematically asks how the chosen settings perform under a specified and reproducible comparison.

Importantly, the greatest mean validation score may not justify added cost. A configuration that scores 0.959 rather than 0.958 but uses much more memory or runs much longer may not be the practical choice, especially when the difference is small relative to variation across folds. A sensible experiment also considers simplicity, interpretability, stable predictions and the real consequences of classification errors. Tuning is not a magic operation that improves every model.

Underfitting and overfitting

Underfitting occurs when a model or learning procedure is too restricted to capture important patterns. A tree forced to make only one split may fail to separate Iris versicolor and virginica even in the training data. The symptoms can include relatively low scores on both training and validation observations. Improving the features or permitting a more flexible model may help, but changing depth without diagnosis is not a guarantee.

Overfitting occurs when a fitted model captures peculiarities of the training observations that do not transfer well to new cases. An unrestricted tree can carve the feature space into tiny regions, remembering noise instead of robust patterns. One warning sign is a large training–validation performance gap, although high training accuracy alone does not prove overfitting. Compare score distributions across suitable validation folds and inspect learning behaviour before concluding that a gap is meaningful.

The bias–variance trade-off, carefully explained

In the familiar intuition, restrictive models may exhibit high bias because they cannot represent the relevant relationship, while highly flexible models can exhibit greater sensitivity to which observations happen to appear in training. Good generalization balances these tendencies against unavoidable noise. Tuning a tree’s depth or leaf size is an accessible illustration, but real model behaviour can be more complicated, especially for ensembles.

The classic mathematical bias–variance decomposition applies under particular assumptions and loss functions. Do not interpret a training–validation score difference as a direct numerical measurement of statistical bias or variance. Instead regard fold-to-fold variation and generalization gaps as practical diagnostics. For classification, the selected objective, class proportions, label quality and whether the folds represent the future prediction situation are especially important.

Training, validation and test data have different jobs

Training observations are used to estimate fitted coefficients, split thresholds and other learned parameters. Validation observations help compare hyperparameter settings and choose an approach. Test observations are reserved for a final independent examination of the selected procedure. If the test set is used again and again to make adjustments, the researcher gradually tailors the procedure to those observations; the apparent independence of the final reported accuracy is lost.

Our experiment reserves 30 Iris flowers before search begins. All tuning takes place among the other 120. Cross-validation repeatedly splits the 120 into fitting and validation partitions. Once the candidate configuration is selected using only those results, the winner is refitted on the full 120, and the 30 untouched flowers provide the final test. This simple separation underpins trustworthy machine-learning comparisons.

What is K-fold cross-validation?

K-fold cross-validation divides the eligible development data into K folds. In each repetition, one fold is used for validation and the other folds for fitting. Each observation serves as validation exactly once in ordinary non-repeated K-fold CV. Five-fold validation on 120 Iris training records creates five validation groups of 24; the model fits on 96 observations and is validated on 24 in each round. Five fold scores are summarized, often using their mean and standard deviation.

This procedure reduces dependence on any one arbitrary validation split, though it does not eliminate sampling uncertainty. Validation folds are not independent new populations, and their score standard deviation should not automatically be presented as a conventional confidence interval. Also, cross-validation is useful only if the splitting respects the true data relationships. Repeated measurements from one student, patient or machine should not be treated as independent examples merely because the array has different rows.

FoldFitting recordsValidation recordsValidation class balance
196248 + 8 + 8
296248 + 8 + 8
396248 + 8 + 8
496248 + 8 + 8
596248 + 8 + 8

Why use StratifiedKFold for Iris?

The Iris target contains three species, each represented by 50 flowers. An 80/20 split with stratify=y produces 40 training and 10 test cases per species. Inside the 120 training cases, StratifiedKFold(n_splits=5, shuffle=True, random_state=89) creates validation folds containing eight of each species, while their fitting complements contain 32 of each species.

Stratification is a practical way to keep class proportions similar across folds, avoiding folds that inadvertently overrepresent one species. It does not solve grouped dependence, time leakage, label noise or population shift. For a dataset containing several visits per person, consider GroupKFold or StratifiedGroupKFold; for forecasting, a time-aware split may be necessary. Always begin with the intended prediction task, then select validation that imitates it.

Meet the Iris classification dataset

The Scikit-Learn Iris dataset is a widely used demonstration dataset with 150 labelled observations. Each flower has sepal length, sepal width, petal length and petal width measured in centimetres. The three target species are setosa, versicolor and virginica. Their encoded class labels are 0, 1 and 2, and each class has 50 observations. It is a small, clean educational dataset rather than a modern large-scale monitoring or research benchmark.

For this exercise the predictor matrix X consists of the four measurements and the target vector y gives the known species. Putting the target label into X would leak the correct answer into the inputs. The primary question is whether a Random Forest’s hyperparameter settings can be chosen systematically from a limited search space, not whether Iris findings directly generalize to new botanical populations or high-stakes applications.

Create and verify the 80/20 split

Using seed 89, the project separates 120 development records from 30 final test records. Because each species is represented equally, the training sample contains 40 setosa, 40 versicolor and 40 virginica; the test sample contains ten of each. The actual Python run verified these values. The fixed seed permits repeated splitting in a comparable software environment, but fixed seeds are not guarantees of identical behaviour across every platform and version.

At this point the untouched test set should be put aside. Students should inspect the feature names, target names, data types, missing values and training label balance before tuning. The official Iris features are complete in the built-in dataset. We include median imputation inside a Pipeline as a workflow demonstration for future less-clean data, not because missing Iris values had to be repaired.

Grid search: exhaustive within a finite grid

GridSearchCV examines every specified combination of hyperparameter values and scores each under cross-validation. If a Decision Tree has two candidate maximum depths and three candidate minimum leaf sizes, the grid contains 2 × 3 = six combinations. Adding two choices for a third parameter doubles the candidates to twelve. This combinatorial multiplication is why an indiscriminately large grid may become expensive.

The main Random Forest experiment fixes n_estimators=60 and searches four maximum depths (None, 3, 6, 10), three minimum leaf sizes (1, 2, 4) and two feature sampling choices ('sqrt', None). This is 4 × 3 × 2 = 24 combinations. Five-fold CV requires 24 × 5 = 120 validation fits, followed by a final refit when refit=True. Exhaustive means exhaustive within those 24 settings, never among all theoretically possible forests.

HyperparameterCandidate valuesOptions
model__max_depthNone, 3, 6, 104
model__min_samples_leaf1, 2, 43
model__max_featuressqrt, None2
Finite grid4 × 3 × 224 combinations
Five-fold search24 × 5120 CV fits

Randomized search: use a controlled evaluation budget

RandomizedSearchCV samples a specified number of parameter settings rather than necessarily checking every possible combination. Setting n_iter=12 means twelve candidates are evaluated, producing 12 × 5 = 60 cross-validation fits under five-fold validation. Our example samples 12 of the same 24 finite list-only settings used by the grid search, with a fixed seed of 89.

When all parameters are finite lists, the implemented method can sample configurations without replacement; if continuous probability distributions are included, sampling behaviour differs and repeated combinations may occur. Randomized search can explore much wider or continuous ranges under a limited fitting budget. It may also miss an important setting. Because the grid evaluates every setting in this same finite space, and both searches use the same deterministic model and folds, its best training CV score cannot be lower than that of a sampled subset. This does not prove that grid search is universally better.

AttributeGridSearchCVRandomizedSearchCV
Candidate settings2412 sampled
Validation folds55
CV model fits12060
Automatic best-model refit11
CoverageAll stated combinationsSubset of stated combinations
Globally optimal model guaranteed?NoNo

Search distributions and parameter-space design

A good search space balances scientific reasoning and computational cost. The chosen depth values should reflect how complex the trees may reasonably become; minimum leaf sizes regulate overly local decisions; and maximum feature selection can alter correlations across ensemble trees. Begin with a small, explainable space, inspect training-only findings, then refine further only under a clearly stated validation plan. Searching an arbitrary collection of hundreds of parameters is not a substitute for understanding the model.

For larger randomized searches, SciPy’s randint can sample integers and loguniform can sample positive quantities across orders of magnitude. For example, Logistic Regression regularization C may warrant a log-spaced range because the meaningful changes often multiply rather than add. Verify combinations: some solver and penalty settings are incompatible, and not every estimator accepts every parameter. Bad search distributions produce expensive but uninformative experiments.

Pipelines protect the integrity of validation

A Scikit-Learn Pipeline connects preprocessing and estimation so they are fitted in the correct order on each training fold. In the Iris project the first step is SimpleImputer(strategy='median') and the second step is a Random Forest. The imputer learns medians only from the current fitting records; it then transforms the fold’s validation records without learning from them. The same sequence is refitted on all 120 training records after selection.

Nested estimator settings use a double underscore: because the forest step is named model, its depth is model__max_depth. The step name must match the actual Pipeline definition. Random Forests generally do not require standard feature scaling, so scaling is not inserted into this main example simply for decoration. For regularized linear or distance-based models, a fold-fitted scaler may be essential.

Complete runnable GridSearchCV and RandomizedSearchCV tutorial

The following Python program reproduces the main selection design. The key safeguards are stratify=y during the initial split, a shared shuffled StratifiedKFold object, a fold-aware preprocessing Pipeline, identical finite search spaces and selection by training-only macro F1. return_train_score=True records diagnostic training scores, but these are not used to select the model. The refit=True default behaviour is made explicit.

After search, the program prints the observed best CV scores and selected settings, chooses the grid result in a tie, builds a simple majority-class baseline and evaluates the winner on the held-out test. The final comparison includes an untuned sixty-tree Random Forest as a contextual diagnostic: its test score is shown only after the tuning decision and is not used to revisit search selection. The notebook and source files are supplied separately as reproducible resources.

import pandas as pd
from sklearn.datasets import load_iris
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import (accuracy_score, f1_score,
                             balanced_accuracy_score,
                             confusion_matrix, classification_report)
from sklearn.model_selection import (GridSearchCV, RandomizedSearchCV,
                                     StratifiedKFold, train_test_split)
from sklearn.pipeline import Pipeline

iris = load_iris(as_frame=True)
X, y = iris.data.copy(), iris.target.copy()
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, stratify=y, random_state=89)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=89)
pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("model", RandomForestClassifier(
        n_estimators=60, random_state=89, n_jobs=1))
])
param_grid = {
    "model__max_depth": [None, 3, 6, 10],
    "model__min_samples_leaf": [1, 2, 4],
    "model__max_features": ["sqrt", None],
}
grid = GridSearchCV(
    pipeline, param_grid, scoring="f1_macro", cv=cv,
    refit=True, n_jobs=-1, return_train_score=True)
random = RandomizedSearchCV(
    pipeline, param_grid, n_iter=12, scoring="f1_macro",
    cv=cv, refit=True, random_state=89, n_jobs=-1,
    return_train_score=True)
grid.fit(X_train, y_train)
random.fit(X_train, y_train)
print("Grid CV score:", grid.best_score_, grid.best_params_)
print("Random CV score:", random.best_score_, random.best_params_)
winner = grid if grid.best_score_ >= random.best_score_ else random
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
for name, clf in [("Baseline", baseline), ("Selected", winner)]:
    pred = clf.predict(X_test)
    print(name, "accuracy", accuracy_score(y_test, pred))
    print(name, "macro F1", f1_score(y_test, pred, average="macro"))
    print(name, "balanced accuracy",
          balanced_accuracy_score(y_test, pred))
    print(confusion_matrix(y_test, pred, labels=[0, 1, 2]))
    print(classification_report(
        y_test, pred, target_names=iris.target_names, zero_division=0))
pd.DataFrame(grid.cv_results_).sort_values(
    "rank_test_score").to_csv("grid-search-results.csv", index=False)
pd.DataFrame(random.cv_results_).sort_values(
    "rank_test_score").to_csv("random-search-results.csv", index=False)

Verified results: what did the two searches find?

The full Python experiment was executed using Scikit-Learn 1.8.0. GridSearchCV evaluated 24 settings and reported a best mean five-fold macro F1 of 0.958235. Its best settings were model__max_depth=None, model__max_features=None and model__min_samples_leaf=2. These are actual observed results under the seed, folds, model and metric described above; they are not chosen for appearance.

RandomizedSearchCV evaluated 12 sampled settings and also obtained 0.958235. Its reported best settings differed: model__max_depth=3, model__max_features=None and model__min_samples_leaf=2. Equal validation scores do not imply identical predictions or models. Following our stated tie rule, GridSearchCV was selected. This is a selection convention, not evidence that its particular depth is universally optimal.

SearchCV candidatesCV fitsBest CV macro F1Chosen configuration
GridSearchCV241200.9582Depth=None; leaf=2; max_features=None
RandomizedSearchCV12600.9582Depth=3; leaf=2; max_features=None

Compare the final models on untouched flowers

The majority-only DummyClassifier predicted one class for all 30 test flowers, achieving 10/30 = 33.33% accuracy, macro F1 0.1667 and balanced accuracy 0.3333. A sixty-tree baseline Random Forest using its designated untuned settings scored 28/30 = 93.33% accuracy and macro F1 0.9333. The selected grid-tuned forest correctly classified 29 of 30, giving 96.67% accuracy and macro F1 0.9666. These are observed held-out results, not forecasts.

The tuned model’s confusion matrix, ordered as setosa, versicolor and virginica, is [[10,0,0],[0,9,1],[0,0,10]]. All ten setosa and virginica cases were identified correctly; one versicolor flower was predicted as virginica. The final test contains only ten cases per species, so a difference of one error produces several percentage points of apparent improvement. The model’s advantage in this run cannot establish that tuning always beats a default forest, or that the observed difference is statistically significant.

ModelTest accuracyTest macro F1Balanced accuracy
Majority-only baseline33.33%0.166733.33%
Untuned 60-tree Random Forest93.33%0.933393.33%
Selected grid-tuned Random Forest96.67%0.966696.67%
Actual speciesPred. setosaPred. versicolorPred. virginica
Setosa1000
Versicolor091
Virginica0010

What do best_params_, best_score_ and best_estimator_ mean?

best_params_ is a dictionary of the selected setting values among the configurations actually evaluated. It is not a universal formula for the best Random Forest on every dataset. best_score_ is the mean cross-validation score used for selection—here macro F1 on the training-partition folds. It is not the 30-row held-out test score, and it can be optimistic because a winner was chosen using those same validation scores.

With refit=True, best_estimator_ is the selected Pipeline trained again on the entire available 120-row training partition. This is why calling grid.predict(X_test) works after fitting the search object. With refit=False, refit-dependent prediction methods and attributes are not generally available in the same way. If multiple scoring metrics are provided, a clear refit metric or selection strategy is needed.

Reading cv_results_ without confusion

The attribute cv_results_ contains a structured record for each candidate. params identifies the configuration; mean_test_score refers to cross-validation scores on validation folds (despite the word ‘test’); std_test_score summarizes fold variation; rank_test_score orders candidates; and timing fields such as mean_fit_time summarize fitting activity. With return_train_score=True, corresponding training diagnostics are available.

Convert the dictionary into a Pandas DataFrame and sort by validation rank to inspect the top five candidates. Also compare per-fold scores, because two close means can conceal very different patterns. Neither ranks nor tiny mean differences automatically establish statistical significance. The measured full-run wall-clock time in one execution was about 11.35 seconds for grid search and 1.06 seconds for randomized search, but those values depend on worker scheduling, caches and hardware; they are not stable universal benchmarks.

grid_table = pd.DataFrame(grid.cv_results_)
cols = ["params","mean_test_score","std_test_score",
        "rank_test_score","mean_fit_time","mean_train_score"]
print(grid_table.sort_values("rank_test_score")[cols].head(5))
print("Refitted winner:", grid.best_estimator_)

Calculate a cross-validation mean and interpret variation

Suppose five fictional validation macro F1 scores were 0.90, 0.92, 0.88, 0.94 and 0.91. Their sum is 4.55; dividing by five gives a mean of 0.91. They vary because the model is trained and validated on different observations in each fold. This is a teaching calculation, not a quotation of the executed Iris search’s per-fold scores.

A useful report includes the mean, variation, sample size and splitting procedure. A high average does not mean every example is classified correctly, and fold scores may be correlated because the fitting sets overlap. Do not turn the standard deviation of five fold scores into a formal confidence interval for future data without a justified statistical procedure. For reliable claims about deployment, further independent data and appropriate uncertainty analysis may be needed.

Visualization: what a tuning heatmap should show

A heatmap can place maximum depth on one axis and minimum leaf size on the other, using the validation macro F1 as the cell colour. Because this experiment also varies max_features, students should filter to a single value or use separate panels so that each cell corresponds to a well-defined configuration. A colour difference represents observed score differences, not necessarily meaningful scientific evidence.

Likewise, a ranked dot plot for the twelve random-search candidates helps show which points in the finite space were sampled. The companion package contains charts derived from the actual CSV results, rather than invented score tables. When displaying graphs on mobile, maintain readable labels and show full-size versions through links instead of squeezing tick text into an unreadable strip.

Actual five-fold GridSearchCV macro F1 heatmap, max_features=None
Verified training-only grid-search macro F1 by maximum tree depth and leaf size
Actual twelve-candidate RandomizedSearchCV score comparison
Verified mean five-fold macro F1 across the twelve sampled settings
Five-fold training-validation design
Five folds with green validation partition and grey fitting partitions

Computation: fit counts are not elapsed seconds

With 24 grid candidates and five folds, the search performs 120 CV fits plus one refit, assuming no failures. With twelve randomized candidates it performs 60 CV fits plus one refit. The second experiment uses half as many cross-validation fits in this design. It does not follow that execution time must be exactly half: model depth, number of examples, parallel scheduling, memory pressure and available CPU cores all influence runtime.

Here we fixed forest size at sixty trees to simplify candidate comparison, ran the inner forest with n_jobs=1 and permitted search-level parallelism. That arrangement avoids uncontrolled nested parallel work while keeping the example approachable. Students should time their own environment and document measurements rather than borrowing somebody else’s speed claims. They should also limit parameter combinations to fit their laptop or school computer resources.

Multi-metric tuning and choosing the right score

For multiclass Iris, macro F1 computes F1 separately for each species and then takes their simple mean; this prevents one class from receiving more influence merely because it has more observations. Balanced accuracy averages recalls across classes, while ordinary accuracy counts the share of correctly classified cases. The three species are evenly represented in this dataset, so their practical differences are smaller than in a severely imbalanced task. Yet they still measure different aspects.

Scikit-Learn can record multiple metrics with scoring={'accuracy':'accuracy','macro_f1':'f1_macro'} and select using refit='macro_f1'. Defining the primary metric in advance prevents cherry-picking whichever score favours a preferred model. For the rare-event classification in Topic 88, Average Precision, positive recall and false-alarm costs may be more central than raw accuracy. Any resampling should be contained inside an imbalanced-learn training Pipeline during tuning.

More search examples: Logistic Regression and Decision Trees

A Logistic Regression extension could search C values 0.01, 0.1, 1, 10 and 100. In its common convention, smaller positive C means stronger regularization and larger C means weaker regularization. A Pipeline should include StandardScaler fitted within each CV training fold, followed by Logistic Regression with a compatible solver and penalty configuration. Discrete candidate values are appropriate for a small grid; log-scaled randomized values can cover broader ranges.

For a Decision Tree, consider max_depth, min_samples_split, min_samples_leaf and the pruning parameter ccp_alpha. Compare a shallow tree, a moderately constrained tree and an unrestricted tree under the same training-only validation. The deepest tree need not win. These are extension designs rather than executed additional experiments in this report; actual performance must be obtained by running them.

Nested cross-validation: separating tuning from performance estimation

Ordinary GridSearchCV selects the candidate with the highest mean score among settings in the inner folds. Because selection favours the greatest measured score, the winner’s best_score_ may be an optimistic estimate of the complete tuning procedure. Nested cross-validation places this tuning process inside an outer validation loop: inner folds select settings using only outer-training observations, and the held-out outer fold evaluates the entire selected procedure.

The outer scores summarize how model selection performs when repeated on separate held-out partitions. This is useful for more rigorous comparisons, especially when datasets are small and many settings are considered. It costs more computation because a complete search is repeated for every outer fold. A properly protected final test set, as in the main tutorial, is a valid practical alternative; beginners do not need nested CV for every classroom experiment.

Grouped validation and time-aware model testing

Imagine a study in which one student contributes several exam records. If the objective is to predict outcomes for new students, a random row split can place records for the same individual in training and validation sets. The model may exploit student-specific patterns rather than learning relationships that generalize to unseen students. GroupKFold keeps groups separate in validation; StratifiedGroupKFold aims to respect both class balance and group separation where feasible.

For weather or financial forecasting, training on later observations to score earlier examples can create unrealistic validation. TimeSeriesSplit creates ordered partitions, but data leakage may still occur through features computed with future values, overlapping labels or improperly aligned lags. Validation design must match the real prediction horizon and feature availability. Ordinary stratification is right for our independent Iris example but not a universal rule.

Forty-five tuning mistakes worth recognizing

Common mistakes begin before code is written: confusing hyperparameters with fitted values; failing to define an objective; skipping baselines; selecting using training accuracy; tuning against the final test set; repeatedly revisiting test results; preprocessing before splitting; choosing an inappropriate validation method; ignoring repeated entities; and treating future observations as available in historical forecasts. Each creates a different kind of weak evidence or possible leakage.

Other recurring mistakes include ignoring rare classes, using unsuitable metrics, sampling too few positives per fold, entering invalid solver–penalty combinations, creating gigantic grids, claiming exhaustive search over all possibilities, assuming randomized search always wins, assuming more complexity means better generalization, miscalculating fit counts, forgetting final refitting, confusing best_score_ with test accuracy, and treating cv_results_‘s ‘test’ columns as independent test-set results.

Further errors include hiding score variability, using different folds for a purportedly controlled comparison, choosing a scoring metric after seeing which winner it gives, failing to record seeds or package versions, inventing best parameters or timings, searching too many interacting options without a design, failing to inspect training and validation behaviour, exaggerating tiny improvements, optimizing only speed, ignoring memory costs, and oversampling before cross-validation.

Advanced mistakes include treating nested CV as identical to ordinary CV, extrapolating from a tiny classroom test to deployment, sharing unverified saved models, plotting fabricated scores, ignoring fairness and privacy, ignoring data provenance, misreporting sample units, failing to check missing values or duplicate rows, mislabelling the target class, and claiming executable code was tested when it was not. For each mistake the correction is to state the actual data split, model, search, scoring objective, executed evidence and limits; in many cases the remedy is a fold-aware Pipeline and honest independent evaluation.

Capstone project: Optimizing an Iris Classifier with GridSearchCV and RandomizedSearchCV

Task 1: Load and verify Iris

Print the 150×4 feature shape, label names, feature units and 50/50/50 counts. Required interpretation: Do not mistake the encoded class numbers for measured quantities. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 2: Reserve the final test set

Use stratify=y, 20% test size and seed 89; verify 120/30 with 40/10 per species. Required interpretation: Never select settings using y_test. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 3: Establish an uninformed baseline

Fit most-frequent DummyClassifier on the 120 training observations. Required interpretation: The 33.33% held-out accuracy is a benchmark, not an optimized result. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 4: Define the search grid

Write the three parameter lists and multiply 4×3×2=24. Required interpretation: Keep fixed n_estimators=60 out of the candidate count. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 5: Run GridSearchCV

Set f1_macro, StratifiedKFold(5), refit=True and execute .fit on training data. Required interpretation: Expect 24 candidates, 120 CV fits and a final refit. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 6: Run RandomizedSearchCV

Set n_iter=12, seed 89, the same five folds and same finite candidate space. Required interpretation: Expect 12 sampled configurations and 60 CV fits. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 7: Inspect search results

Compare best_params_, best_score_, train scores, std_test_score, ranks and the top five rows. Required interpretation: Do not confuse fold validation with untouched test evaluation. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 8: Compare computational budgets

Report fit counts and measured runtime from your own machine. Required interpretation: Do not equate halved fit count with halved elapsed time. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 9: Evaluate the preselected winner

Apply chosen grid settings to the untouched 30-row test and print the confusion matrix. Required interpretation: The verified selected result is 29/30 accuracy and 0.9666 macro F1. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Task 10: Write your research report

Document provenance, seed, versions, search space, metrics, plots and limitations. Required interpretation: Explain why the small 30-flower test is not deployment evidence. Extend your investigation by changing only the experimental factor stated in your hypothesis, and keep the held-out test protected.

Thirty original practice questions with worked solutions

1. What is hyperparameter tuning?

Worked answer: Comparing algorithm settings using a suitable validation procedure to choose a useful configuration. Check: identify the dataset partition and the metric before drawing conclusions.

2. How do learned parameters differ from hyperparameters?

Worked answer: Fitted coefficients and split thresholds are estimated from training observations; hyperparameters govern learning or structure. Check: identify the dataset partition and the metric before drawing conclusions.

3. Name one Decision Tree hyperparameter.

Worked answer: max_depth, min_samples_leaf, min_samples_split or ccp_alpha. Check: identify the dataset partition and the metric before drawing conclusions.

4. What is underfitting?

Worked answer: Failing to capture important structure, commonly reflected in weak fitting and validation performance. Check: identify the dataset partition and the metric before drawing conclusions.

5. What is overfitting?

Worked answer: Fitting idiosyncrasies in training data that fail to generalize to new examples. Check: identify the dataset partition and the metric before drawing conclusions.

6. Define cross-validation.

Worked answer: Repeatedly fitting on development subsets and scoring on their excluded validation subsets. Check: identify the dataset partition and the metric before drawing conclusions.

7. How do fitting and validation observations differ?

Worked answer: Fitting observations estimate the model; validation observations help select settings. Check: identify the dataset partition and the metric before drawing conclusions.

8. Why protect a held-out test set?

Worked answer: Using it to choose settings contaminates the final independent evaluation. Check: identify the dataset partition and the metric before drawing conclusions.

9. Define grid search.

Worked answer: Evaluate every combination in a specified finite parameter grid. Check: identify the dataset partition and the metric before drawing conclusions.

10. Define randomized search.

Worked answer: Evaluate a specified number of settings sampled from a candidate space or distributions. Check: identify the dataset partition and the metric before drawing conclusions.

11. A grid has 4 depths, 3 leaf sizes and 2 feature settings. How many candidates?

Worked answer: 4×3×2=24. Check: identify the dataset partition and the metric before drawing conclusions.

12. How many five-fold CV fits for those 24 combinations?

Worked answer: 24×5=120, before final refitting. Check: identify the dataset partition and the metric before drawing conclusions.

13. How many five-fold fits for 12 random settings?

Worked answer: 12×5=60, before final refitting. Check: identify the dataset partition and the metric before drawing conclusions.

14. Split 150 Iris observations 80/20. What counts result?

Worked answer: 120 training and 30 final test observations. Check: identify the dataset partition and the metric before drawing conclusions.

15. With 120 training rows and five folds, how large is each validation group?

Worked answer: 120/5=24 validation rows; 96 fitting rows. Check: identify the dataset partition and the metric before drawing conclusions.

16. Calculate mean of .90, .92, .88, .94 and .91.

Worked answer: The scores sum to 4.55; 4.55/5=0.91. Check: identify the dataset partition and the metric before drawing conclusions.

17. Why might CV fold scores vary?

Worked answer: Their training and validation observations differ; score variation is a diagnostic, not automatic statistical significance. Check: identify the dataset partition and the metric before drawing conclusions.

18. Choose between validation scores 0.94 and 0.92 under identical conditions.

Worked answer: The first has the higher measured mean, subject to uncertainty and practical cost. Check: identify the dataset partition and the metric before drawing conclusions.

19. What does cv_results_[‘rank_test_score’] convey?

Worked answer: Candidate ranking according to validation performance, not independent test ranking. Check: identify the dataset partition and the metric before drawing conclusions.

20. Which search uses fewer CV fits here and by what amount?

Worked answer: Randomized: 60 instead of 120; 50% fewer validation fits. Check: identify the dataset partition and the metric before drawing conclusions.

21. A scaler is fitted before CV on all rows. What is wrong?

Worked answer: Fold validation information influenced preprocessing; fit the scaler within a Pipeline on each fitting fold. Check: identify the dataset partition and the metric before drawing conclusions.

22. Why is repeated test-set tuning problematic?

Worked answer: It allows choices to overfit the test labels and invalidates the independence of the final estimate. Check: identify the dataset partition and the metric before drawing conclusions.

23. Which distribution suits a positive parameter over several orders of magnitude?

Worked answer: A log-spaced grid or a suitable loguniform distribution. Check: identify the dataset partition and the metric before drawing conclusions.

24. Why avoid incompatible Logistic Regression solver/penalty combinations?

Worked answer: They cause invalid fits or misleading searches; use verified supported combinations. Check: identify the dataset partition and the metric before drawing conclusions.

25. What does best_params_ return?

Worked answer: The selected values among actually evaluated configurations. Check: identify the dataset partition and the metric before drawing conclusions.

26. What does best_score_ return here?

Worked answer: The selected mean training-partition CV macro F1, not the final test score. Check: identify the dataset partition and the metric before drawing conclusions.

27. What does best_estimator_ mean with refit=True?

Worked answer: The chosen Pipeline fitted again on the complete 120-row training partition. Check: identify the dataset partition and the metric before drawing conclusions.

28. When would GroupKFold be appropriate?

Worked answer: When repeated records belong to the same entity and the goal is generalization to unseen groups. Check: identify the dataset partition and the metric before drawing conclusions.

29. What is nested CV?

Worked answer: Inner folds select configurations; outer folds evaluate the full selection procedure. Check: identify the dataset partition and the metric before drawing conclusions.

30. Design a valid tuning experiment in one sentence.

Worked answer: Define objective and metric, reserve test data, build a fold-aware Pipeline, compare settings on consistent folds, select once, refit and evaluate once on test. Check: identify the dataset partition and the metric before drawing conclusions.

Which Hyperparameter Setting Would You Choose? — Eight scenarios

Scenario 1: Your grid has 2,000 configurations and a school laptop has limited memory.

Recommended decision: Reduce the space using informed ranges or sample a controlled randomized budget; record coverage. Other approaches may be defensible if their assumptions are documented.

Scenario 2: Training macro F1 is 1.00 but validation macro F1 is 0.75.

Recommended decision: Investigate overfitting, complexity, fold design and possibly smaller trees or larger leaves. Other approaches may be defensible if their assumptions are documented.

Scenario 3: A classmate checks test accuracy after every parameter change.

Recommended decision: Stop test-set inspection; choose using validation and reserve a fresh independent test where needed. Other approaches may be defensible if their assumptions are documented.

Scenario 4: Only 2% of records are positives and accuracy looks high.

Recommended decision: Define the rare-event objective and consider AP, recall and error costs; follow Topic 88. Other approaches may be defensible if their assumptions are documented.

Scenario 5: Each learner contributes six assessments.

Recommended decision: Use group-aware splitting if generalizing to new learners; do not distribute one learner across fitting and validation. Other approaches may be defensible if their assumptions are documented.

Scenario 6: You forecast next month’s weather with historical readings.

Recommended decision: Use time-aware validation and verify every feature existed at prediction time. Other approaches may be defensible if their assumptions are documented.

Scenario 7: Two models score .955 and .956 but one costs ten times as much.

Recommended decision: Examine fold uncertainty, complexity and operating constraints; the tiny difference may not justify cost. Other approaches may be defensible if their assumptions are documented.

Scenario 8: Random search draws C uniformly from 1 to a million.

Recommended decision: Consider a justified logarithmic distribution when the relevant scale is multiplicative. Other approaches may be defensible if their assumptions are documented.

Formula cheat sheet

QuantityFormulaWorked value
Grid combinationsProduct of candidate-list lengths4×3×2=24
Grid CV fitsCandidates×K24×5=120
Random-search CV fitsn_iter×K12×5=60
Mean fold scoreSum of scores÷K4.55÷5=0.91
AccuracyCorrect predictions÷all predictions29÷30=96.67%
Macro F1Mean of class-specific F1 scoresSelected held-out 0.9666
Generalization gapTrain metric−validation metricInterpret diagnostically

Four-week student learning roadmap

Week 1 — Understand models and validation

Study fitted parameters, hyperparameters, underfitting, overfitting and K-fold validation. Draw a five-fold allocation diagram for 120 observations. Calculate macro F1 from a constructed confusion matrix. Your assignment is to explain the three different purposes of training, validation and final test data in your own words.

Week 2 — Plan and execute two searches

Construct the 24-combination Random Forest grid and calculate its five-fold cost. Implement GridSearchCV and RandomizedSearchCV on the same 120 Iris training observations. Read the returned parameter dictionaries and investigate how twelve sampled settings compare with all twenty-four finite combinations.

Week 3 — Interpret evidence honestly

Convert cv_results_ into a DataFrame, inspect top candidates and their fold variation, then draw the heatmap and ranked random-search scores. Compare candidate counts and measured fitting times, not merely ranking. Report the chosen configuration without using the 30 final test observations to alter search choices.

Week 4 — Produce a reproducible capstone

Complete the ten tasks, answer thirty questions, write a short research report and create a model card listing intended use, dataset provenance, versions, limitations and ethical cautions. Explain nested, grouped and time-series validation. Finally record the untouched test confusion matrix and discuss why a single error changes performance notably in such a small evaluation set.

Frequently asked questions

What is hyperparameter tuning?

Systematically choosing model settings based on suitable validation results.

Is tuning always better than model defaults?

No. Defaults may already be competitive, and tuning can overfit the validation process.

What does CV mean?

Cross-validation: repeated development-data fitting and validation splits.

How does GridSearchCV work?

It evaluates all candidate combinations from a finite grid using the specified cross-validation strategy.

How does RandomizedSearchCV work?

It samples a chosen number of configurations from specified lists or distributions.

Which search is best?

Neither is universally best; consider space size, search budget and evidence.

What is StratifiedKFold?

A splitter designed to preserve approximately similar class proportions across classification folds.

What does best_params_ mean?

The selected parameter values among tested configurations.

What does best_score_ mean?

The winner’s cross-validation score under the search’s scoring and selection rule, not final test accuracy.

What does best_estimator_ mean?

With refit enabled, the chosen estimator trained on the complete search training partition.

Why is cv_results_ useful?

It exposes configurations, fold scores, ranks, variation and timing measurements.

What does refit=True do?

It retrains the chosen configuration on all training data given to the search after validation.

Why must the final test set remain separate?

Using its outcomes during selection compromises independent performance assessment.

How many CV folds should beginners use?

Five is a common starting point, but the task, sample size and dependencies determine the right design.

Does tuning prove a model is reliable in the real world?

No. Independent, representative evidence and task-specific assessment are still necessary.

Authoritative research and follow-up lessons

Download companion learning resources

Additional Python code, the executable notebook, verified GridSearchCV and RandomizedSearchCV CSVs, Excel-compatible workbooks and experiment report are available in the separate complete student package supplied with this lesson. Run the code using matching dependencies and record your own environment before interpreting any differences.

Official references: Scikit-Learn GridSearchCV, RandomizedSearchCV, cross-validation guide, common data-leakage pitfalls and nested cross-validation on Iris. The companion plots and CSVs are original outputs of the experiment described here.

Continue your Notes for SHS learning with Topic 88: Handling Imbalanced Datasets, Topic 87: Machine Learning Classification, Topic 86: Student Grade Prediction, Decision Tree Training and Model Evaluation.

Conclusion: tuning is a carefully designed experiment

The purpose of hyperparameter tuning is not to try random settings until one model reports a flattering percentage. It is to create a meaningful search space, choose a validation procedure aligned with the prediction task, manage computation, protect the test sample and explain the evidence honestly. In the verified Iris experiment, both search methods found configurations with the same best cross-validated macro F1 of 0.9582; the grid was selected by the declared tie rule, and it achieved 29 correct predictions from 30 unseen flowers. That result is useful evidence for an instructional exercise, but it remains limited by sample size, task simplicity and validation assumptions. You can now extend the experiment to another classifier or dataset—provided you preserve the discipline of independent evaluation.