πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Hyperparameter tuning and experiment comparison enable us to systematically optimize model performance while maintaining full reproducibility and traceability of every training run.

Mastering these practices with tools like MLflow helps build reliable, data-driven model selection workflows that scale from experimentation to production.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ“š Key Learnings

  • Understand the hyperparameter search problem and why it matters
  • Run Grid Search with cross-validation using scikit-learn
  • Run Random Search over 10 hyperparameter combinations
  • Log every search combination as a separate MLflow run
  • Compare experiments in the MLflow UI and identify the best run

LearnXOps Labs:


🧠 Learn here

Why Hyperparameter Tuning Matters

Every ML model has two kinds of knobs: parameters learned from data (like neural network weights or Random Forest split thresholds) and hyperparameters you set before training β€” things like the number of trees, max depth, or learning rate. The model itself can't learn hyperparameters. You have to search for them.

The problem is exponential. A Random Forest with just 5 hyperparameters, each with 5 possible values, creates 5⁡ = 3,125 possible combinations. Trying them all is possible but expensive. The question MLOps engineers answer every day is: how do I search this space efficiently without wasting compute, and how do I track what I've tried so nothing is lost?

Hyperparameters you set, such as n_estimators and max_depth, feed RandomForest.fit, which learns the parameters such as split thresholds and produces the cross-validated accuracy.
Hyperparameters vs Parameters: what you control vs what the model learns

scikit-learn provides two primary search strategies, each with a fundamentally different philosophy about how to explore the hyperparameter space. Knowing when to use each one is a core MLOps skill.

Grid search evaluates all 36 points of a 6 by 6 grid; random search samples 10 points from the same space and covers more distinct values.
Grid Search evaluates every point; Random Search samples strategically. Same compute budget β†’ more coverage with Random.
FeatureGridSearchCV (Exhaustive Search)RandomizedSearchCV (Efficient Search)
Search StrategyTries every combination of provided parameter valuesRandomly samples n_iter combinations from parameter distributions
CoverageExhaustiveNon-exhaustive but statistically near-optimal
Best ParametersGuaranteed to find the best combination within the gridHigh probability of finding near-optimal parameters
Computation CostNumber of fits grows multiplicativelyFixed compute budget
Total Fits(values₁ Γ— valuesβ‚‚ Γ— ... ) Γ— cv_foldsn_iter Γ— cv_folds
Example5 Γ— 4 Γ— 3 = 60 combinations Γ— 5 folds = 300 fits20 iterations Γ— 5 folds = 100 fits
ScalabilitySuitable for small, well-constrained search spacesExcellent for large, high-dimensional spaces
Continuous ParametersRequires manually specifying discrete valuesCan sample from continuous distributions (e.g., log-uniform)
EfficiencyCan become very expensive when training is slow or grid size is largeMuch more computationally efficient
Parameter ImportanceTreats all combinations equallyFocuses on exploring the search space efficiently
When to UseSmall number of hyperparameters and valuesLarge search spaces or limited compute resources
PerformanceFinds the exact optimum in the specified gridOften achieves comparable performance with far fewer evaluations
Research SupportClassical exhaustive approachShown by Bergstra & Bengio (2012) to be as effective as grid search with significantly fewer evaluations
Recommended ForSimpler models and smaller datasetsComplex models and large datasets

Project Setup & Dependencies

We'll continue with our running Iris classifier project. The structure adds a dedicated tuning module that integrates cleanly with the MLflow tracking we built in earlier days.

iris-mlops/
β”œβ”€β”€ mlruns/                    # MLflow tracking dir (auto-created)
β”œβ”€β”€ data/
β”‚   └── iris.csv
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ data_loader.py
β”‚   β”œβ”€β”€ train.py              # Days 8-9 training scripts
β”‚   β”œβ”€β”€ tune_grid.py          # NEW: grid search
β”‚   └── tune_random.py        # NEW: random search + MLflow
β”œβ”€β”€ notebooks/
β”‚   └── compare_experiments.ipynb
└── requirements.txt


