본문 바로가기
머신러닝

사이킷럿 파이프라인(Pipelines)

by mintee
728x90

사이킷럿 파이프라인(Pipelines)에 대해 배워봅시다.

 

 

from sklearn.pipeline import make_pipeline

위와 같이 사이킷런의 make_pipeline 함수를 사용하면 모델 학습의 코드를 간단하게 만들 수 있습니다.

공식 문서 : Pipeline

 

예시

 

먼저 필요한 라이브러리를 import합니다.

from category_encoders import OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

 

 

파이프라인을 사용하지 않았을 때

 

로지스틱 회귀모형으로 테스트셋을 예측하는 과정을 파이프라인을 사용하지 않고 원핫인코딩부터 표준화, 결측치 대체를 각 훈련, 검증, 테스트셋에 하고 예측을 하는 과정입니다.

enc = OneHotEncoder()
imp_mean = SimpleImputer()
scaler = StandardScaler()
model_lr = LogisticRegression(n_jobs=-1)

X_train_encoded = enc.fit_transform(X_train)
X_train_imputed = imp_mean.fit_transform(X_train_encoded)
X_train_scaled = scaler.fit_transform(X_train_imputed)
model_lr.fit(X_train_scaled, y_train)

X_val_encoded = enc.transform(X_val)
X_val_imputed = imp_mean.transform(X_val_encoded)
X_val_scaled = scaler.transform(X_val_imputed)

# score method: Return the mean accuracy on the given test data and labels
print('검증세트 정확도', model_lr.score(X_val_scaled, y_val))

X_test_encoded = enc.transform(X_test)
X_test_imputed = imp_mean.transform(X_test_encoded)
X_test_scaled = scaler.transform(X_test_imputed)

y_pred = model_lr.predict(X_test_scaled)

→ 검증세트 정확도 0.8185268651405527

 

 

이번에는 똑같은 과정을 파이프라인을 사용해서 해 봅시다.

 

pipe = make_pipeline(
    OneHotEncoder(), 
    SimpleImputer(), 
    StandardScaler(), 
    LogisticRegression(n_jobs=-1)
)
pipe.fit(X_train, y_train)

print('검증세트 정확도', pipe.score(X_val, y_val))

y_pred = pipe.predict(X_test)

→ 검증세트 정확도 0.8185268651405527

 

코드가 훨씬 짧아지고 가독성이 좋아집니다!!

이렇게 하면 정확도도 똑같이 나오는 똑같은 학습 과정을 매번 길게 쓰지 않고 편하게 할 수 있습니다!

 

파이프라인에서 모델의 파라미터 같은 정보를 확인하는 방식을 살펴 봅시다.

 

(아래 링크는 자세한 사용방법이 정리된 사이킷런의 공식문서입니다.)

6.1.1.1.2. Accessing steps

sklearn.pipeline의 named_steps 속성을 사용하면 파이프라인의 각 스텝에 접근이 가능합니다.

pipe.named_steps

 

로지스틱 함수에서 회귀계수의 영향력을 보는 막대그래프를 파이프라인을 사용하여 그려봅시다.

import matplotlib.pyplot as plt

model_lr = pipe.named_steps['logisticregression']
enc = pipe.named_steps['onehotencoder']
encoded_columns = enc.transform(X_val).columns
coefficients = pd.Series(model_lr.coef_[0], encoded_columns)
plt.figure(figsize=(10,30))
coefficients.sort_values().plot.barh();
728x90

'머신러닝' 카테고리의 다른 글

Partial Dependence Plot (PDP) 부분의존도그림  (4) 2021.06.25

댓글