Hyperparameter Search
In machine learning practice, we often encounter such confusion: why, using the same algorithm, can someone else's model reach 95% accuracy while mine only reaches 85%? Apart from differences in data quality and feature engineering, a key factor often lies in the Hyperparameters settings.
If the model algorithm is a car's engine, then hyperparameters are the fine-tuning knobs such as the engine's ignition timing and fuel injection amount. Tuned well, the engine is powerful; tuned poorly, it may lack power or suffer serious wear.
This article will give you a systematic understanding of hyperparameter search, a crucial part of model optimization and engineering.
What Are Hyperparameters?
Before diving into search methods, we must first clarify a core concept:Hyperparameters The difference between Model parameters difference.
Model Parameters vs Hyperparameters
| Feature | Model parameters | Hyperparameters |
|---|---|---|
| define | Internal variables obtained by the modelStudyfrom the training data. | Configuration variables setbeforetraining begins, manually set by the developer or chosen via an algorithm. |
| Learning Method | Automatically adjusted through optimization algorithms (such as gradient descent). | Not learned from training data; need to be set externally. |
| Example | Weights in linear regression w and bias b; weights and biases in neural networks. |
Learning rate, maximum depth of a decision tree, number of trees in a random forest, the K value in KNN. |
| affects | Determine the model's ability to fit specific data. | Determine the model'slearning process, capacity, and structure, thereby affecting the final performance. |
A vivid analogy: Imagine you are learning to cook a new dish (training a model).
- Model parameters Model parameters are like the specific amounts — "a pinch of salt, half a spoon of sugar" — that you work out during cooking based on the ingredients and heat; these come from practice (training).
- Hyperparameters Hyperparameters, on the other hand, are decided before you start cooking: whether to usehigh heat for stir-fryingoror low heat for slow stewing(learning rate)? How many times in total tostir-fry(number of training epochs)? These choices fundamentally affect your cooking process and the final taste.
Examples of Common Hyperparameters
Different machine learning algorithms have their own unique hyperparameters:
General Hyperparameters:
learning_rate: the learning rate, which controls the step size of model parameter updates. Too large, and it easily "skips" the optimum; too small, and learning is too slow.n_estimators: the number of weak learners (such as trees) in an ensemble model.max_iter/epochs: the maximum number of iterations or training epochs.
Linear Models / Neural Networks:
alpha/lambda: the strength of the regularization term, used to prevent overfitting.batch_size: the number of samples used in each parameter update.hidden_layer_sizes: the size of the hidden layers in a neural network.
Tree Model:
max_depth: the maximum depth of a tree, controlling the model's complexity.min_samples_split: the minimum number of samples required to split an internal node.min_samples_leaf: the minimum number of samples required at a leaf node.
Why Is Hyperparameter Search Needed?
Since hyperparameters are so important, can we set them arbitrarily based on experience or intuition? The answer is no. The reasons are as follows:
- Huge Impact on Performance: for the same model, different hyperparameter combinations can lead to vastly different performance (such as accuracy and F1 score).
- No Universally Optimal Value: the optimal hyperparameters depend heavily on the specific dataset, task, and model; there is no one-size-fits-all "magic default".
- Vast Combination Space: multiple hyperparameters interact with each other, forming a high-dimensional search space. Manual trial and error is extremely inefficient and prone to getting stuck in local thinking.
Therefore, we need systematic and automated methods to explore this vast parameter space and find better-performing configurations. This process is hyperparameter search or hyperparameter optimization。
Its core goal is to find, within an acceptable computational cost, a set of hyperparameters that makes the model perform optimally onunseen data(the validation set).

