本文轉自 https://blog.csdn.net/lanchunhui/article/details/50521648
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 和 輸出層的含義都是一樣的。
只是拋出一個問題,是不是有那么一丟丟的相似性?