Hyperparameter Optimization

Parameters are learned during training. Examples include the coefficients of a linear model or the weights and biases of a neural network.

But models have another set of variables besides parameters, called hyperparameters. So far, we’ve talked at length about how parameters are determined, e.g. gradient descent, but have only really seen hyperparameters in passing.

This Lesson Will Cover
  • ⚙️ What hyperparameters are and how they differ from parameters
  • 📊 Common hyperparameters for different model types
  • 🔍 Methods for hyperparameter optimization including grid search and Bayesian approaches
  • 🏗️ Practical examples using scikit-learn and optuna

What Are Hyperparameters?

Hyperparameters are configuration variables that control the learning process and model architecture.

They are set before training begins and cannot be directly learned from data. Even so, these variables significantly influence how well a model performs on a given dataset.

Examples of hyperparameters include:

Model Type Hyperparameter Typical Value Range
Neural Networks Learning Rate 0.0001 - 0.1
Neural Networks Number of Hidden Layers 1 - 10
Neural Networks Neurons per Layer 32 - 512
Neural Networks Batch Size 16 - 256
Neural Networks Dropout Rate 0.1 - 0.5
Random Forest Number of Trees 50 - 1000
Random Forest Max Depth 3 - 50
Random Forest Min Samples Split 2 - 20
Gradient Boosting Learning Rate 0.01 - 0.3
Gradient Boosting Number of Estimators 50 - 1000
SVM C (Regularization) 0.1 - 100
SVM Kernel rbf, linear, poly
k-NN Number of Neighbors 1 - 20
k-NN Distance Metric euclidean, manhattan
Linear Models Regularization Strength 0.0001 - 10

Hyperparameter Optimization

Hyperparameter optimization is the process of finding the best configuration to maximize model performance.

It’s computationally expensive because separate models have to be trained for each combination of hyperparameters being compared.

Grid Search

Grid search evaluates all combinations of hyperparameters in a predefined grid.

For example, with a random forest classifier, we could grid search over:

  • The number of trees in the model n_estimators
  • The maximum depth max_depth
  • The minimum samples required to split a node min_samples_split

As a parameter grid, this might look like the following:

param_grid = {
    'n_estimators': [10, 50, 100, 200],
    'max_depth': [None, 10, 20, 30],
    'min_samples_split': [3, 5, 8]
}

This results in 4×4×3=484 \times 4 \times 3 = 48 combinations.

In the example below, we set cv=3 for GridSearchCV, which means that we are using KFold cross validation with k=3, and we’ll have to train 48×3=14448 \times 3 = 144 models!

Here’s an example with scikit-learn:

from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier

# Example dataset
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)

# Define model and hyperparameter grid
model = RandomForestClassifier(random_state=1)
param_grid = {
    'n_estimators': [10, 50, 100, 200],
    'max_depth': [None, 10, 20, 30],
    'min_samples_split': [3, 5, 8]
}

# Perform grid search
grid_search = GridSearchCV(model, param_grid, cv=3, scoring='accuracy')
grid_search.fit(X, y)

print(f"Best Parameters: {grid_search.best_params_}")
print(f"Best Score: {grid_search.best_score_}")

# Outputs:
# Best Parameters: {'max_depth': None, 'min_samples_split': 5, 'n_estimators': 10}
# Best Score: 0.9733
Grid Search Scores for Random Forest Classifier
Grid-search combinations sorted by accuracy score, with the best parameters highlighted in pink.

From this information, we can select the hyperparameters that perform best and use them to train our best model on the full set of training data.

Bayesian Optimization

Bayesian optimization is far more sophisticated than grid search. With this technique, we build a probabilistic model to estimate the performance of hyperparameter combinations.

Unlike the brute-force approach of grid search, it focuses on regions of the hyperparameter space likely to perform best.

Here’s an example with scikit-learn and Optuna (a hyperparameter optimization framework):

import optuna
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

# Example dataset
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)

# Objective function that Optuna will optimize
def objective(trial):

    # Define hyperparameter search spaces (i.e. between 10-200, 5-30, 2-10)
    n_estimators = trial.suggest_int('n_estimators', 10, 200)
    max_depth = trial.suggest_int('max_depth', 5, 30)
    min_samples_split = trial.suggest_int('min_samples_split', 2, 10)

    # Create Random Forest model with the suggested hyperparameters
    model = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        min_samples_split=min_samples_split
    )

    # Perform cross validation and return mean accuracy score
    # cv=3 means 3-fold cross validation
    score = cross_val_score(model, X, y, cv=3, scoring='accuracy').mean()
    return score

# Create an Optuna study object that maximizes the objective
study = optuna.create_study(direction='maximize')

# Run optimization for 20 trials
study.optimize(objective, n_trials=20)

