Sklearn Model Evaluation and Tuning
Evaluation and tuning of machine learning models are key steps to ensure model generalization ability and prediction accuracy.
Through appropriate evaluation metrics and tuning methods, model performance can be effectively improved and the risk of overfitting or underfitting can be avoided.
This section will introduce cross validation, grid search, random search, model evaluation methods, and other content in detail.
1. Cross validation
Introduce the concept of cross validation
Cross-Validation is a technique for evaluating model performance. It obtains more stable and reliable evaluation results by dividing the dataset into multiple subsets (folds) and training and testing the model multiple times.
Cross validation helps detect whether the model is overfitting and can more accurately evaluate the model's generalization ability.
Common cross validation methods include:
- K-fold cross validation: divide the data into K folds, select one fold as the test set in turn, use the other K-1 folds as the training set, repeat K times, and finally calculate the average of the K results.
- Leave-One-Out Cross-Validation (LOOCV): each time only one data point is kept as the test set and the rest as the training set. This method is very time-consuming but can be used for small datasets.
- Stratified K-fold cross validation: in K-fold, ensure that the class distribution in each fold is similar to the entire dataset, suitable for class-imbalanced situations.
scikit-learn provides various cross validation methods, such as cross_val_score and cross_val_predict, which help us perform cross validation efficiently.
Use cross_val_score to perform K-fold cross validation
The cross_val_score function is used to perform K-fold cross validation and returns the score of each fold, helping us evaluate the model's stability and performance.
Use cross_val_score to perform K-fold cross validation:
Example
from
sklearn.
model_selection
import
cross_val_score
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
datasets
import
load_iris
Load data
data
=
load_iris
(
)
X
,
y
=
data.
data
,
data.
target
Create the model
model
=
RandomForestClassifier
(
)
Perform K-fold cross validation
scores
=
cross_val_score
(
model
,
X
,
y
,
cv
=
5
)
5-fold cross validation
(
f
"Cross-validation scores: {scores}"
)
(
f
"Mean accuracy: {scores.mean()}"
)
cv=5: indicates performing 5-fold cross validation.scores: returns the score of each fold; the final result is the average of these scores, representing the model's performance.
The output is shown below:
Cross-validation scores: [0.96666667 0.96666667 0.93333333 0.96666667 1. ]
Mean accuracy: 0.9666666666666668
2. Grid search and random search
Use GridSearchCV for hyperparameter tuning
GridSearchCV is a technique that finds the best hyperparameters by exhaustively searching all hyperparameter combinations.
GridSearchCV provides candidate values for a set of parameters, calculates the performance of each combination, and finally selects the best parameter combination.
** Common parameters of GridSearchCV:**
param_grid: the hyperparameter grid to be tuned, usually a dictionary where keys are parameter names and values are candidate parameter values.cv: the number of cross validation folds, usually set to 5 or 10.
Example of using GridSearchCV in scikit-learn:
Example
from
sklearn.
model_selection
import
GridSearchCV
from
sklearn.
svm
import
SVC
from
sklearn.
datasets
import
load_iris
Load data
data
=
load_iris
(
)
X
,
y
=
data.
data
,
data.
target
Create the model
model
=
SVC
(
)
Define the hyperparameter grid
param_grid
=
{
'kernel'
:
[
'linear'
,
'rbf'
]
,
'C'
:
[
1
,
10
,
100
]
}
Perform grid search
grid_search
=
GridSearchCV
(
model
,
param_grid
,
cv
=
5
)
grid_search.
fit
(
X
,
y
)
Output the best parameters and best score
(
f
"Best parameters: {grid_search.best_params_}"
)
(
f
"Best score: {grid_search.best_score_}"
)
grid_search.best_params_: returns the best-performing hyperparameter combination found in the grid search.grid_search.best_score_: returns the cross validation score under the best parameter combination.
The output is shown below:
Best parameters: {'C': 1, 'kernel': 'linear'}
Best score: 0.9800000000000001
Use RandomizedSearchCV to accelerate the tuning process
RandomizedSearchCV is a more efficient hyperparameter tuning method that accelerates the tuning process by randomly selecting a certain number of combinations from the hyperparameter space for evaluation.
RandomizedSearchCV is suitable when the hyperparameter space is large, saving computation time.
Common parameters of RandomizedSearchCV:
param_distributions: the hyperparameter distribution to be tuned, usually a dictionary whose values can be distribution objects (such asscipy.statsdistributions) or lists of discrete values.n_iter: the number of iterations for random search, i.e., the number of randomly selected hyperparameter combinations.
Example of using RandomizedSearchCV in scikit-learn:
Example
from
sklearn.
model_selection
import
RandomizedSearchCV
from
sklearn.
svm
import
SVC
from
sklearn.
datasets
import
load_iris
from
scipy.
stats
import
uniform
Load data
data
=
load_iris
(
)
X
,
y
=
data.
data
,
data.
target
Create the model
model
=
SVC
(
)
Define the hyperparameter distribution
param_distributions
=
{
'C'
: uniform
(
0
,
10
)
,
'kernel'
:
[
'linear'
,
'rbf'
]
}
Perform random search
random_search
=
RandomizedSearchCV
(
model
,
param_distributions
,
n_iter
=
10
,
cv
=
5
)
random_search.
fit
(
X
,
y
)
Output the best parameters and best score
(
f
"Best parameters: {random_search.best_params_}"
)
(
f
"Best score: {random_search.best_score_}"
)
random_search.best_params_: returns the best-performing hyperparameter combination found in the random search.random_search.best_score_: returns the cross validation score under the best parameter combination.
The output is shown below:
Best parameters: {'C': 8.355688344706016, 'kernel': 'rbf'}
Best score: 0.9866666666666667
3. Evaluate the model
Use classification_report, confusion_matrix, roc_auc_score
For classification models, we usually use metrics such as precision, recall, and F1 score to evaluate model performance.
scikit-learn provides many evaluation tools to help us gain deeper insight into the model's performance.
classification_report - provides information such as precision, recall, F1 score, and support (the number of samples per class).
Example
from
sklearn.
metrics
import
classification_report
Assume y_test is the true label and y_pred is the model prediction
(
classification_report
(
y_test
,
y_pred
)
)
confusion_matrix - the confusion matrix shows the performance of a classification model on each class, especially how positive classes are predicted as negative and vice versa.
Example
from
sklearn.
metrics
import
confusion_matrix
Assume y_test is the true label and y_pred is the model prediction
(
confusion_matrix
(
y_test
,
y_pred
)
)
roc_auc_score - ROC AUC (Area Under the Receiver Operating Characteristic curve) is a metric for evaluating classification model performance, especially suitable for imbalanced datasets. The higher the AUC value, the better the model performance.
Example
from
sklearn.
metrics
import
roc_auc_score
Assume y_test is the true label and y_pred_proba is the predicted probability of the model
(
f
"ROC AUC Score: {roc_auc_score(y_test, y_pred_proba)}"
)
Regression model evaluation: mean_squared_error, r2_score
For regression problems, commonly used evaluation metrics include Mean Squared Error (MSE) and the coefficient of determination (R2).
mean_squared_error - mean squared error is a common evaluation criterion for regression models, calculating the average of squared errors between predicted and true values.
Example
from
sklearn.
metrics
import
mean_squared_error
Assume y_test is the true value and y_pred is the predicted value
(
f
"Mean Squared Error: {mean_squared_error(y_test, y_pred)}"
)
r2_score - the coefficient of determination R2 measures how well the model fits the data; the closer the value is to 1, the better the model fit.
Example
from
sklearn.
metrics
import
r2_score
Assume y_test is the true value and y_pred is the predicted value
(
f
"R² Score: {r2_score(y_test, y_pred)}"
)