requirements.txt

mlflow==2.14.1
scikit-learn==1.5.0
pandas==2.2.2
numpy==1.26.4
matplotlib==3.9.0
pip install -r requirements.txt

GridSearchCV with MLflow Logging

We first build a Grid Search baseline. GridSearchCV wraps your estimator, runs cross-validation for every combination, and exposes the best parameters. We then manually log each CV result as a separate MLflow run so you can inspect every combination β€” not just the winner.

MLOps Best Practice
Log all hyperparameter combinations, not just the best. The comparison data is gold β€” it tells you which parameters are actually sensitive (high variance in scores) and which ones don't matter much.

src/tune_grid.py

"""
Day 10 β€” Grid Search with MLflow Logging
Each hyperparameter combination is logged as a separate MLflow run
within the 'iris-grid-search' experiment.
"""

import mlflow
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import accuracy_score, f1_score
import warnings
warnings.filterwarnings('ignore')

# ── 1. Load and split data ────────────────────────────────────────
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# ── 2. Define the parameter grid ─────────────────────────────────
param_grid = {
    'n_estimators':     [50, 100, 200],
    'max_depth':        [None, 3, 5, 10],
    'min_samples_split': [2, 5],
}
# 3 Γ— 4 Γ— 2 = 24 combinations Γ— 5 folds = 120 total fits

# ── 3. Run Grid Search ───────────────────────────────────────────
grid_search = GridSearchCV(
    estimator=RandomForestClassifier(random_state=42),
    param_grid=param_grid,
    cv=5,
    scoring='accuracy',
    n_jobs=-1,
    verbose=0,
    return_train_score=True
)
grid_search.fit(X_train, y_train)

# ── 4. Log every combination to MLflow ──────────────────────────
mlflow.set_experiment("iris-grid-search")

cv_results = grid_search.cv_results_

for i in range(len(cv_results['params'])):
    params       = cv_results['params'][i]
    mean_cv_acc  = cv_results['mean_test_score'][i]
    std_cv_acc   = cv_results['std_test_score'][i]
    mean_fit_time= cv_results['mean_fit_time'][i]
    rank         = cv_results['rank_test_score'][i]

    with mlflow.start_run(run_name=f"grid-combo-{i+1:02d}"):
        # Tag the search type for easy filtering
        mlflow.set_tag("search_type", "grid_search")
        mlflow.set_tag("cv_rank", str(rank))

        # Log hyperparameters
        mlflow.log_params({
            "n_estimators":      params.get("n_estimators"),
            "max_depth":         str(params.get("max_depth")),
            "min_samples_split": params.get("min_samples_split"),
        })

        # Log CV metrics
        mlflow.log_metrics({
            "cv_accuracy_mean": round(mean_cv_acc, 4),
            "cv_accuracy_std":  round(std_cv_acc, 4),
            "mean_fit_time_s":  round(mean_fit_time, 4),
        })

# ── 5. Evaluate best estimator on test set ──────────────────────
best_model = grid_search.best_estimator_
y_pred     = best_model.predict(X_test)
test_acc   = accuracy_score(y_test, y_pred)
test_f1    = f1_score(y_test, y_pred, average='macro')

print(f"\nβœ“ Grid Search complete: {len(cv_results['params'])} combinations logged")
print(f"  Best CV accuracy : {grid_search.best_score_:.4f}")
print(f"  Best params      : {grid_search.best_params_}")
print(f"  Test accuracy    : {test_acc:.4f}")
print(f"  Test F1 (macro)  : {test_f1:.4f}")
Common Mistake
Many engineers only log the winning combination. But logging all combinations enables powerful comparisons: which parameters are most sensitive? Is the best model stable (low std) or lucky? The MLflow UI's parallel coordinates plot becomes much more useful with many runs.

RandomizedSearchCV: 10 Combinations, Full MLflow

This is the core exercise for Day 10. We use RandomizedSearchCV with n_iter=10, sampling from probability distributions rather than discrete grids. Every combination becomes a named MLflow run with full parameter and metric logging.