Main Hyperparameter Search Strategies
1. Grid Search
Grid search is the most basic and intuitive search method.
How It Works:
- Define a list of candidate values for each hyperparameter to be searched.
- The search algorithm generates theCartesian productof these lists, that is, all possible combinations.
- Iterate over every combination, train the model, and evaluate it.
- Select the combination with the best performance on the validation set.
Example: Search over two hyperparameters of a Support Vector Machine (SVM).
Example
Suppose we define the following search grid
param_grid
=
{
'C'
:
[
0.1
,
1
,
10
,
100
]
,
Regularization strength, 4 candidate values
'gamma'
:
[
0.001
,
0.01
,
0.1
,
1
]
Kernel function coefficient, 4 candidate values
}
Grid search will try 4 * 4 = 16 different combinations
Advantages:
- Simple and Reliable: as long as the grid is fine enough, it is guaranteed to find the optimal solution within the given range.
- Easy to parallelize: The training and evaluation of each parameter combination are independent of one another, making it very suitable for parallel computation.
Disadvantages:
- Curse of dimensionality: If there are slightly more hyperparameters or slightly denser candidate values, the number of combinations grows exponentially, and the computational cost becomes prohibitive. For example, with 5 parameters each taking 10 values, you would need to train and evaluate 10^5 = 100,000 models!
- Inefficient: It may waste a large amount of computational resources on "unimportant" parameters.
2. Random Search
Random search is an effective improvement that addresses the shortcomings of grid search.
How It Works:
- Define a probability distribution for each hyperparameterProbability Distributions(such as a uniform distribution or a log-uniform distribution).
- Within the specified total number of trials (
n_iter),Random samplinga set of hyperparameter values. - Train and evaluate each sampled set of parameters.
- Select the combination with the best performance.
Example: Use random search to optimize a random forest.
Example
from
sklearn.
model_selection
import
RandomizedSearchCV
from
scipy.
stats
import
randint
,
uniform
param_dist
=
{
'n_estimators'
: randint
(
100
,
500
)
,
Integer uniform distribution, from 100 to 500
'max_depth'
: randint
(
5
,
30
)
,
Integer uniform distribution, from 5 to 30
'min_samples_split'
: uniform
(
0.01
,
0.2
)
Continuous uniform distribution, from 0.01 to 0.21
}
Perform 50 trials at random
random_search
=
RandomizedSearchCV
(
estimator
=
rf_model
,
param_distributions
=
param_dist
,
n_iter
=
50
,
cv
=
5
,
verbose
=
2
)
random_search.
fit
(
X_train
,
y_train
)
Why is random search more efficient? Research (Bergstra & Bengio, 2012) has shown that for most problems, model performance is typically sensitive to only a few hyperparameters. Random search allows us toevery dimensionto explore more extensively, giving a higher probability of finding the best region for the important parameters, unlike grid search, which is constrained by a fixed grid over unimportant parameters.
Advantages:
- High computational efficiency: Under the same computational budget, it has a higher probability of finding a better solution than grid search.
- Flexible: It is easy to specify probability distributions for parameters (such as searching for the learning rate on a logarithmic scale).
Disadvantages:
- randomness: Results may vary with the random seed, and some regions may be missed.
- Memoryless: Each trial is independent and does not use information from previous trials to guide subsequent searches.
3. Bayesian Optimization
Bayesian optimization is a smarter search method suitable for optimizing functions whose evaluation is very expensive (for example, training a large deep learning model may take several days).
Core idea:
- Surrogate model: Use a computationally cheap probabilistic model (such as a Gaussian process) to "simulate" the real, computationally expensive objective function (that is, the relationship between model performance and hyperparameters).
- Acquisition function: Based on the surrogate model's uncertainty, select the "most promising" hyperparameter combination for the next evaluation. It balances Exploration(sampling in regions with high uncertainty) and Use(sampling near regions with known good performance).
Workflow:

