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:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
π 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:
- Hyperparameter Tuning & Experiment Comparison via Docker
- Hyperparameter Tuning & Experiment Comparison Via Kubernetes
π§ 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?

Grid Search vs Random Search
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.

| Feature | GridSearchCV (Exhaustive Search) | RandomizedSearchCV (Efficient Search) |
|---|---|---|
| Search Strategy | Tries every combination of provided parameter values | Randomly samples n_iter combinations from parameter distributions |
| Coverage | Exhaustive | Non-exhaustive but statistically near-optimal |
| Best Parameters | Guaranteed to find the best combination within the grid | High probability of finding near-optimal parameters |
| Computation Cost | Number of fits grows multiplicatively | Fixed compute budget |
| Total Fits | (valuesβ Γ valuesβ Γ ... ) Γ cv_folds | n_iter Γ cv_folds |
| Example | 5 Γ 4 Γ 3 = 60 combinations Γ 5 folds = 300 fits | 20 iterations Γ 5 folds = 100 fits |
| Scalability | Suitable for small, well-constrained search spaces | Excellent for large, high-dimensional spaces |
| Continuous Parameters | Requires manually specifying discrete values | Can sample from continuous distributions (e.g., log-uniform) |
| Efficiency | Can become very expensive when training is slow or grid size is large | Much more computationally efficient |
| Parameter Importance | Treats all combinations equally | Focuses on exploring the search space efficiently |
| When to Use | Small number of hyperparameters and values | Large search spaces or limited compute resources |
| Performance | Finds the exact optimum in the specified grid | Often achieves comparable performance with far fewer evaluations |
| Research Support | Classical exhaustive approach | Shown by Bergstra & Bengio (2012) to be as effective as grid search with significantly fewer evaluations |
| Recommended For | Simpler models and smaller datasets | Complex 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.0pip install -r requirements.txtGridSearchCV 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.
| Hyperparameter | Search Distribution | Rationale | Best Found |
|---|---|---|---|
| n_estimators | randint(50, 300) | More trees = more stable, diminishing returns above ~200 | 200 best |
| max_depth | [None, 3, 5, 7, 10, 15] | None = fully grown; shallow trees prevent overfitting | None best |
| min_samples_split | randint(2, 15) | Minimum samples to split a node; higher = smoother | 2 default |
| min_samples_leaf | randint(1, 10) | Minimum samples in a leaf; acts as regularizer | 1 default |
| max_features | ['sqrt', 'log2', None] | Features per split; sqrt is the classic RF choice | sqrt default |
| criterion | ['gini', 'entropy', 'log_loss'] | Split quality measure; gini is faster, entropy more info-rich | gini default |
| bootstrap | [True, False] | Whether to bootstrap samples when building trees | True 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:

- Run the random search
- Execute
python src/tune_random.py. - This runs
RandomizedSearchCVwith 10 combinations Γ 5-fold CV = 50 model fits. - The output prints a line for each combination as it is logged.
- Execute
- Launch the MLflow UI
- Run
mlflow uiin your project root. - Open
http://127.0.0.1:5000. - Select the iris-random-search experiment to view all 10 runs in a table.
- Run
- Sort by
cv_accuracy_mean- Click the
cv_accuracy_meancolumn 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.
- Click the
- 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
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββUnderstanding Cross-Validation in Search
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.

- ΞΌ
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=Noneandmin_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:

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)")MLOps Best Practices for Hyperparameter Search
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_statein both the search and the estimatorRandomizedSearchCV(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.
- Grid search requires predefined values such as
- 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:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion