Hyperparameter tuning
- Authors
- Name
- Amit Shekhar
- Published on
Hyperparameter Tuning is the process of finding the best combination of hyperparameters, the values we set before training, that gives us the best performing model.
In this blog, we will learn about Hyperparameter Tuning. We will also see what a hyperparameter is and how it differs from a parameter, how we measure it with a validation set and cross-validation, how it connects with overfitting and underfitting, how methods like Grid Search, Random Search, Bayesian Optimization, and Hyperband work, the best practices we must follow, and where tuning is used in the real world.
We will cover the following:
- What is a parameter?
- What is a hyperparameter?
- Parameters vs Hyperparameters
- Examples of common hyperparameters
- The validation set and cross-validation
- Connection with overfitting and underfitting
- Grid Search
- Random Search
- Bayesian Optimization
- Hyperband and early stopping
- Comparison of search methods
- A small code example with GridSearchCV
- Best practices
- Real-world applications
I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
I teach AI and Machine Learning at Outcome School.
Let's get started.
What is a parameter?
Before jumping into hyperparameters, we must know what a parameter is.
A parameter is a value that the model learns by itself from the data during training.
We do not set these values. The model figures them out on its own while it is learning.
Let's say we are building a model that predicts the price of a house based on its size. The model learns a rule that looks something like this:
price = weight * size + bias
Here, weight and bias are parameters. The model starts with random values for them, looks at the training data again and again, and slowly adjusts them until the predictions become good.
So, parameters are learned from the data automatically. We do not touch them.
We have a detailed blog on Gradient Descent that explains how the model adjusts these parameters step by step.
What is a hyperparameter?
Now, let's understand the main topic.
A hyperparameter is a value that we set ourselves before the training starts. The model does not learn it.
The word "Hyper" means "above" or "on top of". So, a hyperparameter is a setting that sits above the normal parameters. It controls how the model learns the parameters, and it decides how the learning process will happen.
Consider baking a cake. The ingredients mix together on their own inside the oven, that is like the parameters being learned. But the oven temperature and the baking time are things that we decide before we start. Those are the hyperparameters.
If we set a wrong temperature, the cake will burn or stay raw. In the same way, if we set wrong hyperparameters, our model will perform badly.
Parameters vs Hyperparameters
Let me tabulate the differences between parameters and hyperparameters for your better understanding.
| Parameters | Hyperparameters |
|---|---|
| Learned by the model from data | Set by us before training |
| The model adjusts them automatically | We adjust them manually or with a search method |
| Example: weights and bias | Example: learning rate, batch size, epochs |
| Change during training | Stay fixed during one training run |
| We do not control them directly | We fully control them |
Examples of common hyperparameters
Now, let's discuss some common hyperparameters that we use in machine learning.
- Learning rate: This decides how big a step the model takes when it adjusts its parameters. A very high learning rate makes the model jump around and never settle. A very low learning rate makes the model learn very slowly.
- Batch size: This is the number of training examples the model looks at before it updates its parameters once.
- Epochs: This is the number of times the model goes through the entire training data. One epoch means the model has seen all the data one time.
- Number of layers: This is how many layers we stack on top of each other in a neural network. More layers can learn more complex patterns.
- Number of neurons per layer: This is how many small units sit inside each layer. Each unit does a small calculation and passes the result forward.
- Regularization strength: This controls how much we stop the model from memorizing the data, so that it learns the general pattern instead.
There are many more hyperparameters, and the right ones depend on the kind of model we are using. But these are the ones we meet most often.
To learn Hyperparameter Tuning and Epoch, Batch, Batch Size, and Iteration in depth, check out our AI and Machine Learning Program at Outcome School.
The validation set and cross-validation
Before we tune anything, we must know how to measure if a set of hyperparameters is good or bad.
For this, we split our data into parts.
First, we keep one part as the training set. The model learns from this.
Then, we keep another part as the validation set. We never train on this. We only use it to check how well the model performs on data it has not seen before.
So, when we try a set of hyperparameters, we train on the training set and check the score on the validation set. The set of hyperparameters that gives the best validation score is the winner.
If we use just one validation set, the result can depend on luck. Maybe that one split was easy or hard by chance.
So, here comes cross-validation to the rescue.
In cross-validation, we split the data into several equal parts, for example five parts. We train on four parts and validate on the fifth part. Then we repeat this, each time using a different part for validation. Finally, we take the average score.
We can picture 5-fold cross-validation as below:
Round 1: [ V ][ T ][ T ][ T ][ T ]
Round 2: [ T ][ V ][ T ][ T ][ T ]
Round 3: [ T ][ T ][ V ][ T ][ T ]
Round 4: [ T ][ T ][ T ][ V ][ T ]
Round 5: [ T ][ T ][ T ][ T ][ V ]
V = validation part T = training part
Here, we can see that the data is split into five equal parts. In each round, a different part becomes the validation part, marked V, while the other four parts are used for training, marked T. After all five rounds, we take the average score, so every part gets a fair chance to be the validation set.
Planning your move into AI?
No matter which tech domain you work in today, with your effort, you can transition to these roles:
- AI Engineer
- Forward Deployed Engineer
- AI Agent Engineer
- Harness Engineer
- Voice AI Engineer
- AI Architect
- LLM Engineer
- LLM Inference Engineer
- Gen AI Engineer
- MLOps Engineer
- ML Engineer
- Deep Learning Engineer
Our AI and Machine Learning Program at Outcome School takes you there.
Connection with overfitting and underfitting
Now, let's understand how tuning connects with two important problems.
Overfitting happens when the model memorizes the training data instead of learning the general pattern. It does great on training data but fails on new data.
Underfitting happens when the model is too simple and cannot even learn the training data well. It does poorly everywhere.
Hyperparameters directly affect both of these.
For example, too many layers or too many epochs can cause overfitting. Too few layers or too few epochs can cause underfitting. A bad learning rate can cause either problem.
Let's say our data points follow a gentle curve. An underfitting model is too simple, so it draws a flat line and misses the real pattern. A good fit follows the gentle shape of the data. An overfitting model is too wiggly, so it bends to touch almost every point and fails to learn the general pattern.
So, the goal of tuning is to find the right balance in the middle, where the model learns the real pattern and works well on new data. The validation set is our tool to find this balance.
Now that we know what to tune and how to measure it, it is time to learn how we actually search for the best hyperparameters.
Grid Search
The first and simplest method is Grid Search.
In Grid Search, we list out the values we want to try for each hyperparameter, and then we try every possible combination.
Let's say we want to tune two hyperparameters. For the learning rate, we want to try 0.1 and 0.01. For the batch size, we want to try 16 and 32.
Grid Search will try all the combinations:
learning_rate = 0.1, batch_size = 16
learning_rate = 0.1, batch_size = 32
learning_rate = 0.01, batch_size = 16
learning_rate = 0.01, batch_size = 32
Here, we can see that two values for each hyperparameter give us four combinations. We train and validate the model for each one and pick the best.
Advantage: It is simple and it checks every combination, so it does not miss anything in our list.
Disadvantage: It becomes very slow when we have many hyperparameters. If we have five hyperparameters with five values each, that is over three thousand combinations. This problem, where the number of combinations explodes as we add more hyperparameters, is called the curse of dimensionality.
A quick note for you
No matter which tech domain you work in, get familiar with these topics:
- LLM
- RAG
- MCP
- Agent
- Fine-tuning
- Quantization
We put it all together in one video:
AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization
No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.
Now, let's get back to the topic.
Random Search
So, here comes Random Search into the picture to solve the slowness problem.
In Random Search, instead of trying every combination, we pick random combinations of hyperparameters and try only a fixed number of them.
Let's say we decide to try only twenty random combinations. We pick twenty random sets of values, train the model on each, and keep the best one.
Random picking works well because usually only a few hyperparameters really matter. Random Search explores a wider range of values for those important ones without wasting time on every single combination.
Let's compare how Grid Search and Random Search pick their points like below:
Grid Search Random Search
x x x x x x
x
x x x x x x
x x
x x x x x
x x x
x x x x x
Here, we can see that Grid Search tries points arranged in an evenly spaced grid, while Random Search scatters its points randomly across the space. Because the points are scattered, Random Search often explores more distinct values for the hyperparameters that truly matter, which is why it can find a good result with fewer tries.
Advantage: It is much faster than Grid Search and often finds a good result with far fewer tries.
Disadvantage: Because it is random, it can miss the best combination by chance.
Now, let's learn about Bayesian Optimization.
Bayesian Optimization
Both Grid Search and Random Search have one weakness. They do not learn from the past tries. Every new try ignores what happened before.
So, here comes Bayesian Optimization to the rescue.
Bayesian Optimization remembers the results of past tries and uses them to decide which combination to try next. It does not pick blindly.
Let's say it tries a few combinations and notices that a small learning rate is giving better results. It will then focus its next tries around small learning rates. It keeps using what it has learned to make smarter guesses.
Consider a person searching for the best restaurant in a new city. A random person tries any restaurant. A smart person notices which streets have good food and then explores more on those streets. Bayesian Optimization is the smart person.
Advantage: It usually finds good hyperparameters in fewer tries because it learns as it goes.
Disadvantage: It is more complex to set up, and the tries happen one after another, so it is harder to run them all at the same time.
Hyperband and early stopping
Now, let's discuss a method built on a very practical idea called early stopping.
Early stopping means that if a combination of hyperparameters is clearly performing badly after a little training, we stop training it early and do not waste more time on it.
Hyperband uses this idea. It starts by giving a small amount of training to many combinations. Then it keeps only the best ones and gives them more training. It keeps repeating this, throwing away the weak ones and giving more resources to the strong ones.
Advantage: It is very efficient with time and computing power because it quickly drops poor combinations.
Disadvantage: A combination that starts slow but could become good later can get dropped too early.
Comparison of search methods
Let me tabulate the differences between these search methods for your better understanding.
| Method | How it works | Speed | Learns from past tries | Best for |
|---|---|---|---|---|
| Grid Search | Tries every combination | Slow | No | Few hyperparameters with small ranges |
| Random Search | Tries random combinations | Faster | No | Many hyperparameters, quick exploration |
| Bayesian Optimization | Uses past results to guess next | Efficient in tries | Yes | When each try is expensive |
| Hyperband | Drops weak combinations early | Very efficient | Partly | When training is slow and costly |
The best method depends on how many hyperparameters we have and how much time and computing power we can spend.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
A small code example with GridSearchCV
The best way to learn this is by taking an example. Let's see the code as below:
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
# the values we want to try for each hyperparameter
param_grid = {
"n_estimators": [50, 100],
"max_depth": [5, 10]
}
model = RandomForestClassifier()
# cv=5 means 5-fold cross-validation
grid = GridSearchCV(model, param_grid, cv=5)
grid.fit(X_train, y_train)
# the best combination found
print(grid.best_params_)
Here, we can see what is happening step by step.
First, we define param_grid, which holds the values we want to try. Here, n_estimators is the number of trees in the model, and max_depth is how deep each tree can grow. We try 50 and 100 for n_estimators, and 5 and 10 for max_depth. This gives four combinations in total.
Then, we create a RandomForestClassifier model. We have a detailed blog on Decision Trees and Random Forests that explains how this model works.
After that, we pass the model and the grid to GridSearchCV. We set cv=5, which means it uses five-fold cross-validation for each combination. Here, X_train is our training input data, and y_train is the correct answer for each training example.
Finally, grid.fit tries all the combinations, and grid.best_params_ prints the combination that gave the best validation score.
Best practices
Now, let's discuss some best practices that make tuning easier and more effective.
- Start with Random Search. It quickly tells us which ranges of values look promising, and it is faster than Grid Search.
- Tune the important hyperparameters first. For neural networks, the learning rate usually matters the most, so we must focus on it early.
- Always use a validation set or cross-validation. Never judge hyperparameters using the training score, because overfitting can make the training score look better than it really is.
- Keep a separate test set. We must keep a final test set that we never touch during tuning, so we can honestly check the final model.
- Use a wide range first, then narrow down. First search across a big range, find the good area, then search more closely inside that area.
- Use early stopping when training is slow. This saves a lot of time and computing power.
If we want to go deep into Model Development and Training and Evaluation and Testing from the ground up, check out our AI and Machine Learning Program at Outcome School.
Real-world applications
Now, let's see where hyperparameter tuning is used in the real world.
Most machine learning systems use it. When a company builds a model to recommend movies, detect spam emails, predict prices, or recognize images, the team spends a good amount of time tuning hyperparameters to get the best accuracy.
In large companies, this tuning runs on many machines at the same time, trying thousands of combinations automatically. Tools and services exist that do this tuning for us in the cloud.
Even in a simple project, when we want our model to perform just a little better, hyperparameter tuning is the step that often gives us that boost.
Now, we have understood hyperparameter tuning, how it differs from a parameter, and how to do it using Grid Search, Random Search, Bayesian Optimization, and Hyperband.
Frequently Asked Questions
Is the learning rate a parameter or a hyperparameter?
The learning rate is a hyperparameter. We set it ourselves before training starts, and it decides how big a step the model takes when it adjusts its parameters. The weights and bias are the parameters, because the model learns them from the data during training.
Why should we not tune hyperparameters using the training score?
We should not tune hyperparameters using the training score because overfitting can make the training score look better than it really is. A model can memorize the training data and still fail on new data. So, we judge each set of hyperparameters on a validation set or with cross-validation instead.
Why do we need a separate test set if we already have a validation set?
We need a separate test set because the validation set is used again and again to pick the best hyperparameters. The test set is never touched during tuning, so it gives us an honest check of the final model on data that played no part in any choice we made.
Which hyperparameter should we tune first?
For neural networks, the learning rate usually matters the most, so we must focus on it early. A very high learning rate makes the model jump around and never settle, and a very low one makes it learn very slowly. A good approach is to start with Random Search over a wide range, then narrow down.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
