跳轉到

sklearn Pipeline 與資料前處理模板:為什麼前處理一定要包進去?

難度:入門到中。會用 sklearn 的 fit / predict。 本頁的實驗數字來自 Python 3.12、scikit-learn 1.9.1,2026-10-04 執行。 本頁定位:本區的程式碼骨架頁,回答「怎麼寫」。該做哪些前處理見〈特徵工程心法〉;評估與 CV 的策略見〈模型評估與 Cross-Validation 實務〉。

前言

Pipeline 常被介紹成「讓程式碼比較整齊」的工具。整齊是真的,但不是最重要的理由。最重要的理由是:不用 Pipeline,CV 分數很容易是假的,而且你不會發現。

本頁回答三個問題,後半是可以直接複製的模板:

  • 為什麼前處理一定要包進 Pipeline?(先講結論:前處理只要在 CV 外面做,就會看到驗證折的資料。在 100 筆、5,000 個純雜訊特徵的資料上,先選特徵再做 CV,準確率 0.870;包進 Pipeline,回到 0.500。)
  • 數值和類別混在一起的資料怎麼寫?(用 ColumnTransformer 讓不同欄位走不同的前處理,再整個包進一個 Pipeline。)
  • 存下來部署要注意什麼?(存整個 Pipeline 而不是只存模型;載入時 sklearn 版本要對得上;別載入來路不明的 joblib/pickle 檔。)

1. 實驗:先選特徵,再做 CV

我們造一份完全沒有訊號的資料:100 筆、5,000 個特徵,全是標準常態亂數;標籤是隨機的 0 和 1。任何方法的準確率都應該在 0.5 左右。

錯誤寫法:先在全部資料上選出和 y 最相關的 20 個特徵,再拿這 20 個特徵做 5 折 CV。

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 5000)); y = rng.integers(0, 2, 100)
cv = StratifiedKFold(5, shuffle=True, random_state=0)

X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)     # 錯:用全部資料選
cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=cv).mean()

正確寫法:把特徵選擇和模型包進同一個 Pipeline,讓每一折只用訓練折去選。

pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
cross_val_score(pipe, X, y, cv=cv).mean()
寫法 5 折 CV 準確率
先選特徵再 CV 0.870
包進 Pipeline 0.500

5,000 個雜訊特徵裡,總會有幾十個剛好和這 100 個隨機標籤相關。在全部資料上挑,等於挑出「在驗證折上也剛好相關」的那 20 個。CV 再怎麼切,驗證折的答案早在選特徵時就被看過了。

這個例子是《The Elements of Statistical Learning》7.10.2 節的經典示範,特徵越多、樣本越少,錯得越嚴重。現實中的基因資料、文字資料,常常就是這種「特徵比樣本多很多」的形狀。

標準化也是同一類錯誤,只是影響通常小得多:平均和標準差只是兩個數字,能帶過去的資訊有限。特徵選擇、target encoding、重採樣(SMOTE)會帶過去的資訊就多了。規則一律相同:所有用到資料的前處理,都包進 Pipeline。

Pipeline 的另外兩個好處:

  • 部署一致:訓練好的 Pipeline 是一個物件,上線只要 pipeline.predict(X_new),不需要手動重現前處理。
  • 調參乾淨:GridSearchCV(pipeline, ...) 可以同時調前處理和模型的參數,每一折都完整重跑前處理。

常見誤解:我有切測試集,所以沒有洩漏

測試集切出來,確實沒被看到。但如果特徵選擇是在「訓練+驗證」上先做完,再拿去做 CV 調參,CV 分數一樣是假的,你會依據假分數選出錯的超參數和特徵數量。 後果是測試分數比 CV 低很多,然後開始懷疑是不是測試集「運氣不好」。

2. 基礎 Pipeline

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

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression(max_iter=1000, random_state=42))
])

pipe.fit(X_train, y_train)
pipe.score(X_test, y_test)         # accuracy
pipe.predict(X_test)               # 預測類別
pipe.predict_proba(X_test)[:, 1]   # 預測機率

Pipeline 的步驟除最後一步以外必須實作 transform;最後一步通常是模型。


3. ColumnTransformer:處理混合型態資料

實務資料幾乎都是混合型態(數值 + 類別),ColumnTransformer 讓不同欄位走不同前處理管道。

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, OrdinalEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier

# --- 定義欄位類型 ---
num_cols = ['age', 'income', 'tenure']
cat_onehot_cols = ['city', 'product_type']          # 低基數類別 → OneHot
cat_ordinal_cols = ['education']                    # 有序類別 → Ordinal

