smartyfy.mrindigi.com

AI & Machine Learning Master Course — 066. Hyperparameter search without leakage

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 066: Hyperparameter search without leakage

Prerequisites: Lesson 065. Learning outcome: Run bounded model searches through properly nested preprocessing.

1. A search is an experiment with a budget

Hyperparameters configure a learning procedure before its fitted parameters are estimated. An SVM’s C and gamma are hyperparameters; its support-vector coefficients are learned during fitting. Preprocessing choices, feature-selection settings, and thresholds can also be part of the system-selection process. Treating only the final estimator’s knobs as “tuning” misses many real opportunities to overfit validation data.

Begin with a bounded candidate set, a suitable split design, a metric, and a compute budget. A small justified search is often more informative than an enormous unexplained grid. Record every candidate tried, including failed fits, rather than keeping only the successful configuration in the final report.

2. Count the work before launching it

A grid with three C values and two gamma values contains six configurations. Three-fold evaluation requires eighteen fitting runs, followed by one final refit when refit=True. The final refit trains the selected configuration on all allowed development data; it does not average the parameters from the fold models.

Grid search exhaustively covers only the supplied combinations, not every possible setting. Randomized search instead samples a declared distribution or list under a fixed trial budget. For positive scale parameters, logarithmic ranges often make more sense than densely spaced linear values because meaningful behavior can change across orders of magnitude.

A search over incompatible parameter combinations wastes resources and can obscure errors. Use conditional grids or separate candidate dictionaries when an option only applies to a particular estimator or solver. Limit parallel jobs according to available memory and CPU, especially when each candidate itself uses multiple threads.

3. Put the entire learned representation inside the search

The object passed to GridSearchCV should include preprocessing and the estimator. A scaler fitted on all development rows before cross-validation leaks fold-validation information into every candidate. A pipeline fits that scaler separately inside each training fold, so each validation prediction reflects only the information available to that fit.

Nested parameter names use double underscores, such as svc__C. These identify which named component receives the setting. A search can also vary preprocessing parameters, but every learned operation still belongs inside the fold boundary. Target encoding, imputation, vocabulary fitting, feature selection, and calibration require the same care.

The fold design must match the intended prediction setting. A perfect pipeline cannot compensate for related customers crossing a new-customer validation boundary or for future rows entering a forecasting training set. Pass an explicit splitter instead of relying on defaults whose behavior may not match the task.

A three-by-two grid covers C values 0.1, 1, 10 and gamma values 0.1, 1. Every cell contains three separate fold fits. Each fold fits its scaler and SVC using only its training subset. The budget is eighteen fold fits plus one full-development refit. A separate final-test boundary excludes final rows and labels from selection.
Search the whole fitted pipeline. The final refit learns the selected configuration on all permitted development data. Open full-size diagram

4. Inspect the whole result, not only the winner

The cv_results_ structure records parameter combinations, fold and mean scores, variation, and timing information. Its field names use “test” for each held-out cross-validation fold; in this context those are development-validation scores, not a separate final test. Make that distinction explicit in reports.

The highest mean score is a noisy selection statistic. A tiny difference between candidates may not justify a much larger or slower model. Predeclare how performance, latency, memory, or simplicity affect selection. If several metrics are collected, specify which metric or rule determines refitting rather than choosing the most flattering metric afterward.

For this lesson, error_score='raise' makes invalid fits visible immediately instead of silently continuing with missing scores. Larger workflows may deliberately record failures and continue, but must inspect them. A failed candidate is not equivalent to evidence that its underlying modeling idea is poor; the configuration may simply be invalid.

Development search results

Mean three-fold balanced accuracy on the synthetic development data; higher is better
C Gamma Balanced accuracy
0.1 0.1 0.7962
0.1 1.0 0.5953
1.0 0.1 0.8768
1.0 1.0 0.8383
10.0 0.1 0.8714
10.0 1.0 0.8548

5. Keep final assessment outside selection

The selected configuration is C=1,gamma=0.1 in this run. Its 0.8768 mean score has been chosen from six estimates and is not an untouched final performance claim. Assess the selected procedure using a reserved final set or an outer nested evaluation, developed next.

If the best value lies at a search boundary, investigating a broader range can be reasonable during development. That decision becomes part of the search history. Do not repeatedly widen the range after checking final-test results while describing each new score as independent confirmation.

CPU lab: run and audit a small grid

The script uses NumPy and scikit-learn on a CPU, checked with versions 2.3.5 and 1.8.0. It generates 180 synthetic observations and evaluates six prespecified RBF-SVM pipelines with three stratified folds. n_jobs=1 keeps the resource demand bounded; there is no data download or external service.

