昨天和剛來項目的機器學習小白解釋了一邊什么baseline 和pipeline,今天在這里總結一下什么是baseline和pipeline。
1.pipeline
1.1 從管道符到pipeline
先從在linux的管道符講起,
find ./ | grep wqbin | sort
inux體系下的各種命令工具的處理,可以使用管道符作為傳遞,這是一種良好的接口規范,工具的功能有公共的接口規范,就像流水線一樣,一步接着一步。
而我們只需改動每個參數就可以獲取我們想要的結果。該過程就被稱之管道機制。
一個基礎的 機器學習的Pipeline 主要包含了下述 5 個步驟:
- 數據讀取 - 數據預處理 - 創建模型 - 評估模型結果 - 模型調參
上5個步驟可以抽象為一個包括多個步驟的流水線式工作,從數據收集開始至輸出我們需要的最終結果。
因此,對以上多個步驟、進行抽象建模,簡化為流水線式工作流程則存在着可行性,流水線式機器學習比單個步驟獨立建模更加高效、易用。
管道機制在機器學習算法中得以應用的根源在於,參數集在新數據集(比如測試集)上的重復使用。
1.2sklearn中pipeline為例
sklearn也遵循pipeline機制,並封裝到 sklearn.pipline命名空間下面
pipeline.FeatureUnion(transformer_list[, …]) Concatenates results of multiple transformer objects. pipeline.Pipeline(steps[, memory]) Pipeline of transforms with a final estimator. pipeline.make_pipeline(*steps, **kwargs) Construct a Pipeline from the given estimators. pipeline.make_union(*transformers, **kwargs) Construct a FeatureUnion from the given trans
PIPELINE
sklearn中把機器學習處理過程抽象為estimator,其中estimator都有fit方法,表示數據進行初始化or訓練。estimator有2種:
1、特征變換(transformer)
可以理解為特征工程,即:特征標准化、特征正則化、特征離散化、特征平滑、onehot編碼等。該類型統一由一個transform方法,用於fit數據之后,輸入新的數據,進行特征變換。
2、預測器(predictor)
即各種模型,所有模型fit進行訓練之后,都要經過測試集進行predict所有,有一個predict的公共方法。
上面的抽象的好處即可實現機器學習的pipeline,顯然特征變換是可能並行的,通過FeatureUnion實現。特征變換在訓練集、測試集之間都需要統一,所以pipeline可以達到模塊化的目的。舉個NLP處理的例子:
# 生成訓練數據、測試數據 X_train, X_test, y_train, y_test = train_test_split(X, y) # pipeline定義 pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', RandomForestClassifier()) ]) # train classifier pipeline.fit(X_train, y_train) # predict on test data y_pred = pipeline.predict(X_test)
FEATUREUNION
上面看到特征變換往往需要並行化處理,即FeatureUnion所實現的功能。
pipeline = Pipeline([ ('features', FeatureUnion([ ('text_pipeline', Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()) ])), ('findName', FineNameExtractor()) ])) ('clf', RandomForestClassifier()) ])
pipeline還可以嵌套pipeline,整個機器學習處理流程就像流水工人一樣。
上面自定義了一個pipeline處理對象FineNameExtractor,該對象是transformer,自定義一個transformer是很簡單的,創建一個對象,繼承自BaseEstimator, TransformerMixin即可,
代碼如下:
from sklearn.base import BaseEstimator, TransformerMixin class FineNameExtractor(BaseEstimator, TransformerMixin): def find_name(self, text): return True def fit(self, X, y=None): return self def transform(self, X): X_tagged = pd.Series(X).apply(self.find_name) return pd.DataFrame(X_tagged)
執行一個PIPELINE,加上自動調參就可以了,sklearn的調參通過GridSearchCV實現=》pipeline+gridsearch。
GridSearchCV實際上也有fit、predict方法,所以,訓練與預測高效抽象的,代碼很簡潔。