# --- 各管道 ---
num_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler',  StandardScaler()),
])

cat_onehot_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False)),
])

cat_ordinal_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OrdinalEncoder(
        categories=[['High School', 'Bachelor', 'Master', 'PhD']],
        handle_unknown='use_encoded_value',
        unknown_value=-1
    )),
])

# --- 組合 ---
preprocessor = ColumnTransformer([
    ('num',         num_pipe,          num_cols),
    ('cat_onehot',  cat_onehot_pipe,   cat_onehot_cols),
    ('cat_ordinal', cat_ordinal_pipe,  cat_ordinal_cols),
], remainder='drop')  # 其餘欄位丟掉;用 'passthrough' 原樣保留

# --- 完整 Pipeline ---
full_pipe = Pipeline([
    ('preprocessor', preprocessor),
    ('clf', GradientBoostingClassifier(random_state=42)),
])

full_pipe.fit(X_train, y_train)

常用 Transformer 速查

Transformer 適用情境 重要參數
SimpleImputer 填補缺失值 strategy: mean/median/most_frequent/constant
StandardScaler 線性模型、SVM、KNN、NN —
MinMaxScaler 需要 [0,1] 範圍 feature_range
RobustScaler 離群值多時 quantile_range
OneHotEncoder 低基數名義類別(< ~20) handle_unknown='ignore'(上線安全)
OrdinalEncoder 有序類別、樹模型 categories 明確指定順序
TargetEncoder 高基數類別(sklearn ≥ 1.3) smooth, 內建 CV 防 leakage
PowerTransformer 讓數值更接近常態分布 method='yeo-johnson'(支援負值)
PolynomialFeatures 加入交互項與多項式特徵 degree, interaction_only
SelectKBest / SelectFromModel 特徵選擇 放在 preprocessor 後、模型前

4. 自訂 Transformer

當內建 transformer 不夠用時,繼承 BaseEstimator + TransformerMixin:

from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np

class LogTransformer(BaseEstimator, TransformerMixin):
    """對指定欄位做 log1p 轉換(支援 Pipeline fit/transform 介面)。"""

    def __init__(self, cols=None):
        self.cols = cols  # None = 全部欄位

    def fit(self, X, y=None):
        return self  # 無需 fit,直接回傳 self

    def transform(self, X):
        X = X.copy()
        cols = self.cols if self.cols else X.columns.tolist()
        X[cols] = np.log1p(X[cols])
        return X

放進 Pipeline:

pipe = Pipeline([
    ('log', LogTransformer(cols=['income', 'tenure'])),
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression()),
])

FunctionTransformer:輕量的一次性轉換

不需要新 class 時,用 FunctionTransformer 包一個函式:

from sklearn.preprocessing import FunctionTransformer

log_transformer = FunctionTransformer(np.log1p, validate=True)

5. Pipeline + GridSearchCV

超參數名稱用 步驟名__參數名(雙底線):

from sklearn.model_selection import GridSearchCV, StratifiedKFold

param_grid = {
    'preprocessor__num__imputer__strategy': ['mean', 'median'],
    'clf__n_estimators': [100, 300],
    'clf__max_depth': [3, 5, None],
    'clf__learning_rate': [0.05, 0.1],
}

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
grid_search = GridSearchCV(
    full_pipe,
    param_grid,
    cv=cv,
    scoring='roc_auc',
    n_jobs=-1,
    verbose=1,
)
grid_search.fit(X_train, y_train)

print("Best params:", grid_search.best_params_)
print("Best CV AUC:", grid_search.best_score_)
print("Test AUC:", roc_auc_score(y_test, grid_search.predict_proba(X_test)[:, 1]))

n_jobs=-1 使用所有 CPU 核心並行;verbose=1 顯示進度。

RandomizedSearchCV:超參數空間大時的替代

from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, uniform

param_dist = {
    'clf__n_estimators': randint(100, 500),
    'clf__max_depth': [3, 5, 7, None],
    'clf__learning_rate': uniform(0.01, 0.2),
    'clf__subsample': uniform(0.6, 0.4),
}

rand_search = RandomizedSearchCV(
    full_pipe,
    param_dist,
    n_iter=50,
    cv=cv,
    scoring='roc_auc',
    n_jobs=-1,
    random_state=42,
)
rand_search.fit(X_train, y_train)

6. 查看 Pipeline 結構與特徵名稱

# 顯示 Pipeline 架構(Jupyter 中有視覺化)
from sklearn import set_config
set_config(display='diagram')
full_pipe