print(f"Best Parameters: {study.best_params}")
print(f"Best Score: {study.best_value}")

Here’s the full output:

[I 2025-02-27 08:12:03,453] A new study created in memory with name: no-name-a71fcaf9-52ba-43a4-8313-72467436f367
[I 2025-02-27 08:12:03,498] Trial 0 finished with value: 0.9466666666666667 and parameters: {'n_estimators': 26, 'max_depth': 29, 'min_samples_split': 2}. Best is trial 0 with value: 0.9466666666666667.
[I 2025-02-27 08:12:03,560] Trial 1 finished with value: 0.96 and parameters: {'n_estimators': 39, 'max_depth': 19, 'min_samples_split': 6}. Best is trial 1 with value: 0.96.
[I 2025-02-27 08:12:03,717] Trial 2 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 107, 'max_depth': 16, 'min_samples_split': 4}. Best is trial 1 with value: 0.96.
[I 2025-02-27 08:12:03,769] Trial 3 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 34, 'max_depth': 9, 'min_samples_split': 9}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,003] Trial 4 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 164, 'max_depth': 5, 'min_samples_split': 8}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,072] Trial 5 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 45, 'max_depth': 24, 'min_samples_split': 8}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,256] Trial 6 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 120, 'max_depth': 8, 'min_samples_split': 6}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,464] Trial 7 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 145, 'max_depth': 25, 'min_samples_split': 3}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,498] Trial 8 finished with value: 0.9466666666666667 and parameters: {'n_estimators': 20, 'max_depth': 27, 'min_samples_split': 8}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,586] Trial 9 finished with value: 0.96 and parameters: {'n_estimators': 59, 'max_depth': 26, 'min_samples_split': 2}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,699] Trial 10 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 71, 'max_depth': 11, 'min_samples_split': 10}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:04,866] Trial 11 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 109, 'max_depth': 6, 'min_samples_split': 6}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:05,064] Trial 12 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 132, 'max_depth': 11, 'min_samples_split': 10}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:05,191] Trial 13 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 80, 'max_depth': 11, 'min_samples_split': 5}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:05,467] Trial 14 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 188, 'max_depth': 8, 'min_samples_split': 7}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:05,615] Trial 15 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 96, 'max_depth': 16, 'min_samples_split': 9}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:05,824] Trial 16 finished with value: 0.96 and parameters: {'n_estimators': 138, 'max_depth': 13, 'min_samples_split': 5}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:06,005] Trial 17 finished with value: 0.96 and parameters: {'n_estimators': 121, 'max_depth': 20, 'min_samples_split': 7}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:06,030] Trial 18 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 10, 'max_depth': 8, 'min_samples_split': 9}. Best is trial 3 with value: 0.9666666666666667.
[I 2025-02-27 08:12:06,278] Trial 19 finished with value: 0.96 and parameters: {'n_estimators': 166, 'max_depth': 14, 'min_samples_split': 6}. Best is trial 3 with value: 0.9666666666666667.
Best Parameters: {'n_estimators': 34, 'max_depth': 9, 'min_samples_split': 9}
Best Score: 0.9666666666666667

Here we use only 20 trials to search the hyperparameter space, as opposed to 48 for the grid search example above.

Optuna Trial Scores by Hyperparameter Combination for Random Forest Study
Optuna trial hyperparameter combinations sorted by accuracy score, with the best parameters highlighted in pink. Data plotted here is slightly different than the raw output above, because a different random seed was used.

Conclusion

Bayesian optimization is pretty clever. I first encountered it in a book[1] that I read about deep learning, where the author used optuna[2] to train a neural network with hyperparameter optimization.

Key Takeaways

🎛️ Hyperparameters are configuration variables that control model training, set before training begins.

📏 Common hyperparameters include learning rate, model size, and regularization strength.

🔍 Grid search evaluates all hyperparameter combinations but is computationally expensive.

🧠 Bayesian optimization provides an efficient alternative by focusing on promising parameter regions.

⚡ Hyperparameter tuning is essential for model performance but requires careful validation.

Next: Model Selection

Optimizing hyperparameters like we did above will yield (we hope) our best random forest model. But whose to say that some other model, like a boosted tree, wouldn’t perform better? Let’s talk about model selection.

Footnotes


  1. The book was called [MLOps Engineering at Scale]. The author includes many code samples that depend on a library named Kaen. It looked good, so I decided to try it out for one of my projects—only to find that is has just 3 stars on GitHub and no contributions in the last 2 years. It’s unfathomable to me that an author would use such a library as a dependency in a published book. Needless to say, I do not recommend it. ↩︎

  2. I do recommend these Optuna examples, where you can see at a glance how to use it for many frameworks: PyTorch, TensorFlow, Keras, Scikit-Learn, etc… ↩︎

Comments (0)

No comments yet.