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 封装业务逻辑
相关推荐
147API1 小时前
Claude global workspace 研究给智能体测试提了一个醒
人工智能·算法·机器学习
闲猫1 小时前
深入理解 Skills:从 API 调用到智能体行为封装
人工智能·python·langchain
葫三生1 小时前
《论三生原理》与模糊数学的关联、异同、互补关系?
人工智能·科技·算法·机器学习·开源
还是鼠鼠1 小时前
AI掘金头条新闻系统 (Toutiao News)-缓存相关推荐新闻
后端·python·mysql·fastapi·web
骑士雄师1 小时前
大模型:runnable
python·embedding
2401_868534781 小时前
系统分析师案例分析题常考知识点
python·计算机网络
格林威2 小时前
网口相机 vs USB相机:区别与适用场景(选型不再纠结)
人工智能·数码相机·机器学习·计算机视觉·视觉检测·机器视觉·工业相机
江华森2 小时前
Python 实现 2048 游戏(三):面向对象重构与AI模拟
python
可以飞的话3 小时前
五、数据处理1
python