HyperparameterSearch DistributionRationaleBest Found
n_estimatorsrandint(50, 300)More trees = more stable, diminishing returns above ~200200 best
max_depth[None, 3, 5, 7, 10, 15]None = fully grown; shallow trees prevent overfittingNone best
min_samples_splitrandint(2, 15)Minimum samples to split a node; higher = smoother2 default
min_samples_leafrandint(1, 10)Minimum samples in a leaf; acts as regularizer1 default
max_features['sqrt', 'log2', None]Features per split; sqrt is the classic RF choicesqrt default
criterion['gini', 'entropy', 'log_loss']Split quality measure; gini is faster, entropy more info-richgini default
bootstrap[True, False]Whether to bootstrap samples when building treesTrue default

src/tune_random.py β€” Complete Random Search + MLflow

"""
Day 10 β€” Randomized Hyperparameter Search with MLflow
Exercise: Run 10 combinations, log all to MLflow, compare in UI.
"""

import mlflow
import mlflow.sklearn
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import (
    RandomizedSearchCV, train_test_split, cross_val_score
)
from sklearn.metrics import (
    accuracy_score, f1_score,
    precision_score, recall_score
)
from scipy.stats import randint
import warnings
warnings.filterwarnings('ignore')

# ────────────────────────────────────────────────────────────────
# 1. Data preparation
# ────────────────────────────────────────────────────────────────
iris = load_iris()
X, y = iris.data, iris.target
feature_names = iris.feature_names
class_names   = iris.target_names

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.2,
    random_state=42,
    stratify=y   # preserves class proportions
)

print(f"Train: {X_train.shape} | Test: {X_test.shape}")

# ────────────────────────────────────────────────────────────────
# 2. Define the hyperparameter distributions
# ────────────────────────────────────────────────────────────────
param_distributions = {
    'n_estimators':      randint(50, 300),
    'max_depth':         [None, 3, 5, 7, 10, 15],
    'min_samples_split': randint(2, 15),
    'min_samples_leaf':  randint(1, 10),
    'max_features':      ['sqrt', 'log2', None],
    'criterion':         ['gini', 'entropy', 'log_loss'],
    'bootstrap':         [True, False],
}

# ────────────────────────────────────────────────────────────────
# 3. Run Randomized Search (n_iter=10 combinations)
# ────────────────────────────────────────────────────────────────
random_search = RandomizedSearchCV(
    estimator=RandomForestClassifier(random_state=42),
    param_distributions=param_distributions,
    n_iter=10,            # exactly 10 combos β†’ 50 total fits (10 Γ— 5-fold)
    cv=5,
    scoring='accuracy',
    n_jobs=-1,
    random_state=42,     # reproducible sampling
    verbose=1,
    return_train_score=True,
)
random_search.fit(X_train, y_train)

# ────────────────────────────────────────────────────────────────
# 4. Log EVERY combination as a separate MLflow run
# ────────────────────────────────────────────────────────────────
mlflow.set_experiment("iris-random-search")

cv_results     = random_search.cv_results_
best_cv_score  = random_search.best_score_
best_run_id    = None

print(f"\n{'─'*60}")
print("Logging 10 combinations to MLflow...")
print(f"{'─'*60}")

