본문 바로가기
파이썬 라이브러리를 활용한 머신러닝

Algorithm Chains and Pipelines - General Pipeline Interface

by 일일과제중 2019. 12. 19.
반응형

 

파이프라인 인터페이스

 

Pipeline은 사실 전처리나 분류에 극한하지 않고 어떤 추정기와도 연결할 수 있습니다.

 

pipeline.steps는 튜플의 리스트라서 pipeline.step[0][1]은 첫 번째 추정기이고 pipeline.steps[1][1]은 두 번째 추정기가 되는 식입니다. 

 

예를 들어 특성 추출, 특성 선택, 스케일 변경, 분류의 총 네 단계를 포함하는 파이프라인을 만들 수 있습니다.

 

비슷하게 마지막 단계가 분류 대신 회귀나 군집이 될 수 있습니다. 

 

 

파이프라인에 들어갈 추정기는 마지막 단계를 제외하고는 모두 transform 메서드를 가지고 있어야 합니다. 

 

그래서 다음 단계를 위한 새로운 데이터 표현을 만들 수 있어야 합니다. 

 

 

Training process :

 

Pipeline.fit 메서드가 실행되는 동안, 파이프라인은 각 단계에서 이전 단계의 transform의 출력을 입력으로 받아 fit과 transform 메서드를 차례로 호출합니다. 그리고 마지막 단계는 fit 메서드만 호출합니다. 

 

그림1

 

 

Prediction process : 

 

Pipeline을 사용해서 예측할 때는, 비슷한 방식으로 마지막 단계 이전까지 transform 메서드를 호출한 다음, 마지막 단계에서 predict를 호출합니다. 

 

그림2

 

 

파이프라인 생성

 

make_pipeline 함수는 각 단계 이름에 해당 파이썬 클래스의 이름을 부여한 파이프라인을 만들어줍니다. 

 

from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import SVC

# 표준 방법
pipe_long = Pipeline([('scaler', MinMaxScaler()), ("svm", SVC(C=100))])

# 간소화된 방법
pipe_short = make_pipeline(MinMaxScaler(), SVC(C=100))
print("파이프라인 단계:\n", pipe_short.steps)

그림3

 

 

단계 속성에 접근하기

 

종종 파이프라인의 단계 중 하나의 속성을 확인하고 싶을 때가 있습니다.

 

단계 이름을 키로 가진 딕셔너리인 named_steps 속성을 사용하면 파이프라인의 각 단계에 쉽게 접근할 수 있습니다.

 

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

pipe = make_pipeline(StandardScaler(), PCA(n_components=2), StandardScaler())
print("파이프라인 단계:\n", pipe.steps)

그림4

 

 

from sklearn.datasets import load_breast_cancer

cancer = load_breast_cancer()

# cancer 데이터셋에 앞서 만든 파이프라인을 적용합니다.
pipe.fit(cancer.data)

#'pca' 단계의 두 개 주성분을 추출합니다.
components = pipe.named_steps["pca"].components_
print("components.shape:", components.shape)

components.shape: (2, 30)

 

 

파이썬 라이브러리를 활용한 머신러닝 책과 성균관대학교 강석호 교수님 수업 내용을 바탕으로 요약 작성되었습니다.

반응형

댓글