Knowledge / Artificial Intelligence and Data Science / Hyperparameter tuning and AutoML

Hyperparameter tuning and AutoML

Artificial Intelligence and Data Science (B.E./B.Tech) · Advanced learning methods · free study notes for exams, placements and interviews

In short

Hyperparameters are the settings chosen *before* training (learning rate, tree depth, number of layers, regularisation strength); parameters are the weights learned *during* training. Hyperparameter tuning is the search for the setting that minimises validation error, and AutoML automates the whole pipeline - preprocessing, feature engineering, model choice, tuning and sometimes architecture design. It decides whether a model that is theoretically right actually performs, so it carries marks in machine-learning and data-science papers (AICTE model curriculum AI&DS, UGC CBCS electives) and appears in GATE DA (Data Science and AI, introduced 2024) through cross-validation, bias-variance and model selection. In Indian hiring - TCS, Infosys, Wipro, Mu Sigma, Fractal, Swiggy, Zomato, PhonePe, Razorpay, Flipkart, Jio, product teams at Google and Microsoft India - the standard interview question is "how did you tune it, and how do you know you did not overfit the validation set?"

Explained

Parameters versus hyperparameters, and the three-way data split

Validation strategies that tuning rests on

Search strategies

  1. Manual / graduate-student search: tune by intuition, one knob at a time. Not reproducible; still the most common in practice.
  2. Grid search: full Cartesian product of discrete values. Exhaustive, embarrassingly parallel, but cost is exponential in dimensions - the curse of dimensionality. With 5 values on 6 hyperparameters and 5-fold CV that is 5⁶ × 5 = 78,125 fits.
  3. Random search: sample each hyperparameter from a distribution (log-uniform for learning rate and regularisation). Bergstra and Bengio (2012) showed it beats grid search at equal budget because only a few hyperparameters matter - the low effective dimensionality argument; a grid wastes trials repeating the same value of the important knob.
  4. Bayesian optimisation (SMBO): build a cheap surrogate of the validation-error landscape (Gaussian process, or TPE - Tree-structured Parzen Estimator in Optuna/Hyperopt, or random forest in SMAC), then pick the next point by maximising an acquisition function - Expected Improvement, Probability of Improvement, or Upper/Lower Confidence Bound - which balances exploitation (near the best point) against exploration (where variance is high). Sequential, so less parallel, but far fewer trials.
  5. Successive halving (SHA): start n configurations with a small budget (few epochs, subsample, few trees), keep the best 1/η, multiply the budget by η, repeat. Hyperband runs several brackets of successive halving with different starting n to hedge the budget-vs-breadth trade-off; ASHA/BOHB add asynchrony and a Bayesian model.
  6. Population-based: genetic algorithms and evolutionary search (TPOT evolves whole pipelines), Population Based Training (PBT) copies weights from good workers and perturbs their hyperparameters mid-training, and CMA-ES for continuous spaces.
  7. Gradient-based / hypergradient: differentiate validation loss with respect to continuous hyperparameters; used in DARTS-style architecture search.
  8. Early stopping as a tuner: monitor validation loss with patience, restore the best weights - this tunes the "number of epochs" hyperparameter for free.

What to tune, and typical ranges

FamilyKey hyperparametersUsual search scale
Linear / logisticC or λ (L1, L2, elastic-net ratio)log scale, 1e-4 to 1e+4
SVMC, kernel, γlog scale both
k-NNk, distance metric, weightinginteger 1-50
Decision treemax_depth, min_samples_leaf, criterionsmall integers
Random forestn_estimators, max_features, max_depthmore trees never hurts accuracy, only time
XGBoost / LightGBMlearning_rate (eta), n_estimators, max_depth / num_leaves, subsample, colsample_bytree, min_child_weight, lambda, alpha, scale_pos_weighteta log scale; eta and n_estimators traded off
Neural networklearning rate (most important), batch size, optimiser, weight decay, dropout, layers, units, LR schedule, warm-upLR log-uniform 1e-5 to 1e-1
k-means / clusteringk, init, linkageelbow / silhouette

AutoML: scope, components, tools

Practice, cost and Indian context

Key points

Formulas and examples

