본문 바로가기

Study/Introduction to ML with python - 한빛

[Book] 6. 알고리즘 체인과 파이프라인 - (2)

Book Title : Introduction to Machine Learning with Python

- 파이썬 라이브러리를 활용한 머신러닝 -

지은이 : 안드레아스 뮐러, 세라 가이도

옮긴이 : 박해선

출판사 : 한빛미디어

 

코드 출처

https://github.com/rickiepark/introduction_to_ml_with_python

 

GitHub - rickiepark/introduction_to_ml_with_python: 도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의

도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의 주피터 노트북과 코드입니다. Contribute to rickiepark/introduction_to_ml_with_python development by creating an account on GitHub.

github.com


6.4 파이프라인 인터페이스

  • Pipeline은 특성 추출, 특성 선택, 스케일 변경 총 네 단계를 포함하는 파이프라인을 만들 수 있음
  • 파이프라인에 들어갈 추정기는 마지막 단계를 제외하고는 모두 transform 메서드를 가지고 있어야 함

6.4.1 make_pipeline을 사용한 파이프라인 생성

  • - pipe_long과 pipe_short는 정확히 똑같은 작업을 수행
  • - pipe_short는 단계의 이름을 자동으로 생성, steps속성에서 확인가능
from sklearn.pipeline import make_pipeline

pipe_long = Pipeline([('scaler', MinMaxScaler()), ('svm', SVC(C =100))])

pipe_short = make_pipeline(MinMaxScaler(), SVC(C = 100))

print(pipe_short.steps)
# [('minmaxscaler', MinMaxScaler()), ('svc', SVC(C=100))]

 

  • 파이프라인 단계 중 하나의 속성을 확인하고 싶을 때 named_steps 사용
  • pca에서 추출한 주성분 확인
cancer = load_breast_cancer()
pipe.fit(cancer.data)

components = pipe.named_steps['pca'].components_
print("components.shape : ", components.shape)
# components.shape :  (2, 30)

 

  • Pipeline과 GridSearchCV 같이 사용
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter = 1000))
param_grid = {'logisticregression__C' : [0.01, 0.1, 1, 10, 100]}
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state = 4)
grid = GridSearchCV(pipe, param_grid, cv = 5)
grid.fit(X_train, y_train)

print("best_esimator", grid.best_estimator_)
# best_esimator Pipeline(steps=[('standardscaler', StandardScaler()),
                #('logisticregression', LogisticRegression(C=1, max_iter=1000))])

# named_steps 속성을 사용해 logisticregression 단계 접근
print("로지스틱 회귀 단계", grid.best_estimator_.named_steps['logisticregression'])
# 로지스틱 회귀 단계 LogisticRegression(C=1, max_iter=1000)