Hyperparameter Tuning: Grid Search, Random Search & Bayesian Optimization

Hyperparameter tuning is one of the most important steps in building high-performing machine learning models. Even when you select the right algorithm and prepare your dataset correctly, the model may still produce poor results because its hyperparameters are not configured properly.

For example, a Random Forest model can behave very differently depending on the number of trees, maximum tree depth, minimum samples required for splitting, and the number of features considered at each split.

Finding the right combination of these settings is called Hyperparameter Tuning.

There are several strategies for searching through possible configurations, but three widely used approaches are:

  1. Grid Search: Exhaustively tests every specified combination.
  2. Random Search: Tests randomly selected combinations.
  3. Bayesian Optimization: Uses previous evaluation results to intelligently select promising configurations.

In this guide, we will understand how each technique works, compare their advantages and disadvantages, and implement them using Python and Scikit-learn.


1. What Are Hyperparameters in Machine Learning?

Hyperparameters are configuration values that control how a machine learning algorithm learns from training data.

Unlike model parameters, which are learned automatically during training, hyperparameters are usually specified before the training process begins.

Model Parameters vs. Hyperparameters

Model ParametersHyperparameters
Learned during trainingConfigured before training
Updated by the learning algorithmSelected through experimentation or optimization
Directly influence predictionsControl the learning process
Examples: weights and biasesExamples: learning rate and tree depth

For example, in linear regression:

\[ y = wx+b \]

The values of \(w\) and \(b\) are model parameters learned during training.

However, in a neural network, the learning rate, batch size, and number of hidden layers are hyperparameters.

Common Hyperparameters Across ML Algorithms

AlgorithmImportant Hyperparameters
Decision Treemax_depth, min_samples_split, criterion
Random Forestn_estimators, max_depth, max_features
XGBoostlearning_rate, max_depth, n_estimators
SVMC, kernel, gamma
KNNn_neighbors, weights, metric
Neural Networkslearning_rate, batch_size, epochs, hidden_layers
Logistic RegressionC, penalty, solver

Choosing appropriate values can improve generalization, reduce overfitting, and make model training more efficient.


2. What Is Hyperparameter Tuning?

Hyperparameter tuning is the process of systematically searching for hyperparameter values that produce the best model performance.

The objective is to identify a configuration that performs well on unseen data rather than simply maximizing training accuracy.

For example, suppose you are training a Random Forest classifier.

You want to experiment with:

  • Number of trees: 50, 100, 200
  • Maximum depth: 5, 10, 20
  • Minimum samples per split: 2, 5, 10

Different combinations can produce different results.

Configurationn_estimatorsmax_depthmin_samples_splitAccuracy
Model A505291.2%
Model B10010294.1%
Model C20020595.3%
Model D10051090.8%

In this example, Configuration C produces the highest validation accuracy.

However, accuracy is not always the correct optimization objective. Depending on the problem, you might optimize F1-score, ROC-AUC, precision, recall, or another suitable metric.

Why Is Hyperparameter Tuning Important?

  1. Improves model performance: Finds configurations that better capture patterns in the data.
  2. Reduces overfitting: Helps control model complexity.
  3. Improves generalization: Identifies settings that perform well on unseen examples.
  4. Optimizes training efficiency: Helps balance model performance and computational cost.
  5. Supports model selection: Makes it easier to compare different configurations systematically.

Grid Search is one of the simplest and most widely used hyperparameter optimization techniques.

It evaluates every possible combination of hyperparameter values specified in a search grid.

Instead of manually trying configurations one by one, Grid Search automatically generates the combinations and evaluates each one using a selected validation strategy.

How Does Grid Search Work?

Suppose you want to tune a Random Forest model using these values:

n_estimators = [50, 100, 200]

max_depth = [5, 10, 20]

Grid Search generates every possible combination.

The total number of combinations is:

\[ N = n_1 \times n_2 \times \cdots \times n_k \]

Where:

  • \(N\) = Total number of configurations.
  • \(n_i\) = Number of candidate values for each hyperparameter.
  • \(k\) = Number of hyperparameters.