for i in range(10):
    params        = cv_results['params'][i]
    mean_cv       = cv_results['mean_test_score'][i]
    std_cv        = cv_results['std_test_score'][i]
    mean_train    = cv_results['mean_train_score'][i]
    fit_time      = cv_results['mean_fit_time'][i]
    score_time    = cv_results['mean_score_time'][i]
    rank          = cv_results['rank_test_score'][i]
    is_best = (i == random_search.best_index_)  # unique even when scores tie

    # Evaluate this specific combination on test set
    model = RandomForestClassifier(**params, random_state=42)
    model.fit(X_train, y_train)
    y_pred    = model.predict(X_test)
    test_acc  = accuracy_score(y_test, y_pred)
    test_f1   = f1_score(y_test, y_pred, average='macro')
    test_prec = precision_score(y_test, y_pred, average='macro')
    test_rec  = recall_score(y_test, y_pred, average='macro')
    overfit   = round(mean_train - mean_cv, 4)

    run_name = f"random-combo-{i+1:02d}{'⭐' if is_best else ''}"

    with mlflow.start_run(run_name=run_name) as run:
        # Tags for filtering and sorting in the UI
        mlflow.set_tags({
            "search_type":  "random_search",
            "cv_rank":      str(rank),
            "is_best":      str(is_best),
            "model_type":   "RandomForestClassifier",
            "dataset":      "iris",
            "day":          "10",
        })

        # Hyperparameters
        mlflow.log_params({
            "n_estimators":      params.get("n_estimators"),
            "max_depth":         str(params.get("max_depth")),
            "min_samples_split": params.get("min_samples_split"),
            "min_samples_leaf":  params.get("min_samples_leaf"),
            "max_features":      str(params.get("max_features")),
            "criterion":         params.get("criterion"),
            "bootstrap":         str(params.get("bootstrap")),
            "cv_folds":          5,
        })

        # CV metrics (cross-validation, not test set)
        mlflow.log_metrics({
            "cv_accuracy_mean":  round(mean_cv, 4),
            "cv_accuracy_std":   round(std_cv, 4),
            "cv_train_accuracy": round(mean_train, 4),
            "overfit_gap":       overfit,
        })

        # Test set metrics
        mlflow.log_metrics({
            "test_accuracy":   round(test_acc, 4),
            "test_f1_macro":   round(test_f1, 4),
            "test_precision":  round(test_prec, 4),
            "test_recall":     round(test_rec, 4),
        })

        # Timing metrics
        mlflow.log_metrics({
            "mean_fit_time_s":   round(fit_time, 4),
            "mean_score_time_s": round(score_time, 4),
        })

        # Log model artifact for the best run only
        if is_best:
            mlflow.sklearn.log_model(
                model,
                "model",
                registered_model_name="iris-best-random-forest"
            )
            best_run_id = run.info.run_id

        status = "⭐ BEST" if is_best else f"rank {rank}"
        print(f"  Run {i+1:02d} | CV: {mean_cv:.4f}Β±{std_cv:.4f} | "
              f"Test: {test_acc:.4f} | {status}")

# ────────────────────────────────────────────────────────────────
# 5. Summary
# ────────────────────────────────────────────────────────────────
print(f"\n{'═'*60}")
print("RANDOM SEARCH COMPLETE")
print(f"  Best CV accuracy  : {random_search.best_score_:.4f}")
print(f"  Best params       : {random_search.best_params_}")
print(f"  Best MLflow run   : {best_run_id}")
print(f"  View in UI        : mlflow ui")
print(f"{'═'*60}\n")

The Full Tuning Pipeline

Understanding how all the pieces connect β€” from raw data to the MLflow UI β€” is what separates a one-off experiment from a reproducible, auditable MLOps workflow. Here's the complete flow:

Load data, define the search space, run RandomizedSearchCV with 10 combinations and 5 folds, log 10 MLflow runs, compare in the UI; each run holds params, CV metrics, test metrics and tags.
Full tuning pipeline: from data load to 10 tracked MLflow runs
  • Run the random search
    • Execute python src/tune_random.py.
    • This runs RandomizedSearchCV with 10 combinations Γ— 5-fold CV = 50 model fits.
    • The output prints a line for each combination as it is logged.
  • Launch the MLflow UI
    • Run mlflow ui in your project root.
    • Open http://127.0.0.1:5000.
    • Select the iris-random-search experiment to view all 10 runs in a table.
  • Sort by cv_accuracy_mean
    • Click the cv_accuracy_mean column header to sort in descending order.
    • The top run represents the best hyperparameter combination.
    • Check cv_accuracy_std; a lower standard deviation indicates a more stable model across folds.
  • Open the Parallel Coordinates chart
    • In the MLflow UI, select the runs, click Compare β†’ Parallel Coordinates Plot.
    • This visualizes how different hyperparameter values affect cross-validation accuracy.
    • Crossing lines can reveal interactions between parameters.
  • Register the best model
    • Open the best run and click Register Model.
    • Name the model iris-best-random-forest.

