지금까지 불편한 점은?
import pandas as pd
red_wine = pd.read_csv('./data/winequality-red.csv', sep=';')
white_wine = pd.read_csv('./data/winequality-white.csv', 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']
레드/화이트 와인 분류기의 동작 Process
여기서 test_train_split은 Pipeline 내부가 아니다.
이 Pipeline을 코드로 구현한다면?
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
estimators = [('scaler', StandardScaler()),
('clf', DecisionTreeClassifier())]
pipe = Pipeline(estimators)
pipe.steps
#output:
[('scaler', StandardScaler()), ('clf', DecisionTreeClassifier())]
# setparams를 이용해 파라미터를 바꿀 수 있다
pipe.set_params(clf__max_depth=2)
pipe.set_params(clf__random_state=42)
# '스탭이름' + __(언더바 2개) + 속성이름
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=42, stratify=y)
pipe.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
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('Test Acc : ', accuracy_score(y_test, y_pred_test))
# output:
Train Acc : 0.9545891860688859
Test Acc : 0.9584615384615385