# 取得 OneHotEncoder 後的欄位名稱
feature_names = full_pipe.named_steps['preprocessor'].get_feature_names_out()

# 取得各步驟
preprocessor = full_pipe.named_steps['preprocessor']
model = full_pipe.named_steps['clf']

7. 儲存與載入

import joblib

# 儲存(包含前處理的所有 fit 狀態 + 模型權重)
joblib.dump(full_pipe, 'model_pipeline.joblib')

# 載入並預測(只需要一行)
loaded_pipe = joblib.load('model_pipeline.joblib')
predictions = loaded_pipe.predict(X_new)

⚠️ 用 joblib 而非 pickle——joblib 存大型 numpy array 比較有效率。兩者載入時都可能執行任意程式碼,來路不明的檔案別載。版本要對齊:載入時的 sklearn 版本應和儲存時相同或相容,否則可能拋 warning 甚至錯誤。


8. 完整可複製模板

import pandas as pd
import numpy as np
import joblib
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import (
    train_test_split, StratifiedKFold, RandomizedSearchCV, cross_val_score
)
from sklearn.metrics import roc_auc_score, average_precision_score, classification_report
from scipy.stats import randint, uniform

# ── 1. 切分資料 ────────────────────────────────────────────
X_temp, X_test, y_temp, y_test = train_test_split(
    X, y, test_size=0.15, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
    X_temp, y_temp, test_size=0.18, stratify=y_temp, random_state=42
)

# ── 2. 定義欄位 ────────────────────────────────────────────
num_cols = [c for c in X.columns if X[c].dtype in ['int64', 'float64']]
cat_cols  = [c for c in X.columns if X[c].dtype == 'object']

# ── 3. 建 Preprocessor ────────────────────────────────────
num_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler',  StandardScaler()),
])
cat_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False)),
])
preprocessor = ColumnTransformer([
    ('num', num_pipe, num_cols),
    ('cat', cat_pipe, cat_cols),
])

# ── 4. 完整 Pipeline ──────────────────────────────────────
pipe = Pipeline([
    ('preprocessor', preprocessor),
    ('clf', GradientBoostingClassifier(random_state=42)),
])

# ── 5. 超參數搜索 ─────────────────────────────────────────
param_dist = {
    'clf__n_estimators': randint(100, 400),
    'clf__max_depth': [3, 5, 7],
    'clf__learning_rate': uniform(0.05, 0.15),
    'clf__subsample': uniform(0.7, 0.3),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = RandomizedSearchCV(pipe, param_dist, n_iter=40, cv=cv,
                             scoring='roc_auc', n_jobs=-1, random_state=42)
search.fit(X_train, y_train)
best_pipe = search.best_estimator_

# ── 6. 驗證集評估 ─────────────────────────────────────────
val_prob = best_pipe.predict_proba(X_val)[:, 1]
print(f"Val AUC-ROC : {roc_auc_score(y_val, val_prob):.4f}")
print(f"Val PR-AUC  : {average_precision_score(y_val, val_prob):.4f}")

# ── 7. 最終測試集評估(只碰一次)─────────────────────────
test_prob = best_pipe.predict_proba(X_test)[:, 1]
print(f"Test AUC-ROC: {roc_auc_score(y_test, test_prob):.4f}")
print(classification_report(y_test, best_pipe.predict(X_test)))

# ── 8. 儲存 ──────────────────────────────────────────────
joblib.dump(best_pipe, 'model_pipeline.joblib')

結論

回到前言的三個問題。

為什麼前處理一定要包進 Pipeline? 在 CV 外面做的前處理會看到驗證折。純雜訊資料上,先選特徵再 CV 拿到 0.870,包進 Pipeline 是 0.500。特徵越多、樣本越少,錯得越多。

混合型態資料怎麼寫? ColumnTransformer 分欄位處理,再和模型包成一個 Pipeline(§3、§8)。

部署要注意什麼? 存整個 Pipeline;sklearn 版本要對齊;不要載入來路不明的檔案(§7)。

延伸:這篇真正想留下的問題

Pipeline 解決的不是程式風格,而是一個時間順序的問題:在真實上線時,模型拿到一筆新資料,它手上有什麼? 它只有訓練時存下來的平均、選好的特徵、算好的編碼,沒有新資料的答案。

CV 的每一折都應該重現這個情境。寫前處理時的檢查只有一條:上線那一刻,這個數字算得出來嗎?


延伸閱讀(本站)

參考資料