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

Sklearn Model Evaluation and Tuning

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:

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

print

(

f

"Cross-validation scores: {scores}"

)

print

(

f

"Mean accuracy: {scores.mean()}"

)

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:**

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

print

(

f

"Best parameters: {grid_search.best_params_}"

)

print

(

f

"Best score: {grid_search.best_score_}"

)

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:

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

print

(

f

"Best parameters: {random_search.best_params_}"

)

print

(

f

"Best score: {random_search.best_score_}"

)

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

print

(

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

print

(

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

print

(

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

print

(

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

print

(

f

"R² Score: {r2_score(y_test, y_pred)}"

)