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 封装业务逻辑
相关推荐
米码收割机7 小时前
【Python】Flask+SQLite_web 宠物领养系统 (源码+文档)【独一无二】
前端·python·flask
卷无止境7 小时前
python进阶:类方法与静态方法的分野,classmethod 和 staticmethod 到底该怎么选
后端·python
卷无止境8 小时前
继承与多态:Python OOP里最容易被用错的两把梯子
后端·python
SelectDB技术团队8 小时前
丰巢日志平台 ELK 替代:Apache Doris / SelectDB 的技术能力与实践
开发语言·python
崖边看雾8 小时前
Python学习——函数
开发语言·windows·python·学习·pycharm
深念Y8 小时前
Windows幽灵端口占用:HNS如何无声偷走你的端口
windows·python·bug·环境·端口·特权
宸津-代码粉碎机8 小时前
Jar热部署进阶实战|修复原生方案OOM与类冲突问题,生产级无BUG优化方案
java·大数据·服务器·开发语言·前端·人工智能·python
未知违规用户10 小时前
大模型项目:RAG项目实战与FlagEmbedding模型
人工智能·windows·python·深度学习