For our example:

\[ N = 3 \times 3 = 9 \]

Therefore, Grid Search evaluates nine different configurations.

Grid Search Workflow

Define Hyperparameter Grid
          |
          v
Generate All Combinations
          |
          v
Train Model for Each Combination
          |
          v
Evaluate Using Cross-Validation
          |
          v
Compare Performance Scores
          |
          v
Select Best Configuration
          |
          v
Train Final Model

We will use the Breast Cancer Wisconsin dataset available in Scikit-learn.

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

# Create model
model = RandomForestClassifier(random_state=42)

# Define parameter grid
param_grid = {
    "n_estimators": [50, 100, 200],
    "max_depth": [5, 10, 20],
    "min_samples_split": [2, 5]
}

# Create Grid Search
grid_search = GridSearchCV(
    estimator=model,
    param_grid=param_grid,
    cv=5,
    scoring="accuracy",
    n_jobs=-1,
    verbose=1
)

# Perform hyperparameter tuning
grid_search.fit(X_train, y_train)

# Display best parameters
print("Best Parameters:", grid_search.best_params_)

# Display best cross-validation score
print("Best CV Score:", grid_search.best_score_)

# Evaluate on test data
best_model = grid_search.best_estimator_

y_pred = best_model.predict(X_test)

print("Test Accuracy:", accuracy_score(y_test, y_pred))

Understanding the Code

  • param_grid: Defines the hyperparameter values to evaluate.
  • GridSearchCV: Performs exhaustive search using cross-validation.
  • cv=5: Uses five-fold cross-validation.
  • scoring="accuracy": Selects accuracy as the optimization metric.
  • n_jobs=-1: Uses available CPU cores where supported.
  • best_params_: Returns the best hyperparameter configuration.
  • best_score_: Returns its mean cross-validation score.
  • best_estimator_: Returns the fitted estimator using the selected configuration.
  • Simple to understand and implement.
  • Systematically evaluates all specified combinations.
  • Works well when the search space is small.
  • Provides a clear comparison of candidate configurations.
  • Computationally expensive for large search spaces.
  • Evaluates combinations that may not be useful.
  • Requires candidate values to be defined in advance.
  • Can waste resources when only a few hyperparameters strongly influence performance.

Best Use Case: Grid Search is useful when you have a small number of hyperparameters and a limited search space.


Random Search is another popular hyperparameter optimization technique.

Unlike Grid Search, which evaluates every possible combination, Random Search selects a fixed number of random configurations from the specified search space.

This approach is particularly useful when you have many hyperparameters or a large range of possible values.

How Does Random Search Work?

Suppose you want to tune a Random Forest model.

n_estimators = [50, 100, 150, 200, 250]

max_depth = [5, 10, 15, 20, None]

min_samples_split = [2, 5, 10, 15]

The total number of possible configurations is:

\[ N = 5 \times 5 \times 4 = 100 \]

Grid Search would evaluate all 100 combinations.

However, Random Search might evaluate only 15 randomly selected configurations.

This can significantly reduce computation time.

Random Search Workflow

Define Hyperparameter Search Space
              |
              v
Set Number of Iterations
              |
              v
Randomly Select Configuration
              |
              v
Train and Validate Model
              |
              v
Repeat Until Iterations Complete
              |
              v
Compare Performance Scores
              |
              v
Select Best Configuration
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from scipy.stats import randint

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

# Create model
model = RandomForestClassifier(random_state=42)

# Define parameter distributions
param_distributions = {
    "n_estimators": randint(50, 300),
    "max_depth": [5, 10, 15, 20, None],
    "min_samples_split": randint(2, 15),
    "min_samples_leaf": randint(1, 10)
}

# Create Random Search
random_search = RandomizedSearchCV(
    estimator=model,
    param_distributions=param_distributions,
    n_iter=20,
    cv=5,
    scoring="accuracy",
    random_state=42,
    n_jobs=-1,
    verbose=1
)

# Perform hyperparameter tuning
random_search.fit(X_train, y_train)

