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

Sklearn Pipeline

Sklearn Pipeline

In machine learning projects, steps such as data processing, feature engineering, model training, and evaluation are often interdependent, and the order and coordination of these steps are crucial to the final model's performance.

Pipeline is an important tool in scikit-learn for organizing and simplifying these steps.

Through Pipeline, we can integrate data preprocessing with model training, thereby simplifying the workflow and improving code reusability.

What is a Pipeline

A Pipeline is a tool that can execute multiple data processing steps and model training steps in sequence.

In a Pipeline, each step is a tuple containing a name and an object.

Each object is usually a Transformer or an Estimator, where:

Pipeline It makes it simple to integrate multiple steps into a reusable workflow and ensures consistency in the data processing, avoiding errors caused by code duplication or manual handling.

Why use a Pipeline

Components of a Pipeline

A Pipeline consists of multiple steps, each of which is a tuple containing two elements:

  1. Step name(string type): used to identify each step.
  2. Transformer or Estimator: an object used for data processing or modeling.

Common steps include:


Create a simple Pipeline

Suppose we have a dataset and need to standardize the data before training a Support Vector Machine (SVM) classifier. We can combine the standardization and model training steps into a Pipeline.

Example

from

sklearn.

pipeline

import

Pipeline

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

svm

import

SVC

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

datasets

import

load_iris

Load data

data

=

load_iris

(

)

X

,

y

=

data.

data

,

data.

target

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Create the Pipeline

pipeline

=

Pipeline

(

[

   

(

'scaler'

,

StandardScaler

(

)

)

,

 

Data standardization

   

(

'svc'

,

SVC

(

)

)

 

Support Vector Machine classifier

]

)

Train the model

pipeline.

fit

(

X_train

,

y_train

)

Prediction result

y_pred

=

pipeline.

predict

(

X_test

)

Print the model accuracy

print

(

f

"Model accuracy: {pipeline.score(X_test, y_test)}"

)

Run the above code; the output is as follows:



Model accuracy: 1.0

How Pipeline works

In the example above, the Pipeline performs two steps:

  1. Data standardization(through StandardScaler()): standardize the data so that each feature has a mean of 0 and a variance of 1.
  2. Model training(through SVC()): train the Support Vector Machine classifier on the standardized data.

Pipeline 's workflow is: first execute the data preprocessing step (such as standardization), then pass the processed data to the model for training. This process can be done through pipeline.fit() in one step, andpipeline.predict() when making predictions, the data also passes through each step in the pipeline in the same order.


Advantages of Pipeline

Simplify code and workflow

Through Pipeline, we can integrate multiple steps into one object, thereby reducing the code for manually executing multiple steps.

Without using it, preprocessing needs to be executed multiple times:

Example

Without Pipeline (requires executing preprocessing multiple times)

scaler

=

StandardScaler

(

)

X_train_scaled

=

scaler.

fit_transform

(

X_train

)

X_test_scaled

=

scaler.

transform

(

X_test

)

model

=

SVC

(

)

model.

fit

(

X_train_scaled

,

y_train

)

y_pred

=

model.

predict

(

X_test_scaled

)

Using Pipeline, complete in one step:

Example

With Pipeline (complete in one step)

pipeline

=

Pipeline

(

[

   

(

'scaler'

,

StandardScaler

(

)

)

,

   

(

'svc'

,

SVC

(

)

)

]

)

pipeline.

fit

(

X_train

,

y_train

)

y_pred

=

pipeline.

predict

(

X_test

)

Ensure consistency in training and test data processing

Without a Pipeline, if we manually perform data processing and training, we might accidentally use different processing methods for the training and test sets, causing data leakage.

For example, we compute the mean and variance for standardization on the training set, but if we compute different mean and variance on the test set, the model evaluation becomes inaccurate. Using a Pipeline ensures consistency in these processing methods.

Automate the entire process

Pipeline allows us to encapsulate multiple steps into one object, automating the entire process of data preprocessing, model training, and prediction. Through this automated process, human errors can be reduced and code reusability can be improved.


Pipeline tuning and optimization

When we use a Pipeline, we can perform hyperparameter tuning directly.

By combining GridSearchCV or RandomizedSearchCV, we can optimize the hyperparameters of every step in the pipeline.

Use GridSearchCV to tune the hyperparameters in the Pipeline:

Example

from

sklearn.

pipeline

import

Pipeline

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

svm

import

SVC

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

GridSearchCV

Load data

data

=

load_iris

(

)

X

,

y

=

data.

data

,

data.

target

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Create the Pipeline

pipeline

=

Pipeline

(

[

   

(

'scaler'

,

StandardScaler

(

)

)

,

 

Data standardization

   

(

'svc'

,

SVC

(

)

)

 

Support Vector Machine classifier

]

)

Train the model

pipeline.

fit

(

X_train

,

y_train

)

Define the hyperparameter grid

param_grid

=

{

   

'svc__C'

:

[

0.1

,

1

,

10

]

,

 

Adjust the C parameter in SVC

   

'svc__kernel'

:

[

'linear'

,

'rbf'

]

 

Adjust the kernel parameter

}

Create the GridSearchCV object

grid_search

=

GridSearchCV

(

pipeline

,

param_grid

,

cv

=

5

)

Perform hyperparameter tuning

grid_search.

fit

(

X_train

,

y_train

)

Output the best parameters and score

print

(

f

"Best parameters: {grid_search.best_params_}"

)

print

(

f

"Best score: {grid_search.best_score_}"

)

<

strong>Note:

The output is as follows:

Best parameters: {'svc__C': 0.1, 'svc__kernel': 'linear'}

Best score: 0.9583333333333334


Use Pipeline for cross validation

Pipeline and cross validation can be combined to ensure the entire model evaluation process is consistent. In cross validation, each iteration preprocesses the training data and then trains the model for validation.

Example

from

sklearn.

pipeline

import

Pipeline

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

svm

import

SVC

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

cross_val_score

Load data

data

=

load_iris

(

)

X

,

y

=

data.

data

,

data.

target

Split the dataset into training and test sets

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Create the Pipeline

pipeline

=

Pipeline

(

[

   

(

'scaler'

,

StandardScaler

(

)

)

,

 

Data standardization

   

(

'svc'

,

SVC

(

)

)

 

Support Vector Machine classifier

]

)

Train the model

pipeline.

fit

(

X_train

,

y_train

)

Perform 5-fold cross validation

cv_scores

=

cross_val_score

(

pipeline

,

X

,

y

,

cv

=

5

)

Output the cross validation scores

print

(

f

"Cross-validation scores: {cv_scores}"

)

print

(

f

"Mean cross-validation score: {cv_scores.mean()}"

)

In this example, cross_val_score automatically performs cross validation on the data while standardizing the data before each training.

The output is as follows:

Cross-validation scores: [0.96666667 0.96666667 0.96666667 0.93333333 1.        ]

Mean cross-validation score: 0.9666666666666666