什么是 Sklearn Pipeline

Sklearn Pipeline 是 scikit-learn 提供的一个工具,用于将多个数据处理和建模步骤组合为一个整体工作流。它能够自动化数据预处理、特征选择和模型训练过程,确保数据在训练和预测时的一致性,同时减少代码冗余。

Pipeline 的核心优势在于:

  • 避免数据泄露(Data Leakage)
  • 简化代码结构
  • 支持超参数调优(GridSearchCV 或 RandomizedSearchCV)

基本 Pipeline 构建

一个简单的 Pipeline 通常包含数据预处理和模型训练两个部分。以下是一个标准化数据后训练逻辑回归模型的示例:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

# 创建 Pipeline
pipe = Pipeline([
    ('scaler', StandardScaler()),  # 标准化
    ('classifier', LogisticRegression())  # 分类器
])

# 使用 Pipeline 训练和预测
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)

复杂 Pipeline 构建

对于更复杂的数据处理流程,可以使用 ColumnTransformer 结合 Pipeline 对不同特征进行不同的预处理:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler

# 定义数值和类别列
numeric_features = ['age', 'income']
categorical_features = ['gender', 'education']

# 创建预处理步骤
preprocessor = ColumnTransformer([
    ('num', MinMaxScaler(), numeric_features),
    ('cat', OneHotEncoder(), categorical_features)
])

# 构建完整 Pipeline
full_pipe = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier())
])

full_pipe.fit(X_train, y_train)

Pipeline 与网格搜索结合

Pipeline 可以方便地与超参数调优工具结合,统一调整预处理和模型参数:

from sklearn.model_selection import GridSearchCV

# 定义参数网格
param_grid = {
    'preprocessor__num__strategy': ['mean', 'median'],
    'classifier__n_estimators': [50, 100, 200],
    'classifier__max_depth': [None, 5, 10]
}

# 创建网格搜索对象
grid_search = GridSearchCV(full_pipe, param_grid, cv=5)
grid_search.fit(X_train, y_train)

# 输出最佳参数
print(grid_search.best_params_)

自定义转换器集成

可以创建自定义转换器并集成到 Pipeline 中:

from sklearn.base import BaseEstimator, TransformerMixin

class CustomTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, multiplier=1):
        self.multiplier = multiplier
    
    def fit(self, X, y=None):
        return self
    
    def transform(self, X):
        return X * self.multiplier

# 集成自定义转换器
custom_pipe = Pipeline([
    ('custom', CustomTransformer(multiplier=10)),
    ('model', LinearRegression())
])

多模型 Pipeline 比较

可以构建多个 Pipeline 来比较不同算法:

from sklearn.svm import SVC
from sklearn.ensemble import GradientBoostingClassifier

# 定义多个 Pipeline
pipelines = {
    'svm': Pipeline([
        ('scaler', StandardScaler()),
        ('svm', SVC())
    ]),
    'gbdt': Pipeline([
        ('preprocessor', preprocessor),
        ('gbdt', GradientBoostingClassifier())
    ])
}

# 训练并比较模型
for name, pipeline in pipelines.items():
    pipeline.fit(X_train, y_train)
    score = pipeline.score(X_test, y_test)
    print(f"{name} accuracy: {score:.4f}")

模型持久化与部署

训练好的 Pipeline 可以保存为单一文件,便于部署:

import joblib

# 保存 Pipeline
joblib.dump(full_pipe, 'model_pipeline.pkl')

# 加载 Pipeline
loaded_pipe = joblib.load('model_pipeline.pkl')
y_pred = loaded_pipe.predict(new_data)

常见问题与解决方案

  • 内存问题:对于大数据集,可以在 Pipeline 步骤中设置 memory 参数缓存中间结果

    from sklearn.pipeline import Pipeline
    from joblib import Memory
    
    memory = Memory(location='./cache')
    pipe = Pipeline([...], memory=memory)
    

  • 调试 Pipeline:使用 set_params 检查中间步骤

    pipe.set_params(classifier__max_depth=5).fit(X_train, y_train)
    

  • 特征名称保留:使用 set_output API 保持特征名称

    pipe.set_output(transform="pandas")
    

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