# Display best parameters
print("Best Parameters:", random_search.best_params_)

# Display best cross-validation score
print("Best CV Score:", random_search.best_score_)

# Evaluate on test data
best_model = random_search.best_estimator_

y_pred = best_model.predict(X_test)

print("Test Accuracy:", accuracy_score(y_test, y_pred))

Understanding the Code

  • param_distributions: Defines possible values or probability distributions.
  • randint(50, 300): Samples integer values from 50 up to, but not including, 300.
  • n_iter=20: Evaluates 20 sampled configurations.
  • random_state=42: Makes the random sampling reproducible.
  • RandomizedSearchCV: Performs randomized hyperparameter search with cross-validation.

Imagine that a model has ten hyperparameters, but only two have a major influence on its performance.

Grid Search spends resources evaluating every combination across all ten hyperparameters.

Random Search can explore more distinct values of the influential hyperparameters within the same evaluation budget.

This is one reason Random Search can be more efficient in high-dimensional search spaces.

  • Usually faster than exhaustive Grid Search for large spaces.
  • Explores a wider range of values for influential hyperparameters.
  • Supports continuous and discrete distributions.
  • Allows you to control the number of evaluations.
  • Does not guarantee finding the best configuration.
  • Results depend partly on random sampling.
  • May select configurations that perform poorly.
  • Requires choosing an appropriate number of iterations.

Best Use Case: Random Search is useful when the search space is large and you want to explore multiple hyperparameters with a limited computational budget.


Bayesian Optimization is a more advanced optimization technique that uses previous evaluation results to decide which hyperparameter configuration should be tested next.

Unlike Grid Search and Random Search, it does not simply evaluate combinations independently.

Instead, it builds a probabilistic model of the relationship between hyperparameters and model performance.

It then uses this model to identify promising configurations.

How Does Bayesian Optimization Work?

Bayesian Optimization generally involves two important components:

  1. Surrogate Model: An approximate model that predicts the objective function's performance.
  2. Acquisition Function: A strategy that selects the next hyperparameter configuration to evaluate.

The surrogate model helps estimate how well a configuration might perform without training the actual machine learning model every time.

The acquisition function decides whether to explore uncertain regions or exploit configurations that are already predicted to perform well.

Bayesian Optimization Workflow

Define Hyperparameter Search Space
              |
              v
Evaluate Initial Configurations
              |
              v
Build Surrogate Model
              |
              v
Calculate Acquisition Function
              |
              v
Select Next Promising Configuration
              |
              v
Train and Evaluate Actual Model
              |
              v
Update Surrogate Model
              |
              v
Repeat Until Budget Is Exhausted
              |
              v
Return Best Configuration

Understanding the Surrogate Model

A surrogate model approximates the relationship between hyperparameter configurations and their performance.

For example:

Learning RateMaximum DepthObserved Accuracy
0.01389.2%
0.05593.5%
0.10794.1%
0.20991.8%

After observing these results, the surrogate model learns an approximate performance landscape.

It can then predict which unexplored configurations are worth evaluating.

Common surrogate models include:

  • Gaussian Processes.
  • Random Forest-based models.
  • Tree-structured Parzen Estimators (TPE).

The choice depends on the optimization library and the type of search space.

Understanding the Acquisition Function

The acquisition function determines which configuration should be evaluated next.

Common acquisition strategies include:

1. Expected Improvement (EI)

Expected Improvement estimates how much a candidate configuration is expected to improve upon the best result observed so far.

2. Probability of Improvement (PI)

Probability of Improvement estimates the probability that a candidate configuration will outperform the current best result.

3. Upper Confidence Bound (UCB)

Upper Confidence Bound balances predicted performance and uncertainty.

These strategies help Bayesian Optimization balance two important ideas:

  • Exploration: Testing configurations in uncertain regions.
  • Exploitation: Testing configurations expected to perform well.

Python Implementation: Bayesian Optimization Using Optuna

Optuna is a popular Python framework for hyperparameter optimization.

It supports adaptive search strategies, pruning, and efficient experimentation.

Install the required libraries:

