Scikit-learn Pipeline:构建可复用的 ML 流水线

Scikit-learn Pipeline:构建可复用的 ML 流水线

1. Pipeline 基础

python 复制代码
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier

# 创建流水线
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('pca', PCA(n_components=10)),
    ('clf', RandomForestClassifier(n_estimators=100))
])

# 训练
pipe.fit(X_train, y_train)

# 预测
y_pred = pipe.predict(X_test)

# 评分
score = pipe.score(X_test, y_test)

2. ColumnTransformer

python 复制代码
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

numeric_features = ['age', 'income', 'score']
categorical_features = ['city', 'gender']

preprocessor = ColumnTransformer([
    ('num', Pipeline([
        ('imputer', SimpleImputer(strategy='median')),
        ('scaler', StandardScaler()),
    ]), numeric_features),
    ('cat', Pipeline([
        ('imputer', SimpleImputer(strategy='most_frequent')),
        ('encoder', OneHotEncoder(handle_unknown='ignore')),
    ]), categorical_features),
])

# 完整流水线
pipe = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier())
])

3. 自定义 Transformer

python 复制代码
from sklearn.base import BaseEstimator, TransformerMixin

class FeatureEngineer(BaseEstimator, TransformerMixin):
    def __init__(self, add_interaction=True):
        self.add_interaction = add_interaction
    
    def fit(self, X, y=None):
        return self
    
    def transform(self, X):
        X = X.copy()
        X['price_per_sqft'] = X['price'] / X['area']
        if self.add_interaction:
            X['age_income'] = X['age'] * X['income']
        return X

# 使用
pipe = Pipeline([
    ('feature_eng', FeatureEngineer()),
    ('scaler', StandardScaler()),
    ('clf', RandomForestClassifier())
])

4. GridSearch + Pipeline

python 复制代码
from sklearn.model_selection import GridSearchCV

param_grid = {
    'pca__n_components': [5, 10, 15],
    'clf__n_estimators': [50, 100, 200],
    'clf__max_depth': [5, 10, None],
}

grid = GridSearchCV(pipe, param_grid, cv=5, scoring='accuracy')
grid.fit(X_train, y_train)
print(f"最佳参数: {grid.best_params_}")

总结

组件 作用
Pipeline 串联处理步骤
ColumnTransformer 按列分别处理
FeatureUnion 并行特征提取
自定义 Transformer 封装业务逻辑
相关推荐
糖炒栗子03269 小时前
learn-claude-code 简要记录
笔记·python
测试19989 小时前
Python接口测试之requests库安装和导入
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
%4710 小时前
DAY 34
python
leisoo809710 小时前
涨停板次日表现因子怎么挖掘本地化Python全流程实战
大数据·人工智能·python
像颗糖10 小时前
AG-UI:把 Agent 与前端之间的“私有暗号”变成标准协议
python·agent·ai编程
Zane199410 小时前
类也是对象?一文讲透元类 metaclass 这件"深度魔法"
后端·python
Fanta丶10 小时前
3.FastAPI ORM建表
python
jyOverQ10 小时前
LangGraph 记忆管理详解:短期记忆、长期记忆与 Runtime Context
python·langchain
云水初10 小时前
【agent篇】RAG 知识库构建避坑指南
开发语言·python·学习·agent·rag
2019一路前行10 小时前
Python 函数、循环语句
开发语言·python