Hyperparameter Tuning in Machine Learning: Grid Search, Random Search and Beyond
On this page
Hyperparameter tuning is the process of finding the settings that make a machine learning model perform best on new data. Hyperparameters are the choices you make before training, such as the depth of a decision tree, the number of trees in a random forest or the learning rate of a neural network. You try different combinations, score each one with cross-validation, and keep the best. Done well, tuning squeezes extra performance out of a model; done badly, it simply overfits your validation data.
Parameters vs hyperparameters
| Parameters | Hyperparameters | |
|---|---|---|
| Who sets them? | Learned by the model from data | Chosen by you before training |
| Examples | Regression coefficients, neural network weights, tree split values | max_depth, n_estimators, learning_rate, C, k in KNN, batch size |
| How they change | During training (for example by gradient descent) | Between training runs, by tuning |
Hyperparameters worth tuning for common models
- Logistic regression: C (regularisation strength), penalty.
- Decision tree: max_depth, min_samples_leaf, min_samples_split.
- Random forest: n_estimators, max_depth, min_samples_leaf, max_features.
- XGBoost / LightGBM: learning_rate, n_estimators, max_depth, subsample, colsample_bytree. See XGBoost explained.
- KNN: n_neighbors, weights, distance metric.
- Neural networks: learning rate, batch size, number of layers and units, dropout.
Most of these control the trade-off between underfitting and overfitting, which is why tuning and overfitting vs underfitting go hand in hand.
The golden rule: never tune on the test set
Split your data into training and test sets first and lock the test set away. Tune using cross-validation on the training set only: the training data is split into k folds (commonly 5), the model is trained on k−1 folds and scored on the remaining fold, and this repeats k times. The average score decides which hyperparameters win. Use the test set once, at the end, to estimate real-world performance.
Four tuning methods
| Method | How it works | Best when |
|---|---|---|
| Manual tuning | Change one setting, retrain, compare | Learning how a model behaves |
| Grid search | Tries every combination in a fixed grid | Few hyperparameters with a handful of values each |
| Random search | Samples a fixed number of random combinations from ranges | Many hyperparameters or wide ranges; usually more efficient than grid |
| Bayesian optimisation | Uses past results to choose the next promising combination (for example with Optuna) | Expensive models where each training run takes a long time |
Random search often beats grid search for the same budget because only a few hyperparameters usually matter, and random sampling tries more distinct values of each one.
A tested example with scikit-learn
We tuned a random forest on scikit-learn’s built-in breast cancer dataset (569 rows), using an 80/20 stratified split and 5-fold cross-validation scored by F1.
from scipy.stats import randint
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
base = RandomForestClassifier(random_state=42).fit(X_train, y_train)
print("Default test accuracy:", round(base.score(X_test, y_test), 3))
grid = GridSearchCV(
RandomForestClassifier(random_state=42),
param_grid={"n_estimators": [100, 300], "max_depth": [None, 5, 10], "min_samples_leaf": [1, 3]},
cv=5, scoring="f1", n_jobs=-1)
grid.fit(X_train, y_train)
print("Grid best:", grid.best_params_, "CV F1:", round(grid.best_score_, 3))
rand = RandomizedSearchCV(
RandomForestClassifier(random_state=42),
param_distributions={"n_estimators": randint(100, 500), "max_depth": randint(3, 20), "min_samples_leaf": randint(1, 6)},
n_iter=20, cv=5, scoring="f1", random_state=42, n_jobs=-1)
rand.fit(X_train, y_train)
print("Random best:", rand.best_params_, "CV F1:", round(rand.best_score_, 3))
print("Tuned test accuracy:", round(grid.best_estimator_.score(X_test, y_test), 3))
What we got (scikit-learn 1.9):
- Default random forest test accuracy: 0.956
- Grid search (12 combinations × 5 folds = 60 fits): best n_estimators=300, max_depth=None, min_samples_leaf=1, CV F1 0.967
- Random search (20 combinations × 5 folds = 100 fits): best n_estimators=314, max_depth=9, min_samples_leaf=2, CV F1 0.967
- Tuned model test accuracy: 0.947
Notice that the tuned model did not beat the default on the test set. This is an important, honest lesson: random forest defaults are already strong, the test set here has only 114 rows (one prediction is worth almost 0.9 percentage points), and a small difference in cross-validation score can disappear on new data. Tuning gives the biggest gains on sensitive models such as gradient boosting and neural networks, and on larger datasets. Always compare against the untuned baseline before claiming an improvement.
Bayesian optimisation with Optuna
Optuna is a popular open-source library for smarter search. You write an objective function that trains a model with suggested values (for example trial.suggest_int("max_depth", 3, 20)) and returns a cross-validation score. Optuna learns which regions look promising and focuses its trials there, and it can stop unpromising trials early. It is especially useful for XGBoost, LightGBM and deep learning, where each run is costly.
Practical tuning tips
- Get a baseline first with default settings, and fix data and feature problems before tuning; better features usually matter more than hyperparameters.
- Choose the right metric. Use F1, recall or ROC AUC for imbalanced classes, not just accuracy.
- Start wide, then narrow. Use random search over broad ranges, then a small grid around the best values.
- Search learning rates and regularisation on a log scale (0.001, 0.01, 0.1) rather than evenly spaced values.
- Put preprocessing inside a Pipeline so scaling and encoding are fitted within each fold, preventing data leakage.
- Set random_state so your results can be reproduced.
- Track experiments with a tool such as MLflow once you run many trials; see the MLOps roadmap.
Frequently asked questions
Is hyperparameter tuning always necessary?
No. Many models perform well with sensible defaults. Tune when you have a clear baseline, a reliable validation method and a model that is sensitive to its settings.
Grid search or random search: which should I use?
For two or three hyperparameters with a few values each, grid search is fine. For more hyperparameters or wide ranges, random search usually finds equally good settings with fewer fits.
How many cross-validation folds should I use?
Five folds is a common default. Use ten for small datasets if training is fast, and stratified folds for classification so each fold keeps the class balance.
Can hyperparameter tuning cause overfitting?
Yes. If you test hundreds of combinations, some will score well on validation data by chance. Keep the test set untouched and treat small improvements with caution.
Related reading
- How to evaluate a machine learning model
- Overfitting vs underfitting
- XGBoost explained
- Decision tree vs random forest
- Naive Bayes explained
- Cross-validation explained: k-fold, stratified and time series
Want to practise tuning and evaluating models on real projects with guidance? See our Machine Learning course or the complete Data Science course.
A note from Mehul Prajapati
I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in machine learning and want a second opinion on your learning path, I am happy to help.
“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”
Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Machine Learning course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.