pip install optuna scikit-learn

Now implement Bayesian-style optimization using Optuna's Tree-structured Parzen Estimator (TPE) sampler.

import optuna

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split

# Load dataset
data = load_breast_cancer()

X = data.data
y = data.target

# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

# Define objective function
def objective(trial):

    n_estimators = trial.suggest_int(
        "n_estimators", 50, 300
    )

    max_depth = trial.suggest_int(
        "max_depth", 3, 30
    )

    min_samples_split = trial.suggest_int(
        "min_samples_split", 2, 15
    )

    min_samples_leaf = trial.suggest_int(
        "min_samples_leaf", 1, 10
    )

    model = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        min_samples_split=min_samples_split,
        min_samples_leaf=min_samples_leaf,
        random_state=42
    )

    scores = cross_val_score(
        model,
        X_train,
        y_train,
        cv=5,
        scoring="accuracy"
    )

    return scores.mean()


# Create optimization study
study = optuna.create_study(
    direction="maximize",
    sampler=optuna.samplers.TPESampler(seed=42)
)

# Run optimization
study.optimize(objective, n_trials=30)

# Display best configuration
print("Best Parameters:", study.best_params)

print("Best CV Accuracy:", study.best_value)

# Train final model
best_model = RandomForestClassifier(
    **study.best_params,
    random_state=42
)

best_model.fit(X_train, y_train)

# Evaluate on test data
print("Test Accuracy:", best_model.score(X_test, y_test))

Understanding the Code

  • objective(): Defines the machine learning experiment.
  • trial.suggest_int(): Selects integer hyperparameter values.
  • cross_val_score(): Evaluates each configuration using cross-validation.
  • create_study(): Creates an optimization study.
  • direction="maximize": Attempts to maximize the objective score.
  • TPESampler(): Uses a probabilistic model to guide the search.
  • n_trials=30: Runs 30 optimization trials.
  • study.best_params: Returns the best discovered configuration.
  • study.best_value: Returns its objective score.

Important: TPE is a Bayesian optimization approach, but it is not the same as Gaussian Process optimization. Both use probabilistic modeling to guide the search, but they construct their models differently.

Advantages of Bayesian Optimization

  • Uses previous evaluation results to guide future experiments.
  • Can find strong configurations with fewer evaluations.
  • Works well when model training is expensive.
  • Supports complex search spaces through suitable optimization libraries.
  • Can balance exploration and exploitation.

Disadvantages of Bayesian Optimization

  • More complex to understand and configure.
  • Has additional computational overhead for optimization.
  • Performance depends on the surrogate model and acquisition strategy.
  • Can be less effective in some very high-dimensional or highly discontinuous search spaces.

Best Use Case: Bayesian Optimization is especially useful when model evaluations are expensive and you want to make the most of a limited experimentation budget.


6. Grid Search vs. Random Search vs. Bayesian Optimization

All three techniques aim to identify strong hyperparameter configurations, but they use different search strategies.

FeatureGrid SearchRandom SearchBayesian Optimization
Search strategyExhaustiveRandom samplingModel-guided
EvaluationsEvery specified combinationFixed number of samplesSequentially selected trials
Uses previous results to guide searchNoNoYes
Search efficiencyCan be low for large gridsOften better for large spacesOften efficient for expensive evaluations
ImplementationEasyEasyMore complex
Computational costPotentially highControllableDepends on trials and optimization overhead
Best suited forSmall search spacesLarge search spacesExpensive model evaluations

Example Comparison

Suppose you have 100 possible hyperparameter configurations.

TechniqueNumber of EvaluationsSearch Behavior
Grid Search100Tests all configurations
Random Search20Tests 20 random configurations
Bayesian Optimization20Selects 20 configurations using previous results

In this simplified example, Random Search and Bayesian Optimization use fewer evaluations than Grid Search.

However, fewer evaluations do not automatically guarantee better results. The quality of the search space, evaluation metric, sampling strategy, and model all matter.


7. Cross-Validation: Why It Matters During Hyperparameter Tuning

