パイプライン構築(例: scikit-learnのPipeline)

機械学習におけるパイプライン構築は、前処理からモデル学習・予測までの一連の処理を**一つの統一された流れ(ワークフロー)**として管理・実行する手法です。特に、scikit-learn ライブラリでは、Pipeline クラスを用いてこのような処理を簡潔に記述することができます。


1. パイプラインの目的

  • 再現性の確保:データの前処理から学習・予測までを一貫して適用可能。

  • コードの簡潔化:複数の処理を一つにまとめて可読性を向上。

  • ハイパーパラメータのチューニングが容易GridSearchCVRandomizedSearchCV で一括して調整可能。

  • データリークの防止:訓練データのみに前処理を適用し、適切に検証データと分離できる。


2. 基本的な構成

scikit-learnのPipelineは、以下のように複数の処理ステップ(変換器 transformer推定器 estimator)を順に定義します。

python
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression pipeline = Pipeline([ ('scaler', StandardScaler()), # 特徴量のスケーリング ('classifier', LogisticRegression()) # モデル学習 ])

各ステップには (名前, インスタンス) のタプルを指定し、最後のステップは予測器でなければなりません(fit メソッドを持ち、predict できるオブジェクト)。


3. 典型的な使用例

python
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # データ読み込みと分割 X, y = load_iris(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # パイプライン適用 pipeline.fit(X_train, y_train) y_pred = pipeline.predict(X_test)

4. PipelineGridSearchCVの連携

ハイパーパラメータのチューニングも容易に行えます。

python
from sklearn.model_selection import GridSearchCV param_grid = { 'classifier__C': [0.1, 1.0, 10.0], # 'classifier'はPipelineのステップ名 } grid = GridSearchCV(pipeline, param_grid, cv=5) grid.fit(X_train, y_train)

5. ColumnTransformerとの併用(複数の特徴量処理)

異なる列に異なる前処理を適用したい場合は、ColumnTransformerと組み合わせて使います。

python
from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.impute import SimpleImputer preprocessor = ColumnTransformer(transformers=[ ('num', StandardScaler(), [0, 1, 2]), # 数値列のスケーリング ('cat', OneHotEncoder(), [3]) # カテゴリ列のエンコーディング ]) pipeline = Pipeline([ ('preprocess', preprocessor), ('clf', LogisticRegression()) ])

6. まとめ

機能 説明
Pipeline([...]) 一連の処理ステップを定義
fit() / predict() 全体を一貫して処理
GridSearchCV との連携 ハイパーパラメータ最適化
ColumnTransformerとの組み合わせ 列ごとの異なる前処理

補足事項

  • 各ステップの名前は一意である必要があります。

  • ステップ名の後に続く処理オブジェクトは、fittransform(または fit_transform)を持つ必要があります。

  • 最後のステップは必ず予測器(分類器や回帰器)でなければなりません。

生成日:2025/06/01