Advantages:
- Extremely efficient: It can find near-optimal solutions with the fewest trials, making it especially suitable for expensive models.
- Adaptivity: It intelligently guides the search direction using historical information.
Disadvantages:
- Complex to implement: More complex than the previous two methods.
- Difficult to parallelize: Standard Bayesian optimization is sequential and difficult to parallelize directly (although improved methods exist).
- In high-dimensional spaces: As the number of hyperparameter dimensions increases, fitting and optimizing the surrogate model becomes harder.
Common tools: scikit-optimize, BayesianOptimization, Optuna, Hyperopt。
Engineering Practices and Precautions
1. Validation Strategy: Do Not Contaminate Your Test Set!
When searching for hyperparameters,you must neveruse the test set to guide the search process, otherwise it will lead to information leakage and overly optimistic estimates of generalization performance.
Correct approach:
- Split the data into:Training Set、validation set、Test Set。
- Hyperparameter search is performed on the "training set + validation set" (for example, using cross-validation).
- After selecting the best hyperparameters, use them on thecomplete training set(or the merged training + validation set) to retrain the final model.
- Finally, take the data that has never been involved in any training or tuning process Test Set to fairly evaluate the final model's generalization ability.
2. Use Cross-Validation
To evaluate hyperparameter performance more robustly and avoid the randomness introduced by a single data split, cross-validation should be used.
Example
from
sklearn.
model_selection
import
GridSearchCV
Grid search with 5-fold cross-validation
grid_search
=
GridSearchCV
(
estimator
=
model
,
param_grid
=
param_grid
,
cv
=
5
,
5-fold cross-validation
scoring
=
'accuracy'
,
return_train_score
=
True
)
grid_search.
fit
(
X_train_val
,
y_train_val
)
Here the training + validation data is used
(
f
"Best parameters: {grid_search.best_params_}"
)
(
f
"Best cross-validation score: {grid_search.best_score_:.4f}"
)
Obtain the best model (already refitted on all data with the best parameters)
best_model
=
grid_search.
best_estimator_
3. Tips for Designing the Hyperparameter Space
- Scale-sensitive parameters: For parameters such as the learning rate and regularization strength, theireffective ranges often span several orders of magnitude. You should search on a logarithmic scale (such as
[0.001, 0.01, 0.1, 1]), rather than on a linear scale (such as[0.1, 0.2, ..., 1.0])。 - Coarse first, fine later: You can first perform a large-scale random search or a sparse grid search to locate regions with better performance, and then conduct a finer search within that region.
- Leverage prior knowledge: Set reasonable initial ranges and distributions based on algorithmic principles and empirical literature.
4. Automation and Toolchains
In real-world engineering, hyperparameter search is often integrated into MLOps pipelines.
- Framework:
Scikit-learnprovidesGridSearchCVandRandomizedSearchCV。 - Advanced libraries:
Optuna,Ray Tune,Keras Tunerprovide more powerful, distributed-friendly search capabilities and support advanced features such as early stopping and pruning. - Cloud service: Platforms such as AWS SageMaker and Google Vertex AI provide managed hyperparameter optimization services.
Hands-on Exercises
Now, let us use the Scikit-learn and 随机森林 dataset to complete a full hyperparameter search exercise.
Task: Use the wine dataset to optimize a random forest classifier with random search.
Example
1. Import the necessary libraries
import
numpy
as
np
from
sklearn.
datasets
import
load_wine
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
model_selection
import
train_test_split
,
RandomizedSearchCV
from
sklearn.
metrics
import
classification_report
from
scipy.
stats
import
randint
2. Load the data and split it
data
=
load_wine
(
)
X
,
y
=
data.
data
,
data.
target
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.2
,
random_state
=
42
)
X_train_val
,
X_val
,
y_train_val
,
y_val
=
train_test_split
(
X_train
,
y_train
,
test_size
=
0.25
,
random_state
=
42
)
0.25 * 0.8 = 0.2
3. Define the model and parameter distributions
rf
=
RandomForestClassifier
(
random_state
=
42
)
param_dist
=
{
'n_estimators'
: randint
(
50
,
300
)
,
Number of trees
'max_depth'
: randint
(
3
,
20
)
,
Maximum depth of the trees
'min_samples_split'
: randint
(
2
,
10
)
,
Minimum number of samples required to split an internal node
'min_samples_leaf'
: randint
(
1
,
5
)
,
Minimum number of samples per leaf node
'max_features'
:
[
'sqrt'
,
'log2'
]
Number of features to consider when looking for the best split
}
4. Perform random search (with 3-fold cross-validation)
random_search
=
RandomizedSearchCV
(
estimator
=
rf
,
param_distributions
=
param_dist
,
n_iter
=
30
,
Randomly try 30 sets of parameters
cv
=
3
,
3-fold cross-validation
scoring
=
'accuracy'
,
random_state
=
42
,
verbose
=
1
,
n_jobs
=
1
)
Parallelize using all CPU cores
random_search.
fit
(
X_train_val
,
y_train_val
)
5. Output the search results
(
"="
50
)
(
"Best parameters from random search:"
)
(
random_search.
best_params_
)
(
f
"\nBest cross-validation accuracy: {random_search.best_score_:.4f}"
)
6. Evaluate the best model on an independent validation set
best_model
=
random_search.
best_estimator_
y_val_pred
=
best_model.
predict
(
X_val
)
(
"\nPerformance report on the validation set:"
)
(
classification_report
(
y_val
,
y_val_pred
,
target_names
=
data.
target_names
)
)
7. (Final step) Retrain on the entire training set with the best parameters and evaluate on the test set
final_model
=
RandomForestClassifier
(
**random_search.
best_params_
,
random_state
=
42
)
final_model.
fit
(
X_train
,
y_train
)
Use all training data
y_test_pred
=
final_model.
predict
(
X_test
)
(
"="
50
)
(
"Performance report of the final model on the test set (completely new data):"
)
(
classification_report
(
y_test
,
y_test_pred
,
target_names
=
data.
target_names
)
)
Output:
Fitting 3 folds for each of 30 candidates, totalling 90 fits
==================================================
Random search for optimal parameters:
{'max_depth': 9, 'max_features': 'log2', 'min_samples_leaf': 1, 'min_samples_split': 8, 'n_estimators': 156}
最佳交叉验证准确率:0.9812
Performance report on the validation set:
precision recall f1-score support
class_0 1.00 1.00 1.00 11
class_1 1.00 0.94 0.97 16
class_2 0.90 1.00 0.95 9
accuracy 0.97 36
macro avg 0.97 0.98 0.97 36
weighted avg 0.98 0.97 0.97 36
==================================================
Performance report of the final model on the test set (new data):
precision recall f1-score support
class_0 1.00 1.00 1.00 14
class_1 1.00 1.00 1.00 14
class_2 1.00 1.00 1.00 8
accuracy 1.00 36
macro avg 1.00 1.00 1.00 36
weighted avg 1.00 1.00 1.00 36