A model may perform well on one validation split but poorly on another.

To reduce dependence on a single split, hyperparameter tuning commonly uses cross-validation.

In K-Fold Cross-Validation, the training dataset is divided into K subsets.

The model is trained K times, using a different subset for validation in each iteration.

For example, with five-fold cross-validation:

Dataset
   |
   v
+------+------+------+------+------+
| Fold1| Fold2| Fold3| Fold4| Fold5|
+------+------+------+------+------+

Iteration 1: Validate on Fold 1
Iteration 2: Validate on Fold 2
Iteration 3: Validate on Fold 3
Iteration 4: Validate on Fold 4
Iteration 5: Validate on Fold 5

The average score is calculated as:

\[ CV\ Score = \frac{1}{K}\sum_{i=1}^{K} Score_i \]

For example, if the five validation scores are:

92%, 94%, 93%, 95%, 91%

Then:

\[ CV\ Score = \frac{92+94+93+95+91}{5} \]

\[ CV\ Score = 93\% \]

This provides a more reliable estimate of model performance than relying on a single validation split.

Which Cross-Validation Strategy Should You Use?

  • K-Fold: General-purpose problems with reasonably independent observations.
  • Stratified K-Fold: Classification problems where class proportions should be preserved.
  • Group K-Fold: Data containing related observations that must stay together.
  • Time Series Split: Time-dependent data where future observations must not influence past predictions.

The cross-validation strategy should match the structure of your dataset.


8. Important Mistakes to Avoid During Hyperparameter Tuning

Hyperparameter tuning can produce misleading results when the evaluation process is not designed correctly.

1. Using Test Data During Tuning

The test dataset should not be used to select hyperparameters.

Repeatedly checking test performance and changing model settings based on it causes information leakage.

Correct approach:

Complete Dataset
      |
      v
Training Dataset
      |
      v
Cross-Validation
      |
      v
Hyperparameter Selection
      |
      v
Final Model Training
      |
      v
Untouched Test Dataset
      |
      v
Final Evaluation

Keep the test dataset untouched until the final evaluation.

2. Searching Too Many Hyperparameters at Once

A large search space can increase computational cost significantly.

Start with the most influential hyperparameters and expand the search when necessary.

3. Choosing the Wrong Evaluation Metric

Accuracy is not always appropriate.

For an imbalanced fraud detection dataset, recall, precision, F1-score, or PR-AUC may be more useful depending on the business objective.

4. Ignoring Data Leakage During Preprocessing

Preprocessing operations such as feature scaling, imputation, and feature selection should be fitted inside the cross-validation process.

Use Scikit-learn Pipelines to ensure that preprocessing is learned only from each training fold.

5. Ignoring Computational Resources

A five-fold cross-validation search with 100 configurations can require approximately:

\[ 100 \times 5 = 500 \]

model fits.

Large models and datasets can make this expensive.

Choose the number of trials and parallel workers according to available resources.

6. Assuming the Best Score Guarantees the Best Production Model

A high cross-validation score does not guarantee strong real-world performance.

Always consider:

  • Data distribution changes.
  • Inference latency.
  • Model size.
  • Prediction stability.
  • Business requirements.

9. Practical Best Practices for Hyperparameter Tuning

For an efficient tuning workflow, follow these recommendations:

  1. Establish a baseline model before tuning.
  2. Choose an evaluation metric that matches the business problem.
  3. Use a suitable cross-validation strategy.
  4. Start with Random Search for large search spaces.
  5. Use Grid Search when the candidate space is small.
  6. Consider Bayesian Optimization when model evaluations are expensive.
  7. Use logarithmic search spaces for parameters such as learning rates and regularization strengths when appropriate.
  8. Apply preprocessing through Scikit-learn Pipelines.
  9. Record experiments and compare configurations.
  10. Evaluate the final selected model on an untouched test dataset.

A Practical Model Optimization Strategy

A useful real-world workflow is:

Step 1: Train Baseline Model
              |
              v
Step 2: Identify Important Hyperparameters
              |
              v
Step 3: Run Random Search
              |
              v