This step is already automated in the script using:

mlflow.sklearn.log_model(
    model,
    "model",
    registered_model_name="iris-best-random-forest",
)

Expected Output & Metrics

When you run the random search script, you'll see console output like this for each of the 10 combinations:

Train: (120, 4) | Test: (30, 4)
Fitting 5 folds for each of 10 candidates...

────────────────────────────────────────────────────────────
Logging 10 combinations to MLflow...
────────────────────────────────────────────────────────────
  Run 01 | CV: 0.9500Β±0.0354 | Test: 0.9667 | rank 8
  Run 02 | CV: 0.9667Β±0.0298 | Test: 0.9667 | rank 2
  Run 03 | CV: 0.9500Β±0.0272 | Test: 0.9333 | rank 8
  Run 04 | CV: 0.9583Β±0.0236 | Test: 0.9667 | rank 5
  Run 05 | CV: 0.9583Β±0.0314 | Test: 0.9667 | rank 5
  Run 06 | CV: 0.9750±0.0204 | Test: 1.0000 | ⭐ BEST
  Run 07 | CV: 0.9583Β±0.0204 | Test: 0.9667 | rank 5
  Run 08 | CV: 0.9667Β±0.0272 | Test: 0.9667 | rank 2
  Run 09 | CV: 0.9250Β±0.0354 | Test: 0.9000 | rank 10
  Run 10 | CV: 0.9667Β±0.0216 | Test: 0.9667 | rank 2

════════════════════════════════════════════════════════════
RANDOM SEARCH COMPLETE
  Best CV accuracy  : 0.9750
  Best params       : {'n_estimators': 200, 'max_depth': None,
                       'min_samples_split': 2, 'min_samples_leaf': 1,
                       'max_features': 'sqrt', 'criterion': 'gini',
                       'bootstrap': True}
  Best MLflow run   : a1b2c3d4e5f6...
  View in UI        : mlflow ui
════════════════════════════════════════════════════════════

Cross-validation is the backbone of reliable hyperparameter search. Without it, you risk choosing parameters that happen to work well on one particular train-test split β€” not on the underlying distribution.

Five rounds of 5-fold cross-validation, each holding out a different fold for validation; the mean and standard deviation of the five scores are reported.
Each hyperparameter combination is evaluated across 5 different train/validate splits. The mean score is the reported cv_accuracy_mean.
  • ΞΌ cv_accuracy_mean
    • Average accuracy across the 5 validation folds.
    • This is the primary ranking metric; a higher mean indicates better generalization.
    • Target: > 0.96 for the Iris dataset.
  • Οƒ cv_accuracy_std
    • Standard deviation of accuracy across the 5 folds.
    • A low value (e.g., Β±0.02) indicates stable predictions.
    • A high value (e.g., Β±0.05 or more) suggests the model is sensitive to the training data and may be less reliable in production.
  • Ξ” overfit_gap
    • Difference between training accuracy and cross-validation accuracy.
    • An overfit gap > 0.05 indicates the model may have memorized the training data.
    • Pay special attention when using max_depth=None and min_samples_split=2, as fully grown trees tend to overfit.
  • T test_accuracy
    • Final accuracy measured on the 30 Iris samples that were never used during hyperparameter search.
    • Evaluated only after selecting the best model based on cross-validation results.
    • If test accuracy >> CV accuracy, the result may be due to luck.
    • If test accuracy < CV accuracy, the test set is likely more challenging than expected.

Identifying the Best Run in the UI

Once your 10 runs are logged, the MLflow UI gives you several powerful ways to compare and rank them. Here's exactly what to do:

Table of iris-random-search runs sorted by cv_accuracy_mean: random-combo-06 leads at 0.9750, three runs tie at 0.9667, random-combo-09 is last at 0.9250.
MLflow UI after logging 10 random search runs, sorted by cv_accuracy_mean descending

