scikit-learn의 pipeline은 데이터 전처리 단계와 모델 학습 단계를 하나의 객체로 묶어 순차적으로 실행하도록 돕는 라이브러리다.
자동화와 교차 검증시 데이터 누수를 방지하는 역할을 한다.
pipeline을 사용한 것과 사용하지 않은것을 간략하게 도식화 하면 다음과 같다.
X->변수 선택 -> X_select -> 표준화 -> X_standard + y -> 모델 학습
pipeline은 여기서 변수 선택부터 모델 클래스까지를 묶어주는 라이브러리로
(변수 선택, 표준화, 클래스)
X,y -> pipeline -> 모델 학습
코드의 구조도 훨씬 간략해지며 pipeline의 구조 자체도 쉽기에 재사용성도 올라가게 된다.
데이터 누수 방지
데이터 누수란 모델 학습(train)과정에 검증 또는 테스트(test) 데이터의 정보가 포함되어 모델 성능이 비정상적으로 높게 평가되는 현상으로 GridSearchCV나 cross_val_score를 사용하기 전에 전체 데이터셋에 StandardScaler를 적용하면 훈련 데이터뿐만 아니라 검증 데이터의 평균과 표준편차까지 학습에 반영되게 된다.
이것을 pipeline을 사용하게 되면 교차 검증의 각 폴드마다 훈련용 폴드 데이터로만 스케일러를 fit하고 검증용 폴드 데이터에는 해당 스케일러 중 transform만 적용하게 된다.
예시 코드
from xgboost import XGBClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
# 'imputer' (변환기) -> 'scaler' (변환기) -> 'model' (추정기/모델)
pipe_xgb = Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler()),
('model', XGBClassifier(use_label_encoder=False, eval_metric='logloss'))
])
xgboost를 사용한 예시 코드
pipe_xgb = Pipeline([
('imputer', SimpleImputer(strategy='median')), # 1단계
('scaler', StandardScaler()), # 2단계
('model', XGBClassifier( # 3단계
use_label_encoder=False,
eval_metric='logloss',
random_state=42
)) # 3단계
])
pipe_xgb.fit(X_train, y_train)
pipe_cat = Pipeline([
('imputer', SimpleImputer(strategy='median')), # 1단계
('scaler', StandardScaler()), # 2단계
('model', CatBoostClassifier( # 3단계
verbose=0,
random_state=42
))
])
pipe_cat.fit(X_train, y_train)
catboost와 xgboost를 사용한 예제 코드
eval_metric이라는 항목이 있는데 이것은 분류 문제에서 이진분류인지, 다중분류인지에 따라 지정하면 된다.
logloss : 이진분류, 모델이 예측한 확률을 평가하며 실제 정담 (0 or 1)에 가까운 확률을 예측할수록 점수가 낮아진다.
mlogloss : 다중 분류, 다중 클래스에서의 logloss이며 클래스의 개수에 따라 logloss로 지정해도 mlogloss로 계산해주는 경우도 있다.
그 외에는 회귀와 순위 문제일때는 또 다른 지표를 사용한다.
회귀 문제 : rmse, mae, rmsle, mape
순위 문제 : ndcg, map
'공부 정리 > 라이브러리' 카테고리의 다른 글
| smote? smotenc? smote-tomek link? (0) | 2025.10.24 |
|---|