Step 4: Narrow Down Search Space
              |
              v
Step 5: Apply Bayesian Optimization
              |
              v
Step 6: Validate Best Configuration
              |
              v
Step 7: Train Final Model
              |
              v
Step 8: Evaluate on Test Data
              |
              v
Step 9: Save and Deploy Model

This combines broad exploration with more targeted optimization.

It is a practical strategy, not a mandatory sequence. For a small search space, Grid Search may be sufficient without the additional stages.


10. Real-World Applications of Hyperparameter Tuning

Hyperparameter tuning is used across different machine learning applications.

ApplicationImportant HyperparametersPossible Evaluation Metrics
Fraud Detectionmax_depth, learning_rate, class_weightRecall, F1, PR-AUC
Recommendation Systemsembedding_dim, regularization, learning_ratePrecision@K, Recall@K, NDCG
Image Classificationbatch_size, learning_rate, epochsAccuracy, F1
Customer Churn Predictionn_estimators, max_depth, min_samples_leafRecall, ROC-AUC
Stock Price Forecastingwindow_size, learning_rate, hidden_unitsMAE, RMSE
Spam DetectionC, kernel, n_neighborsPrecision, Recall, F1

The best tuning strategy depends on model complexity, dataset size, available computing resources, and the cost of each model evaluation.


11. Frequently Asked Questions (FAQs)

Q1. What is hyperparameter tuning in machine learning?

Hyperparameter tuning is the process of selecting suitable configuration values for a machine learning algorithm to improve its performance and generalization.

Q2. What is the difference between model parameters and hyperparameters?

Model parameters are learned automatically during training, whereas hyperparameters control the learning process and are configured before or around training.

Q3. Is Grid Search better than Random Search?

Not always. Grid Search evaluates every specified combination, while Random Search explores selected configurations. Random Search is often more efficient when the search space is large.

Q4. Why is Bayesian Optimization considered intelligent search?

It uses results from previous experiments to build a probabilistic model and select promising configurations for future evaluations.

Q5. What is the difference between Grid Search CV and Randomized Search CV?

GridSearchCV evaluates all combinations in a specified grid, while RandomizedSearchCV evaluates a fixed number of sampled configurations. Both can use cross-validation.

Q6. Which hyperparameter tuning technique should beginners learn first?

Start with Grid Search to understand systematic search, then learn Random Search and Bayesian Optimization for larger and more complex search spaces.

Q7. Can hyperparameter tuning cause overfitting?

Yes. Excessive optimization against a limited validation process can overfit the validation data. Use appropriate cross-validation and keep a separate test dataset for final evaluation.

Q8. What is Optuna used for?

Optuna is a Python optimization framework used to automate hyperparameter search. It supports samplers such as TPE, pruning, and experiment management.

Q9. Does hyperparameter tuning always improve model accuracy?

No. It may improve performance, but results depend on data quality, model choice, search space, and evaluation strategy. Tuning can also increase computational cost without meaningful improvement.

Q10. What is the difference between Bayesian Optimization and Grid Search?

Grid Search evaluates predefined combinations independently. Bayesian Optimization uses previous evaluation results to guide the selection of subsequent configurations.


Conclusion

Hyperparameter tuning plays a major role in developing reliable and high-performing machine learning models.

Grid Search, Random Search, and Bayesian Optimization offer different ways to explore hyperparameter configurations.

  • Grid Search is straightforward and effective for small search spaces.
  • Random Search provides broader exploration with a controlled number of evaluations.
  • Bayesian Optimization uses previous experiments to guide future evaluations and can be valuable when model training is expensive.

There is no universally best optimization technique. The right choice depends on the size of the search space, computational resources, model complexity, and evaluation requirements.

A strong machine learning workflow does not simply search for the highest score. It identifies a configuration that generalizes well, performs reliably on unseen data, and meets real-world requirements.

Remember: The goal of hyperparameter tuning is not to make a model memorize the training dataset. It is to help the model learn patterns that generalize to new data.


Author: Kulbhushan Pukale
Category: AI & Machine Learning