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:
- Transformer is an object that performs data transformation, such as data preprocessing (e.g., normalization, standardization, feature selection, etc.).
- Estimator is an object used to train a model, such as a classifier or regressor.
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
- Simpler code: combine multiple steps into a whole, simplifying code structure and management.
- Avoid data leakage: during data preprocessing, ensure that the handling of the training and test sets is isolated to avoid data leakage. For example, during standardization, the mean and standard deviation must not be computed on the test set.
- Reduce repetitive work: Through
PipelineIt can chain data preprocessing and model training together, avoiding rewriting preprocessing code for each training. - Improve reusability: encapsulate data processing and model training into a
Pipelineobject that can be reused across different projects and datasets. - Facilitate tuning: Through
PipelineIt can directly apply hyperparameter optimization, cross validation, etc. during tuning, simplifying the entire process.
Components of a Pipeline
A Pipeline consists of multiple steps, each of which is a tuple containing two elements:
- Step name(string type): used to identify each step.
- Transformer or Estimator: an object used for data processing or modeling.
Common steps include:
- Data preprocessing steps: such as data cleaning, standardization, encoding, etc.
- Model training step: such as classifiers, regressors, etc.
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
(
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:
- Data standardization(through
StandardScaler()): standardize the data so that each feature has a mean of 0 and a variance of 1. - 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
(
f
"Best parameters: {grid_search.best_params_}"
)
(
f
"Best score: {grid_search.best_score_}"
)
<
strong>Note:
svc__Candsvc__kernelIsPipelineMediumSVCstep's hyperparameters. By specifying these parameters inGridSearchCV, we can directly perform hyperparameter tuning onPipelinethe model in the pipeline.cv=5indicates 5-fold cross validation.
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
(
f
"Cross-validation scores: {cv_scores}"
)
(
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