It checks the candidate count and verifies that the final refitted scaler uses the development mean. Fold-specific preprocessing is handled by the pipeline passed into the search. The output table is an observed result of this synthetic experiment, not a recommendation that these hyperparameters are optimal for another dataset.

import numpy as np
from sklearn.datasets import make_classification
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV,StratifiedKFold,ParameterGrid
X,y=make_classification(n_samples=180,n_features=6,n_informative=4,n_redundant=0,random_state=66)
pipe=Pipeline([('scale',StandardScaler()),('svc',SVC())])
grid={'svc__C':[.1,1.,10.],'svc__gamma':[.1,1.]}
cv=StratifiedKFold(3,shuffle=True,random_state=66)
search=GridSearchCV(pipe,grid,cv=cv,scoring='balanced_accuracy',
    n_jobs=1,error_score='raise',return_train_score=True).fit(X,y)
assert len(search.cv_results_['params'])==len(list(ParameterGrid(grid)))==6
print('Candidates/CV fits/refit:',6,18,1)
print('Selected:',search.best_params_)
print('Selected development balanced accuracy:',round(search.best_score_,4))
for params,score in zip(search.cv_results_['params'],search.cv_results_['mean_test_score']):
    print(params,round(score,4))
# Final refit scaler learns only this development dataset.
np.testing.assert_allclose(search.best_estimator_.named_steps['scale'].mean_,X.mean(axis=0))

Four practice questions with worked answers

Practice 1

A grid has four depths, three leaf sizes, and five folds. How many fitting runs occur with one final refit?

Answer: There are 4×3=12 configurations, each fitted five times, giving 60 cross-validation fits. A final refit adds one, for 61 total. Additional calibration, preprocessing searches, or repeated folds can add more work, so budget for the complete workflow rather than just the final estimator.

Practice 2

Why is scaling all development rows before GridSearchCV still a problem even if a separate final test exists?

Answer: Each inner validation fold has already influenced the scaler used to predict it. That distorts the development comparison and can affect which model is selected. Put scaling inside the searched pipeline so each fold’s representation is fitted only on its training portion.

Practice 3

What does mean_test_score refer to in this grid-search result?

Answer: It is the mean held-out fold score within the development search. The API calls those folds test splits, but they are used for selection here. The selected mean is therefore not a separate final-test estimate and should be labeled development cross-validation performance.

Practice 4

The best C is the largest value searched. What is a defensible next step?

Answer: During development, consider extending the range if the modeling rationale and budget support it, while recording the expanded search. Do not use final-test performance to decide the extension. A boundary result alone does not prove the true optimum lies beyond the grid or that larger values must improve performance.

Five multiple-choice questions

Question 1

What does refit=True do after selection?

  • A. Train on the final-test labels automatically
  • B. Train the chosen configuration on all supplied development data
  • C. Average all fold coefficients

Correct: B. It creates a new fitted best estimator using the full allowed search dataset.

Question 2

What does svc__C identify?

  • A. A class-specific validation score
  • B. A new feature column
  • C. The C parameter of the named svc pipeline step

Correct: C. Double-underscore syntax routes a parameter to a nested component.

Question 3

Does a grid search find the best setting over every possible value?

  • A. No, only among supplied combinations
  • B. Only if the score is accuracy
  • C. Yes, by exhaustive optimization

Correct: A. The candidate space and budget are chosen by the experimenter.

Question 4

Why inspect failed fits?

  • A. They may reveal invalid configurations or numerical problems
  • B. They can be ignored whenever another candidate succeeds
  • C. They prove the entire model family is useless

Correct: A. Failures are part of the evidence and require diagnosis, not concealment.

Question 5

Why is the winning development score selection-influenced?

  • A. Every cross-validation fold contains the final test
  • B. It was chosen as the maximum among noisy candidate estimates
  • C. The estimator cannot process validation data

Correct: B. Selecting a winner can favor favorable estimation noise even when preprocessing boundaries are correct.

Common pitfalls

Do not search an unbounded space without a resource plan. Do not fit preprocessing before fold construction or hide failed candidates. Avoid treating the selected cross-validation maximum as an independently confirmed final score.

Summary

A defensible search is bounded, reproducible, and pipeline-based. Count its fits, choose explicit folds and metrics, inspect all candidate results, and preserve independent assessment for the selected process. Hyperparameter search is part of learning, not a free evaluation step.

Primary sources and further reading