Pipeline 이란?
-> 데이터 전처리 및 모델링 코드를 체계적으로 정리할 수 있는 간단한 방법
특히 Pipeline은 전처리와 모델링 단계를 묶어서 하나의 단계처럼 사용할 수 있도록 전체 번들을 제공
더 깔끔한 코드: 전처리 각 단계에서 데이터를 설명하는 것은 지저분해질 수 있음
파이프라인을 사용하면 각 단계에서 학습 및 유효성 검사 데이터를 수동으로 추적할 필요가 없음
버그 감소: 단계를 잘못 적용하거나 전처리 단계를 잊어버릴 가능성이 줄어듬
더 쉬운 프로덕션화: 프로토타입에서 대규모 배포가 가능한 모델로 전환하는 것은 의외로 어려울 수 있음
여기서는 이와 관련된 많은 문제를 다루지는 않겠지만 Pipeline이 도움이 될 수 있음
Model validation을 위한 더 많은 옵션: 다음 튜토리얼에서 교차 유효성 검사를 다루는 예제를 볼 수 있음
Melbourne Housing dataset을 사용
import pandas as pd
from sklearn.model_selection import train_test_split
data = pd.read_csv(filepath)
# 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)
caregorical_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와 결측값이 있는 열이 모두 포함되어있음을 알 수 있다.
pipeline을 사용하면 이 두 가지(categorical data, 결측값)를 모두 쉽게 처리할 수 있음
X_train.head()
pipeline이 전처리 및 모델링 단계를 함께 묶는 방식과 유사하게, columnTransformer 클래스를 사용하여 다양한 전처리 단계를 함께 묶는다.
아래의 코드는
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipiline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
# numerical data를 전처리
numerical_transformer = SimpleImputer(strategy='constant')
# 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)
])
RandomForestRegressor class를 사용
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=100, random_state=0)
마지막으로 pipeline class를 사용하여 전처리 & 모델링 단계를 번들로 묶는 pipeline을 정의함
중요한 사항
from sklearn.metrics import mean_absolute_error
# Bunde 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 model
score = mean_absolute_error(y_valid, preds)
print('MAE: ', score)
pipeline은 ML 코드를 정리하고 오류를 방지하는데 유용하고, 정교한 데이터 전처리가 있는 workflow에 중요하다.