sklearn 中的 Pipeline 機制
from sklearn.pipeline import Pipeline
管道機制在機器學習演算法中得以應用的根源在於,引數集在新資料集(比如測試集)上的重複使用。
管道機制實現了對全部步驟的流式化封裝和管理(streaming workflows with pipelines)。
注意:管道機制更像是程式設計技巧的創新,而非演算法的創新。
接下來我們以一個具體的例子來演示sklearn庫中強大的Pipeline用法:
1. 載入資料集
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'
'breast-cancer-wisconsin/wdbc.data', header=None)
# Breast Cancer Wisconsin dataset
X, y = df.values[:, 2:], df.values[:, 1]
# y為字元型標籤
# 使用LabelEncoder類將其轉換為0開始的數值型
encoder = LabelEncoder()
y = encoder.fit_transform(y)
>>> encoder.transform(['M', 'B'])
array([1, 0])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)
2. 構思演算法的流程
可放在Pipeline中的步驟可能有:
- 特徵標準化是需要的,可作為第一個環節
- 既然是分類器,classifier也是少不了的,自然是最後一個環節
- 中間可加上比如資料降維(PCA)
- 。。。
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
pipe_lr = Pipeline([('sc', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', LogisticRegression(random_state=1))
])
pipe_lr.fit(X_train, y_train)
print('Test accuracy: %.3f' % pipe_lr.score(X_test, y_test))
# Test accuracy: 0.947
Pipeline物件接受二元tuple構成的list,每一個二元 tuple 中的第一個元素為 arbitrary identifier string,我們用以獲取(access)Pipeline object 中的 individual elements,二元 tuple 中的第二個元素是 scikit-learn與之相適配的transformer 或者 estimator。
Pipeline([('sc', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', LogisticRegression(random_state=1))])
3. Pipeline執行流程的分析
Pipeline 的中間過程由scikit-learn相適配的轉換器(transformer)構成,最後一步是一個estimator。比如上述的程式碼,StandardScaler和PCA transformer 構成intermediate steps,LogisticRegression 作為最終的estimator。
當我們執行 pipe_lr.fit(X_train, y_train)
時,首先由StandardScaler在訓練集上執行 fit和transform方法,transformed後的資料又被傳遞給Pipeline物件的下一步,也即PCA()。和StandardScaler一樣,PCA也是執行fit和transform方法,最終將轉換後的資料傳遞給 LosigsticRegression。整個流程如下圖所示:
4. pipeline 與深度神經網路的multi-layers
只不過步驟(step)的概念換成了層(layer)的概念,甚至the last step 和 輸出層的含義都是一樣的。
只是丟擲一個問題,是不是有那麼一丟丟的相似性?