(ML)Pipeline

지며리·2023년 2월 3일
0


파이프라인을 활용하여 전처리부터 label 예측까지 간소하게 코딩해보자

1. 머신러닝 파이프라인이란

  • 광의의 의미: 데이터 수집, 전처리, 모델 학습, 학습 모델 배포, 예측 등 머신러닝의 전체 과정을 순차적으로 처리하는 일련의 프로세스
  • 협의의 의미: 새로운 데이터가 들어왔을 때 이 데이터의 label을 예측하기까지 필요한 프로세스

2. Skleanrn의 Pipeline 클래스

  • 결측치 제거, 스케일링, 머신러닝모델 학습 등을 묶어서 한꺼번에 진행 가능
  • 파라미터를 조정하고 싶으면 pipe.set_params(모델명__하이퍼파라미터명 = 값) 사용 가능

데이터 로드

import pandas as pd
red_url = 'https://raw.githubusercontent.com/PinkWink/\
				ML_tutorial/master/dataset/winequality-red.csv'
white_url = 'https://raw.githubusercontent.com/PinkWink/\
				ML_tutorial/master/dataset/winequality-white.csv'

red_wine = pd.read_csv(red_url, sep = ';')
white_wine = pd.read_csv(white_url, sep = ';')

red_wine['color'] =1 
white_wine['color']=0

wine = pd.concat([red_wine, white_wine])

X = wine.drop(['color'], axis = 1)
y = wine['color']

파이프라인 구축

from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler

estimators = [
    ('scaler', StandardScaler()),
    ('clf', DecisionTreeClassifier())
]

pipe = Pipeline(estimators)

하이퍼파라미터 설정

pipe.set_params(clf__max_depth = 2)
pipe.set_params(clf__random_state = 13)

fit -> predict

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,\
												random_state = 13, stratify = y)

# 스케일러와 학습을 순차적으로 한큐에 진행
pipe.fit(X_train, y_train)

from sklearn.metrics import accuracy_score

# 그다음 바로 predict 적용 가능
y_pred_tr = pipe.predict(X_train)
y_pred_test = pipe.predict(X_test)

print('Train Acc: ', accuracy_score(y_train, y_pred_tr))
print('Train Acc: ', accuracy_score(y_test, y_pred_test))


3. 참고하면 좋은 자료

파이프라인의 각 스텝에 접근하는 방법

  • 특정스텝에 대한 코딩(ex: 로지스틱 함수에서 회귀계수 영향력 보는 막대그래프 그리기)을 할 때 유용

파이프라인 커스터마이징하기

  • 사이킷런의 인스턴스가 아닌 다른 인스턴스 사용, 하이퍼파라미터 튜닝에 유용
profile
호지자불여락지자

0개의 댓글