Grid search cost: N_fits = (∏ᵢ kᵢ) × F, where kᵢ = number of values for hyperparameter i, F = CV folds. Unit: model fits.
Random search guarantee: P(at least one sample in the best p fraction of the space) = 1 − (1 − p)ⁿ, n = number of trials.
Trials needed: n ≥ log(1 − P) / log(1 − p).
k-fold CV estimate: CV_error = (1/k) Σ₍ᵢ₌₁..k₎ Eᵢ, with standard error SE = s/√k, s = sample SD of the k fold errors.
Expected Improvement: EI(x) = E[max(0, f_best − f(x))] - the acquisition function maximised to choose the next trial.
Upper/Lower confidence bound: a(x) = μ(x) − κ·σ(x) for minimisation; κ controls exploration.
Successive halving: rounds R = ⌊log_η(n)⌋ + 1; survivors after round r = ⌈n/ηʳ⌉; η = reduction factor (commonly 3).
Hyperband total budget per bracket ≈ B = n × r (configs × resource per config), repeated over brackets.
Step LR decay: ηₜ = η₀ × γ^⌊t/s⌋. Cosine annealing: ηₜ = η_min + ½(η₀ − η_min)(1 + cos(πt/T)).
Bias-variance decomposition: E[(y − f̂)²] = Bias²(f̂) + Var(f̂) + σ² (irreducible noise).
Compute cost: Cost (₹) = trials × avg minutes per trial / 60 × rate per hour (₹/h).

Example 1 - grid versus random cost. An XGBoost grid: eta {0.01, 0.05, 0.1}, max_depth {3, 5, 7, 9}, subsample {0.6, 0.8, 1.0}, colsample {0.6, 0.8, 1.0}, with 5-fold CV.

Example 2 - how many random trials. Probability of landing in the top 5% of the configuration space.

Example 3 - reading a 5-fold CV result. Two configurations on a churn dataset, F1 per fold:

ConfigF1 by foldMeanSDSE
A (eta 0.10, depth 5)0.812, 0.798, 0.825, 0.805, 0.8100.81000.01000.0045
B (eta 0.05, depth 7)0.818, 0.790, 0.830, 0.796, 0.8160.81000.01660.0074

Example 4 - successive halving budget. n = 81 configurations, η = 3, starting budget 1 epoch.

Example 5 - rupee cost of a sweep. 150 Optuna trials, average 8 minutes per trial, 4 parallel GPU workers at ₹250 per GPU-hour.

import optuna
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.ensemble import HistGradientBoostingClassifier

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

def objective(trial):
    params = dict(
        learning_rate=trial.suggest_float("learning_rate", 1e-3, 3e-1, log=True),
        max_leaf_nodes=trial.suggest_int("max_leaf_nodes", 15, 255, log=True),
        l2_regularization=trial.suggest_float("l2", 1e-8, 10.0, log=True),
        max_iter=600, early_stopping=True, random_state=42,
    )
    pipe = Pipeline([                      # fitted inside each fold - no leakage
        ("imp", SimpleImputer(strategy="median")),
        ("sc", StandardScaler()),
        ("clf", HistGradientBoostingClassifier(**params)),
    ])
    return cross_val_score(pipe, X_tr, y_tr, cv=cv, scoring="f1").mean()

study = optuna.create_study(direction="maximize",
                            sampler=optuna.samplers.TPESampler(seed=42),
                            pruner=optuna.pruners.HyperbandPruner())
study.optimize(objective, n_trials=150, timeout=3600)
print(study.best_params, round(study.best_value, 4))   # test set touched only now
MethodTrials neededParallelHandles conditional spaceTypical use
Grid searchVery highFullyPoorly≤ 3 hyperparameters, small models
Random searchModerateFullyYesDefault baseline, any dimension
Bayesian (TPE/GP)LowPartlyYesExpensive trials, ≤ ~20 dims
Hyperband/ASHALow per trialFullyYesDeep nets, iterative learners
Evolutionary/PBTHighFullyYesWhole pipelines, RL, long training
Full AutoMLFramework-setFullyYesTabular baselines, non-experts

Where it is used

Interview questions

Common mistakes

Related topics

Semi-supervised and self-supervised learning · Multimodal AI · Model evaluation metrics and cross-validation · Regularisation and the bias-variance trade-off · Ensemble methods: bagging, boosting and stacking · MLOps, experiment tracking and model deployment

Open in the Knowledge reader →Find jobs →