Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Hyperparameter Search

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).

Examples of Common Hyperparameters

Different machine learning algorithms have their own unique hyperparameters:

General Hyperparameters:

Linear Models / Neural Networks:

Tree Model:


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:

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:

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:

Disadvantages:

2. Random Search

Random search is an effective improvement that addresses the shortcomings of grid search.

How It Works:

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:

Disadvantages:

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:

Workflow:

Advantages:

Disadvantages:

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:

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

print

(

f

"Best parameters: {grid_search.best_params_}"

)

print

(

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

4. Automation and Toolchains

In real-world engineering, hyperparameter search is often integrated into MLOps pipelines.


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

print

(

"="

50

)

print

(

"Best parameters from random search:"

)

print

(

random_search.

best_params_

)

print

(

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

)

print

(

"\nPerformance report on the validation set:"

)

print

(

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

)

print

(

"="

50

)

print

(

"Performance report of the final model on the test set (completely new data):"

)

print

(

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