Pipeline介紹
Pipeline是一種使資料預處理和模組化代碼井井有條的簡單方法。
具體來說,Pipeline流程打包捆綁了(bundles)預處理和模組化步驟,是以您可以像使用單個步驟一樣使用整個捆綁包。
許多資料科學家在沒有Pipeline的情況下将模型組合在一起,但Pipeline有一些重要的好處。其中包括:
- 更簡潔的代碼:在預處理的每個步驟中處理資料可能會變得混亂。使用管道,您無需在每個步驟手動跟蹤您的訓練和驗證資料。
- 更少的錯誤:錯誤應用步驟或忘記預處理步驟的機會更少。
- 更易于生産:将模型從原型轉換為可大規模部署的模型可能非常困難。我們不會在這裡讨論許多相關的問題,但管道可以提供幫助。
- 模型驗證的更多選項:例如交叉驗證。
例子
使用Melbourne Housing dataset的例子
先加載資料,并劃分訓練集和驗證集
這裡不詳細講解資料加載步驟。相反,您可以想象您已經在 X_train、X_valid、y_train 和 y_valid.n 中擁有訓練和驗證資料。
import pandas as pd
from sklearn.model_selection import train_test_split
# Read the data
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
# Separate target from predictors
y = data.Price
X = data.drop(['Price'], axis=1)
# Divide data into training and validation subsets
X_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,
random_state=0)
# "Cardinality" means the number of unique values in a column
# Select categorical columns with relatively low cardinality (convenient but arbitrary)
categorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and
X_train_full[cname].dtype == "object"]
# Select numerical columns
numerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in ['int64', 'float64']]
# Keep selected columns only
my_cols = categorical_cols + numerical_cols
X_train = X_train_full[my_cols].copy()
X_valid = X_valid_full[my_cols].copy()
我們使用下面的 head() 方法檢視訓練資料。
請注意,資料包含分類資料(categorical data)和具有缺失值的列(columns with missing values)。
有了Pipeline,兩者都可以輕松處理!
我們分三步建構完整的Pipeline。
第一步:定義預處理步驟(Define Preprocessing Steps)
類似于pipeline如何将預處理和模組化步驟捆綁在一起,
我們使用
ColumnTransformer
類将不同的預處理步驟捆綁在一起。
以下代碼:
估算 數值資料(numerical data) 中的缺失值,
估算缺失值并對 分類資料(categorical data) 應用 one-hot 編碼。
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
# Preprocessing for numerical data
numerical_transformer = SimpleImputer(strategy='constant')
# Preprocessing for categorical data
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Bundle preprocessing for numerical and categorical data
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_cols),
('cat', categorical_transformer, categorical_cols)
])
第二步: 定義模型 (Define the Model)
接下來,我們使用熟悉的
RandomForestRegressor
類定義一個随機森林模型。
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=100, random_state=0)
第 3 步:建立和評估Pipeline (Create and Evaluate the Pipeline)
最後,我們使用
Pipeline
類來定義捆綁預處理和模組化步驟的管道。
有幾個重要的事情需要注意:
-
通過Pipeline,我們預處理訓練資料并在一行代碼中拟合模型。
(相比之下,如果沒有管道,我們必須在不同的步驟中進行插補、one-hot編碼和模型訓練。如果我們必須同時處理數值和分類變量,這會變得特别混亂!)
-
通過Pipeline,我們提供X_valid 中未處理的特征到 predict() 指令,管道在生成預測之前自動預處理特征。
(但是,如果沒有Pipeline,我們必須要記得在進行預測之前對驗證資料進行預處理。)
from sklearn.metrics import mean_absolute_error
# Bundle preprocessing and modeling code in a pipeline
my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
('model', model)
])
# Preprocessing of training data, fit model
my_pipeline.fit(X_train, y_train)
# Preprocessing of validation data, get predictions
preds = my_pipeline.predict(X_valid)
# Evaluate the model
score = mean_absolute_error(y_valid, preds)
print('MAE:', score)
MAE: 160679.18917034855
結論
Pipeline對于整潔機器學習代碼和避免錯誤很有價值,對于具有複雜資料預處理的工作流尤其有用。