Query Results via the MLflow API

You don't have to click through the UI to find the best run. MLflow's Python API lets you query, sort, and compare runs programmatically β€” critical for CI/CD pipelines that need to auto-promote the best model.

notebooks/compare_experiments.py

import mlflow
import pandas as pd

# ── Load all runs from the experiment ────────────────────────────
experiment = mlflow.get_experiment_by_name("iris-random-search")
runs = mlflow.search_runs(
    experiment_ids=[experiment.experiment_id],
    order_by=["metrics.cv_accuracy_mean DESC"]
)

# ── Pull the columns we care about ───────────────────────────────
summary = runs[[
    'tags.mlflow.runName',
    'params.n_estimators',
    'params.max_depth',
    'params.criterion',
    'metrics.cv_accuracy_mean',
    'metrics.cv_accuracy_std',
    'metrics.test_accuracy',
    'metrics.overfit_gap',
    'run_id',
]].copy()

summary.columns = [
    'run_name', 'n_est', 'max_depth', 'criterion',
    'cv_acc', 'cv_std', 'test_acc', 'overfit', 'run_id'
]

print(summary.to_string(index=False))

# ── Get the best run object ───────────────────────────────────────
best_run    = runs.iloc[0]
best_run_id = best_run['run_id']
best_cv     = best_run['metrics.cv_accuracy_mean']

print(f"\nπŸ† Best Run ID    : {best_run_id}")
print(f"   CV Accuracy    : {best_cv:.4f}")
print(f"   n_estimators   : {best_run['params.n_estimators']}")
print(f"   max_depth      : {best_run['params.max_depth']}")

# ── Load the best model directly from MLflow ─────────────────────
model_uri  = f"runs:/{best_run_id}/model"
best_model = mlflow.sklearn.load_model(model_uri)

print(f"\nβœ“ Model loaded: {type(best_model).__name__}")
print(f"  Ready for inference or registration.")

# ── Sensitivity analysis: which params vary most with score? ─────
numeric_cols = runs[['params.n_estimators', 'metrics.cv_accuracy_mean']].apply(pd.to_numeric, errors='coerce')
corr = numeric_cols.corr().iloc[0, 1]
print(f"\n  Correlation n_estimators ↔ cv_accuracy: {corr:.3f}")
print(f"  (closer to 1.0 = more trees strongly improve accuracy)")

Knowing how to run a search is not enough. In production, you also need to know how to search responsibly β€” with reproducibility, compute efficiency, and model governance in mind.

  • Always set random_state in both the search and the estimator
    • RandomizedSearchCV(random_state=42) controls which hyperparameter combinations are sampled.
    • RandomForestClassifier(random_state=42) controls the model's internal randomness.
    • Both are required for reproducibility.
    • Without them, the same script can produce different "best" models on each run.
  • Separate CV accuracy from test accuracy
    • Use cross-validation accuracy to select the best hyperparameters.
    • Use test accuracy only to estimate real-world performance.
    • Choosing a model based on test accuracy leaks information and makes the test score unreliable.
    • Select via CV, evaluate once on the test set, and report the test result.
  • Think in distributions, not discrete lists
    • Grid search requires predefined values such as [50, 100, 200].
    • Random search can sample from ranges like randint(50, 300).
    • Continuous distributions are especially useful for parameters such as learning rate.
    • For example, loguniform(1e-4, 1e-1) efficiently explores values across four orders of magnitude.
  • Log everything β€” not just the winners
    • Failed experiments are valuable information.
    • Poor-performing combinations show where not to search next time.
    • Logging all runs creates a searchable history of experiments.
    • Future engineers (or future you) can use MLflow to understand what has already been tried before starting a new search.

Mastering hyperparameter tuning and experiment comparison enables us to systematically optimize model performance instead of relying on trial and error.

It ensures that every experiment is reproducible and fully traceable. These practices help teams make data-driven decisions when selecting models. Ultimately, they are essential for building scalable and production-ready machine learning systems.


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post